espconn_mbedtls.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. /*
  2. * ESPRSSIF MIT License
  3. *
  4. * Copyright (c) 2016 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
  5. *
  6. * Permission is hereby granted for use on ESPRESSIF SYSTEMS ESP8266 only, in which case,
  7. * it is free of charge, to any person obtaining a copy of this software and associated
  8. * documentation files (the "Software"), to deal in the Software without restriction, including
  9. * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
  10. * and/or sell copies of the Software, and to permit persons to whom the Software is furnished
  11. * to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in all copies or
  14. * substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  18. * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  19. * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  20. * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  21. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. *
  23. */
  24. #if !defined(ESPCONN_MBEDTLS)
  25. #if !defined(MBEDTLS_CONFIG_FILE)
  26. #include "mbedtls/config.h"
  27. #else
  28. #include MBEDTLS_CONFIG_FILE
  29. #endif
  30. #include "mbedtls/ssl_internal.h"
  31. #include "mem.h"
  32. #include "lauxlib.h"
  33. #ifdef MEMLEAK_DEBUG
  34. static const char mem_debug_file[] ICACHE_RODATA_ATTR = __FILE__;
  35. #endif
  36. #include "sys/socket.h"
  37. #include "sys/espconn_mbedtls.h"
  38. #include "lwip/app/espconn_tcp.h"
  39. static os_event_t lwIPThreadQueue[lwIPThreadQueueLen];
  40. static bool lwIPThreadFlag = false;
  41. extern espconn_msg *plink_active;
  42. static espconn_msg *plink_server = NULL;
  43. static pmbedtls_parame def_certificate = NULL;
  44. static pmbedtls_parame def_private_key = NULL;
  45. /* Implementation that should never be optimized out by the compiler */
  46. static void mbedtls_zeroize( void *v, size_t n ) {
  47. volatile unsigned char *p = v;
  48. while( n-- ) *p++ = 0;
  49. }
  50. static pmbedtls_parame mbedtls_parame_new(size_t capacity)
  51. {
  52. pmbedtls_parame rb = (pmbedtls_parame)os_zalloc(sizeof(mbedtls_parame));
  53. if (rb && capacity != 0) {
  54. rb->parame_datalen = capacity;
  55. rb->parame_data = (uint8*)os_zalloc(rb->parame_datalen + 1);
  56. if (rb->parame_data) {
  57. } else {
  58. os_free(rb);
  59. rb = NULL;
  60. }
  61. }
  62. return rb;
  63. }
  64. static void mbedtls_parame_free(pmbedtls_parame *fp)
  65. {
  66. lwIP_ASSERT(fp);
  67. lwIP_ASSERT(*fp);
  68. os_free((*fp)->parame_data);
  69. os_free(*fp);
  70. *fp = NULL;
  71. }
  72. static unsigned char* mbedtls_get_default_obj(uint32 *sec, uint32 type, uint32 *len)
  73. {
  74. const char* const begin = "-----BEGIN";
  75. unsigned char *parame_data = NULL;
  76. pmbedtls_parame mbedtls_obj = NULL;
  77. if (type == ESPCONN_PK) {
  78. mbedtls_obj = def_private_key;
  79. } else {
  80. mbedtls_obj = def_certificate;
  81. }
  82. if (mbedtls_obj->parame_sec != 0) {
  83. #define DATA_OFFSET 4
  84. uint32 data_len = mbedtls_obj->parame_datalen;
  85. parame_data = (unsigned char *)os_zalloc(data_len + DATA_OFFSET);
  86. if (parame_data) {
  87. spi_flash_read(mbedtls_obj->parame_sec * FLASH_SECTOR_SIZE, (uint32*)parame_data, data_len);
  88. /*
  89. * Determine buffer content. Buffer contains either one DER certificate or
  90. * one or more PEM certificates.
  91. */
  92. if ((char*)os_strstr(parame_data, begin) != NULL) {
  93. data_len ++;
  94. parame_data[data_len - 1] = '\0';
  95. }
  96. }
  97. *len = data_len;
  98. } else {
  99. parame_data = mbedtls_obj->parame_data;
  100. *len = mbedtls_obj->parame_datalen;
  101. }
  102. *sec = mbedtls_obj->parame_sec;
  103. return parame_data;
  104. }
  105. static int mbedtls_setsockopt(int sock_id, int level, int optname, int optval)
  106. {
  107. return setsockopt(sock_id, level, optname, (void*)&optval, sizeof(optval));
  108. }
  109. static int mbedtls_keep_alive(int sock_id, int onoff, int idle, int intvl, int cnt)
  110. {
  111. int ret = ERR_OK;
  112. if (onoff == 0)
  113. return mbedtls_setsockopt(sock_id, SOL_SOCKET, SO_KEEPALIVE, onoff);;
  114. ret = mbedtls_setsockopt(sock_id, SOL_SOCKET, SO_KEEPALIVE, onoff);
  115. lwIP_REQUIRE_NOERROR(ret, exit);
  116. ret = mbedtls_setsockopt(sock_id, IPPROTO_TCP, TCP_KEEPALIVE, onoff);
  117. lwIP_REQUIRE_NOERROR(ret, exit);
  118. ret = mbedtls_setsockopt(sock_id, IPPROTO_TCP, TCP_KEEPIDLE, idle);
  119. lwIP_REQUIRE_NOERROR(ret, exit);
  120. ret = mbedtls_setsockopt(sock_id, IPPROTO_TCP, TCP_KEEPINTVL, intvl);
  121. lwIP_REQUIRE_NOERROR(ret, exit);
  122. ret = mbedtls_setsockopt(sock_id, IPPROTO_TCP, TCP_KEEPCNT, cnt);
  123. lwIP_REQUIRE_NOERROR(ret, exit);
  124. exit:
  125. return ret;
  126. }
  127. static pmbedtls_espconn mbedtls_espconn_new(void)
  128. {
  129. pmbedtls_espconn mbedtls_conn = NULL;
  130. mbedtls_conn = (pmbedtls_espconn)os_zalloc(sizeof(mbedtls_espconn));
  131. if (mbedtls_conn) {
  132. mbedtls_conn->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp));
  133. if (mbedtls_conn->proto.tcp == NULL) {
  134. os_free(mbedtls_conn);
  135. mbedtls_conn = NULL;
  136. }
  137. }
  138. return mbedtls_conn;
  139. }
  140. static void mbedtls_espconn_free(pmbedtls_espconn *mbedtlsconn)
  141. {
  142. lwIP_ASSERT(mbedtlsconn);
  143. lwIP_ASSERT(*mbedtlsconn);
  144. os_free((*mbedtlsconn)->proto.tcp);
  145. (*mbedtlsconn)->proto.tcp = NULL;
  146. os_free((*mbedtlsconn));
  147. *mbedtlsconn = NULL;
  148. }
  149. static pmbedtls_session mbedtls_session_new(void)
  150. {
  151. pmbedtls_session session = (pmbedtls_session)os_zalloc(sizeof(mbedtls_session));
  152. if (session) {
  153. mbedtls_x509_crt_init(&session->cacert);
  154. mbedtls_x509_crt_init(&session->clicert);
  155. mbedtls_pk_init(&session->pkey);
  156. // mbedtls_entropy_init(&session->entropy);
  157. }
  158. return session;
  159. }
  160. static void mbedtls_session_free(pmbedtls_session *session)
  161. {
  162. lwIP_ASSERT(session);
  163. lwIP_ASSERT(*session);
  164. mbedtls_x509_crt_free(&(*session)->cacert);
  165. mbedtls_x509_crt_free(&(*session)->clicert);
  166. mbedtls_pk_free(&(*session)->pkey);
  167. // mbedtls_entropy_free(&(*session)->entropy);
  168. os_free(*session);
  169. *session = NULL;
  170. }
  171. static pmbedtls_msg mbedtls_msg_new(void)
  172. {
  173. pmbedtls_msg msg = (pmbedtls_msg)os_zalloc( sizeof(mbedtls_msg));
  174. if (msg) {
  175. os_bzero(msg, sizeof(mbedtls_msg));
  176. msg->psession = mbedtls_session_new();
  177. if (msg->psession) {
  178. mbedtls_net_init(&msg->fd);
  179. mbedtls_ssl_init(&msg->ssl);
  180. mbedtls_ssl_config_init(&msg->conf);
  181. mbedtls_ctr_drbg_init(&msg->ctr_drbg);
  182. mbedtls_entropy_init(&msg->entropy);
  183. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && defined(SSL_MAX_FRAGMENT_LENGTH_CODE)
  184. mbedtls_ssl_conf_max_frag_len(&msg->conf, SSL_MAX_FRAGMENT_LENGTH_CODE);
  185. #endif
  186. } else {
  187. os_free(msg);
  188. msg = NULL;
  189. }
  190. }
  191. return msg;
  192. }
  193. static void mbedtls_msg_server_step(pmbedtls_msg msg)
  194. {
  195. lwIP_ASSERT(msg);
  196. /*to prevent memory leaks, ensure that each allocated is deleted at every handshake*/
  197. if (msg->psession) {
  198. mbedtls_session_free(&msg->psession);
  199. }
  200. mbedtls_entropy_free(&msg->entropy);
  201. mbedtls_ssl_free(&msg->ssl);
  202. mbedtls_ssl_config_free(&msg->conf);
  203. mbedtls_ctr_drbg_free(&msg->ctr_drbg);
  204. /*New connection ensure that each initial for next handshake */
  205. os_bzero(msg, sizeof(mbedtls_msg));
  206. msg->psession = mbedtls_session_new();
  207. if (msg->psession) {
  208. mbedtls_net_init(&msg->fd);
  209. mbedtls_ssl_init(&msg->ssl);
  210. mbedtls_ssl_config_init(&msg->conf);
  211. mbedtls_ctr_drbg_init(&msg->ctr_drbg);
  212. mbedtls_entropy_init(&msg->entropy);
  213. }
  214. }
  215. static void mbedtls_msg_free(pmbedtls_msg *msg)
  216. {
  217. lwIP_ASSERT(msg);
  218. lwIP_ASSERT(*msg);
  219. /*to prevent memory leaks, ensure that each allocated is deleted at every handshake*/
  220. if ((*msg)->psession) {
  221. mbedtls_session_free(&((*msg)->psession));
  222. }
  223. mbedtls_entropy_free(&(*msg)->entropy);
  224. mbedtls_ssl_free(&(*msg)->ssl);
  225. mbedtls_ssl_config_free(&(*msg)->conf);
  226. mbedtls_ctr_drbg_free(&(*msg)->ctr_drbg);
  227. os_free(*msg);
  228. *msg = NULL;
  229. }
  230. static espconn_msg* mbedtls_msg_find(int sock)
  231. {
  232. espconn_msg *plist = NULL;
  233. pmbedtls_msg msg = NULL;
  234. for (plist = plink_active; plist != NULL; plist = plist->pnext) {
  235. if(plist->pssl != NULL) {
  236. msg = plist->pssl;
  237. if (msg->fd.fd == sock)
  238. return plist;
  239. }
  240. }
  241. return NULL;
  242. }
  243. static bool mbedtls_handshake_result(const pmbedtls_msg Threadmsg)
  244. {
  245. if (Threadmsg == NULL)
  246. return false;
  247. if (Threadmsg->ssl.state == MBEDTLS_SSL_HANDSHAKE_OVER) {
  248. if (ssl_client_options.cert_ca_sector.flag) {
  249. int ret = mbedtls_ssl_get_verify_result(&Threadmsg->ssl);
  250. if (ret != 0) {
  251. char vrfy_buf[512];
  252. os_memset(vrfy_buf, 0, sizeof(vrfy_buf)-1);
  253. mbedtls_x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), "!", ret);
  254. os_printf("%s\n", vrfy_buf);
  255. Threadmsg->verify_result = ret;
  256. return false;
  257. } else
  258. return true;
  259. } else
  260. return true;
  261. } else
  262. return false;
  263. }
  264. static void mbedtls_fail_info(espconn_msg *pinfo, int ret)
  265. {
  266. pmbedtls_msg TLSmsg = NULL;
  267. lwIP_REQUIRE_ACTION(pinfo,exit,);
  268. TLSmsg = pinfo->pssl;
  269. lwIP_REQUIRE_ACTION(TLSmsg,exit,);
  270. /* Don't complain to console if we've been told the other end is hanging
  271. * up. That's entirely normal and not worthy of the confusion it sows!
  272. */
  273. if (ret != MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  274. if (TLSmsg->quiet) {
  275. os_printf("client's data invalid protocol\n");
  276. mbedtls_ssl_close_notify(&TLSmsg->ssl);
  277. } else {
  278. os_printf("client handshake failed!\n");
  279. }
  280. }
  281. os_printf("Reason:[-0x%2x]\n",-ret);
  282. /*Error code convert*/
  283. ret = -ret;
  284. if ((ret & 0xFF) != 0) {
  285. ret = ((ret >> 8) + ret);
  286. } else {
  287. ret >>= 8;
  288. }
  289. pinfo->hs_status = -ret;
  290. pinfo->pespconn->state = ESPCONN_CLOSE;
  291. mbedtls_net_free(&TLSmsg->fd);
  292. exit:
  293. return;
  294. }
  295. static void mbedtls_handshake_succ(mbedtls_ssl_context *ssl)
  296. {
  297. lwIP_ASSERT(ssl);
  298. if( ssl->handshake )
  299. {
  300. mbedtls_ssl_handshake_free( ssl );
  301. mbedtls_ssl_transform_free( ssl->transform_negotiate );
  302. mbedtls_ssl_session_free( ssl->session_negotiate );
  303. os_free( ssl->handshake );
  304. os_free( ssl->transform_negotiate );
  305. os_free( ssl->session_negotiate );
  306. ssl->handshake = NULL;
  307. ssl->transform_negotiate = NULL;
  308. ssl->session_negotiate = NULL;
  309. }
  310. if( ssl->session )
  311. {
  312. mbedtls_ssl_session_free( ssl->session );
  313. os_free( ssl->session );
  314. ssl->session = NULL;
  315. }
  316. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  317. if( ssl->hostname != NULL )
  318. {
  319. mbedtls_zeroize( ssl->hostname, os_strlen( ssl->hostname ) );
  320. os_free( ssl->hostname );
  321. ssl->hostname = NULL;
  322. }
  323. #endif
  324. }
  325. /******************************************************************************
  326. * FunctionName : espconn_ssl_reconnect
  327. * Description : reconnect with host
  328. * Parameters : arg -- Additional argument to pass to the callback function
  329. * Returns : none
  330. *******************************************************************************/
  331. static void espconn_close_internal(void *arg, netconn_event event_type)
  332. {
  333. espconn_msg *pssl_recon = arg;
  334. struct espconn *espconn = NULL;
  335. sint8 ssl_reerr = 0;
  336. sint16 hs_status = 0;
  337. lwIP_ASSERT(pssl_recon);
  338. espconn = pssl_recon->preverse;
  339. ssl_reerr = pssl_recon->pcommon.err;
  340. hs_status = pssl_recon->hs_status;
  341. if (espconn != NULL) {
  342. //clear pcommon parameters.
  343. pssl_recon->pcommon.write_flag = false;
  344. pssl_recon->pcommon.ptrbuf = NULL;
  345. pssl_recon->pcommon.cntr = 0;
  346. pssl_recon->pcommon.err = 0;
  347. } else {
  348. espconn = pssl_recon->pespconn;
  349. os_free(pssl_recon);
  350. pssl_recon = NULL;
  351. }
  352. espconn_kill_oldest_pcb();
  353. switch (event_type) {
  354. case NETCONN_EVENT_ERROR:
  355. if (hs_status == ESPCONN_OK)
  356. ESPCONN_EVENT_ERROR(espconn, ssl_reerr);
  357. else
  358. ESPCONN_EVENT_ERROR(espconn, hs_status);
  359. break;
  360. case NETCONN_EVENT_CLOSE:
  361. if (hs_status == ESPCONN_OK)
  362. ESPCONN_EVENT_CLOSED(espconn);
  363. else
  364. ESPCONN_EVENT_ERROR(espconn, hs_status);
  365. break;
  366. default:
  367. break;
  368. }
  369. }
  370. /******************************************************************************
  371. * FunctionName : espconn_ssl_read_param_from_flash
  372. * Description : load parameter from flash, toggle use two sector by flag value.
  373. * Parameters : param--the parame point which write the flash
  374. * Returns : none
  375. *******************************************************************************/
  376. static bool espconn_ssl_read_param_from_flash(void *param, uint16 len, int32 offset, mbedtls_auth_type auth_type)
  377. {
  378. if (param == NULL || (len + offset) > ESPCONN_SECURE_MAX_SIZE) {
  379. return false;
  380. }
  381. uint32 FILE_PARAM_START_SEC = 0x3B;
  382. switch (auth_type) {
  383. case ESPCONN_CERT_AUTH:
  384. FILE_PARAM_START_SEC = ssl_client_options.cert_ca_sector.sector;
  385. break;
  386. case ESPCONN_CERT_OWN:
  387. case ESPCONN_PK:
  388. FILE_PARAM_START_SEC = ssl_client_options.cert_req_sector.sector;
  389. break;
  390. default:
  391. return false;
  392. }
  393. spi_flash_read(FILE_PARAM_START_SEC * 4096 + offset, param, len);
  394. return true;
  395. }
  396. static bool
  397. espconn_mbedtls_parse(mbedtls_msg *msg, mbedtls_auth_type auth_type, const uint8_t *buf, size_t len)
  398. {
  399. int ret;
  400. switch (auth_type) {
  401. case ESPCONN_CERT_AUTH:
  402. ret = mbedtls_x509_crt_parse(&msg->psession->cacert, buf, len);
  403. break;
  404. case ESPCONN_CERT_OWN:
  405. ret = mbedtls_x509_crt_parse(&msg->psession->clicert, buf, len);
  406. break;
  407. case ESPCONN_PK:
  408. ret = mbedtls_pk_parse_key(&msg->psession->pkey, buf, len, NULL, 0);
  409. break;
  410. default:
  411. return false;
  412. }
  413. exit:
  414. return (ret >= 0);
  415. }
  416. /*
  417. * Three-way return:
  418. * 0 for no commitment, -1 to fail the connection, 1 on success
  419. */
  420. static int
  421. nodemcu_tls_cert_get(mbedtls_msg *msg, mbedtls_auth_type auth_type)
  422. {
  423. int cbref;
  424. int cbarg;
  425. int loop = 0;
  426. switch(auth_type) {
  427. case ESPCONN_CERT_AUTH:
  428. loop = 1;
  429. cbarg = 1;
  430. cbref = ssl_client_options.cert_verify_callback;
  431. break;
  432. case ESPCONN_PK:
  433. loop = 0;
  434. cbarg = 0;
  435. cbref = ssl_client_options.cert_auth_callback;
  436. break;
  437. case ESPCONN_CERT_OWN:
  438. loop = 1;
  439. cbarg = 1;
  440. cbref = ssl_client_options.cert_auth_callback;
  441. break;
  442. default:
  443. return 0;
  444. }
  445. if (cbref == LUA_NOREF) {
  446. return 0;
  447. }
  448. lua_State *L = lua_getstate();
  449. do {
  450. lua_rawgeti(L, LUA_REGISTRYINDEX, cbref);
  451. lua_pushinteger(L, cbarg);
  452. if (lua_pcall(L, 1, 1, 0) != 0) {
  453. /* call failure; fail the connection attempt */
  454. lua_pop(L, 1); /* pcall will have pushed an error message */
  455. return -1;
  456. }
  457. if (lua_isnil(L, -1) || (lua_isboolean(L,-1) && lua_toboolean(L,-1) == false)) {
  458. /* nil or false return; stop iteration */
  459. lua_pop(L, 1);
  460. break;
  461. }
  462. size_t resl;
  463. const char *res = lua_tolstring(L, -1, &resl);
  464. if (res == NULL) {
  465. /* conversion failure; fail the connection attempt */
  466. lua_pop(L, 1);
  467. return -1;
  468. }
  469. if (!espconn_mbedtls_parse(msg, auth_type, res, resl+1)) {
  470. /* parsing failure; fail the connction attempt */
  471. lua_pop(L, 1);
  472. return -1;
  473. }
  474. /*
  475. * Otherwise, parsing successful; if this is a loopy kind of
  476. * callback, then increment the argument and loop.
  477. */
  478. lua_pop(L, 1);
  479. cbarg++;
  480. } while (loop);
  481. return 1;
  482. }
  483. static bool mbedtls_msg_info_load(mbedtls_msg *msg, mbedtls_auth_type auth_type)
  484. {
  485. const char* const begin = "-----BEGIN";
  486. const char* const type_name = "private_key";
  487. #define FILE_OFFSET 4
  488. int ret = 0;
  489. int32 offerset = 0;
  490. uint8* load_buf = NULL;
  491. size_t load_len = 0;
  492. file_param file_param;
  493. bzero(&file_param, sizeof(file_param));
  494. again:
  495. espconn_ssl_read_param_from_flash(&file_param.file_head, sizeof(file_head), offerset, auth_type);
  496. file_param.file_offerset = offerset;
  497. os_printf("%s %d, type[%s],length[%d]\n", __FILE__, __LINE__, file_param.file_head.file_name, file_param.file_head.file_length);
  498. if (file_param.file_head.file_length == 0xFFFF) {
  499. return false;
  500. } else {
  501. /*Optional is load the private key*/
  502. if (auth_type == ESPCONN_PK && os_memcmp(&file_param.file_head.file_name, type_name, os_strlen(type_name)) != 0) {
  503. offerset += sizeof(file_head) + file_param.file_head.file_length;
  504. goto again;
  505. }
  506. /*Optional is load the cert*/
  507. if (auth_type == ESPCONN_CERT_OWN && os_memcmp(file_param.file_head.file_name, "certificate", os_strlen("certificate")) != 0) {
  508. offerset += sizeof(file_head) + file_param.file_head.file_length;
  509. goto again;
  510. }
  511. load_buf = (uint8_t *) os_zalloc( file_param.file_head.file_length + FILE_OFFSET);
  512. if (load_buf == NULL) {
  513. return false;
  514. }
  515. offerset = sizeof(file_head) + file_param.file_offerset;
  516. espconn_ssl_read_param_from_flash(load_buf, file_param.file_head.file_length, offerset, auth_type);
  517. }
  518. load_len = file_param.file_head.file_length;
  519. /*
  520. * Determine buffer content. Buffer contains either one DER certificate or
  521. * one or more PEM certificates.
  522. */
  523. if ((char*)os_strstr(load_buf, begin) != NULL) {
  524. load_len += 1;
  525. load_buf[load_len - 1] = '\0';
  526. }
  527. ret = espconn_mbedtls_parse(msg, auth_type, load_buf, load_len) ? 0 : -1;
  528. exit:
  529. os_free(load_buf);
  530. if (ret < 0) {
  531. return false;
  532. } else {
  533. return true;
  534. }
  535. }
  536. static void
  537. mbedtls_dbg(void *p, int level, const char *file, int line, const char *str)
  538. {
  539. os_printf("TLS<%d> (heap=%d): %s:%d %s", level, system_get_free_heap_size(), file, line, str);
  540. }
  541. static bool mbedtls_msg_config(mbedtls_msg *msg)
  542. {
  543. bool load_flag = false;
  544. int ret = ESPCONN_OK;
  545. /* Load upstream default configs */
  546. ret = mbedtls_ssl_config_defaults(&msg->conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);
  547. lwIP_REQUIRE_NOERROR(ret, exit);
  548. ret = mbedtls_ssl_setup(&msg->ssl, &msg->conf);
  549. lwIP_REQUIRE_NOERROR(ret, exit);
  550. /*Initialize the RNG and the session data*/
  551. ret = mbedtls_ctr_drbg_seed(&msg->ctr_drbg, mbedtls_entropy_func, &msg->entropy, "client", 6);
  552. lwIP_REQUIRE_NOERROR(ret, exit);
  553. /*Load the certificate and private RSA key*/
  554. ret = 0;
  555. if (ssl_client_options.cert_auth_callback != LUA_NOREF) {
  556. ret = nodemcu_tls_cert_get(msg, ESPCONN_PK);
  557. switch(ret) {
  558. case 0: break;
  559. case -1: ret = ESPCONN_ABRT; goto exit;
  560. case 1: switch(nodemcu_tls_cert_get(msg, ESPCONN_CERT_OWN)) {
  561. case -1: ret = ESPCONN_ABRT; goto exit;
  562. case 0: break;
  563. case 1:
  564. ret = mbedtls_ssl_conf_own_cert(&msg->conf, &msg->psession->clicert, &msg->psession->pkey);
  565. lwIP_REQUIRE_ACTION(ret == 0, exit, ret = ESPCONN_ABRT);
  566. }
  567. }
  568. }
  569. if (ret == 0 && ssl_client_options.cert_req_sector.flag) {
  570. load_flag = mbedtls_msg_info_load(msg, ESPCONN_CERT_OWN);
  571. lwIP_REQUIRE_ACTION(load_flag, exit, ret = ESPCONN_MEM);
  572. load_flag = mbedtls_msg_info_load(msg, ESPCONN_PK);
  573. lwIP_REQUIRE_ACTION(load_flag, exit, ret = ESPCONN_MEM);
  574. ret = mbedtls_ssl_conf_own_cert(&msg->conf, &msg->psession->clicert, &msg->psession->pkey);
  575. lwIP_REQUIRE_ACTION(ret == 0, exit, ret = ESPCONN_ABRT);
  576. }
  577. ret = 0;
  578. /*Load the trusted CA*/
  579. if (ssl_client_options.cert_verify_callback != LUA_NOREF) {
  580. ret = nodemcu_tls_cert_get(msg, ESPCONN_CERT_AUTH);
  581. switch(ret) {
  582. case 0: break;
  583. case -1: ret = ESPCONN_ABRT; goto exit;
  584. case 1:
  585. mbedtls_ssl_conf_authmode(&msg->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  586. mbedtls_ssl_conf_ca_chain(&msg->conf, &msg->psession->cacert, NULL);
  587. break;
  588. }
  589. }
  590. if(ret == 0 && ssl_client_options.cert_ca_sector.flag) {
  591. load_flag = mbedtls_msg_info_load(msg, ESPCONN_CERT_AUTH);
  592. lwIP_REQUIRE_ACTION(load_flag, exit, ret = ESPCONN_MEM);
  593. mbedtls_ssl_conf_authmode(&msg->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  594. mbedtls_ssl_conf_ca_chain(&msg->conf, &msg->psession->cacert, NULL);
  595. } else if (ret == 0) {
  596. /*
  597. * OPTIONAL is not optimal for security, but makes interop easier in this session
  598. * This gets overridden below if appropriate.
  599. */
  600. mbedtls_ssl_conf_authmode(&msg->conf, MBEDTLS_SSL_VERIFY_NONE);
  601. }
  602. ret = 0;
  603. mbedtls_ssl_conf_rng(&msg->conf, mbedtls_ctr_drbg_random, &msg->ctr_drbg);
  604. mbedtls_ssl_conf_dbg(&msg->conf, mbedtls_dbg, NULL);
  605. mbedtls_ssl_set_bio(&msg->ssl, &msg->fd, mbedtls_net_send, mbedtls_net_recv, NULL);
  606. exit:
  607. if (ret != 0) {
  608. return false;
  609. } else {
  610. return true;
  611. }
  612. }
  613. int espconn_mbedtls_parse_internal(int socket, sint8 error)
  614. {
  615. int ret = ERR_OK;
  616. bool config_flag = false;
  617. espconn_msg *Threadmsg = NULL;
  618. pmbedtls_msg TLSmsg = NULL;
  619. Threadmsg = mbedtls_msg_find(socket);
  620. lwIP_REQUIRE_ACTION(Threadmsg, exit, ret = ERR_MEM);
  621. TLSmsg = Threadmsg->pssl;
  622. lwIP_REQUIRE_ACTION(TLSmsg, exit, ret = ERR_MEM);
  623. if (error == ERR_OK) {
  624. if (TLSmsg->quiet) {
  625. uint8 *TheadBuff = NULL;
  626. size_t ThreadLen = MBEDTLS_SSL_PLAIN_ADD;
  627. TheadBuff = (uint8 *)os_zalloc(ThreadLen + 1);
  628. lwIP_REQUIRE_ACTION(TheadBuff, exit, ret = ERR_MEM);
  629. do {
  630. os_memset(TheadBuff, 0, ThreadLen);
  631. ret = mbedtls_ssl_read(&TLSmsg->ssl, TheadBuff, ThreadLen);
  632. if (ret > 0) {
  633. ESPCONN_EVENT_RECV(Threadmsg->pespconn, TheadBuff, ret);
  634. } else {
  635. if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == 0) {
  636. ret = ESPCONN_OK;
  637. break;
  638. } else if(ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  639. ret = ESPCONN_OK;
  640. mbedtls_ssl_close_notify(&TLSmsg->ssl);
  641. } else {
  642. break;
  643. }
  644. }
  645. } while(1);
  646. os_free(TheadBuff);
  647. TheadBuff = NULL;
  648. lwIP_REQUIRE_NOERROR(ret, exit);
  649. } else {
  650. if (TLSmsg->ssl.state == MBEDTLS_SSL_HELLO_REQUEST) {
  651. os_printf("client handshake start.\n");
  652. config_flag = mbedtls_msg_config(TLSmsg);
  653. if (config_flag) {
  654. // mbedtls_keep_alive(TLSmsg->fd.fd, 1, SSL_KEEP_IDLE, SSL_KEEP_INTVL, SSL_KEEP_CNT);
  655. system_overclock();
  656. } else {
  657. ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
  658. lwIP_REQUIRE_NOERROR(ret, exit);
  659. }
  660. }
  661. system_soft_wdt_stop();
  662. uint8 cpu_freq;
  663. cpu_freq = system_get_cpu_freq();
  664. system_update_cpu_freq(160);
  665. while ((ret = mbedtls_ssl_handshake(&TLSmsg->ssl)) != 0) {
  666. if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  667. ret = ESPCONN_OK;
  668. break;
  669. } else {
  670. break;
  671. }
  672. }
  673. system_soft_wdt_restart();
  674. system_update_cpu_freq(cpu_freq);
  675. lwIP_REQUIRE_NOERROR(ret, exit);
  676. /**/
  677. TLSmsg->quiet = mbedtls_handshake_result(TLSmsg);
  678. if (TLSmsg->quiet) {
  679. os_printf("client handshake ok!\n");
  680. // mbedtls_keep_alive(TLSmsg->fd.fd, 0, SSL_KEEP_IDLE, SSL_KEEP_INTVL, SSL_KEEP_CNT);
  681. mbedtls_session_free(&TLSmsg->psession);
  682. mbedtls_handshake_succ(&TLSmsg->ssl);
  683. system_restoreclock();
  684. TLSmsg->SentFnFlag = true;
  685. ESPCONN_EVENT_CONNECTED(Threadmsg->pespconn);
  686. } else {
  687. lwIP_REQUIRE_NOERROR_ACTION(TLSmsg->verify_result, exit, ret = TLSmsg->verify_result);
  688. }
  689. }
  690. } else if (error < 0) {
  691. Threadmsg->pcommon.err = error;
  692. Threadmsg->pespconn->state = ESPCONN_CLOSE;
  693. mbedtls_net_free(&TLSmsg->fd);
  694. ets_post(lwIPThreadPrio, NETCONN_EVENT_ERROR, (uint32)Threadmsg);
  695. } else {
  696. ret = MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY;
  697. lwIP_REQUIRE_NOERROR(ret, exit);
  698. }
  699. exit:
  700. if (ret != ESPCONN_OK) {
  701. mbedtls_fail_info(Threadmsg, ret);
  702. if(ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  703. Threadmsg->hs_status = ESPCONN_OK;
  704. }
  705. ets_post(lwIPThreadPrio, NETCONN_EVENT_CLOSE,(uint32)Threadmsg);
  706. }
  707. return ret;
  708. }
  709. int espconn_mbedtls_parse_thread(int socket, int event, int error)
  710. {
  711. int ret = ERR_OK;
  712. espconn_msg *Threadmsg = NULL;
  713. pmbedtls_msg TLSmsg = NULL;
  714. Threadmsg = mbedtls_msg_find(socket);
  715. lwIP_REQUIRE_ACTION(Threadmsg, exit, ret = ERR_MEM);
  716. TLSmsg = Threadmsg->pssl;
  717. lwIP_REQUIRE_ACTION(TLSmsg, exit, ret = ERR_MEM);
  718. if (TLSmsg->quiet) {
  719. int out_msglen = TLSmsg->ssl.out_msglen + 5;
  720. if (Threadmsg->pcommon.write_flag)
  721. TLSmsg->record_len += error;
  722. if (TLSmsg->record_len == out_msglen) {
  723. TLSmsg->record_len = 0;
  724. Threadmsg->pcommon.write_flag = false;
  725. if (Threadmsg->pcommon.cntr != 0) {
  726. espconn_ssl_sent(Threadmsg, Threadmsg->pcommon.ptrbuf, Threadmsg->pcommon.cntr);
  727. } else {
  728. TLSmsg->SentFnFlag = true;
  729. ESPCONN_EVENT_SEND(Threadmsg->pespconn);
  730. }
  731. }
  732. }
  733. exit:
  734. return ret;
  735. }
  736. /**
  737. * @brief Api_Thread.
  738. * @param events: contain the Api_Thread processing data
  739. * @retval None
  740. */
  741. static void
  742. mbedtls_thread(os_event_t *events)
  743. {
  744. int ret = ESP_OK;
  745. bool active_flag = false;
  746. espconn_msg *Threadmsg = NULL;
  747. espconn_msg *ListMsg = NULL;
  748. pmbedtls_msg TLSmsg = NULL;
  749. Threadmsg = (espconn_msg *)events->par;
  750. lwIP_REQUIRE_ACTION(Threadmsg,exit,ret = ERR_ARG);
  751. TLSmsg = Threadmsg->pssl;
  752. lwIP_REQUIRE_ACTION(TLSmsg,exit,ret = ERR_ARG);
  753. lwIP_REQUIRE_ACTION(Threadmsg->pespconn,exit,ret = ERR_ARG);
  754. /*find the active connection*/
  755. for (ListMsg = plink_active; ListMsg != NULL; ListMsg = ListMsg->pnext) {
  756. if (Threadmsg == ListMsg) {
  757. active_flag = true;
  758. break;
  759. }
  760. }
  761. if (active_flag) {
  762. /*remove the node from the active connection list*/
  763. espconn_list_delete(&plink_active, Threadmsg);
  764. mbedtls_msg_free(&TLSmsg);
  765. Threadmsg->pssl = NULL;
  766. switch (events->sig) {
  767. case NETCONN_EVENT_ERROR:
  768. espconn_close_internal(Threadmsg, NETCONN_EVENT_ERROR);
  769. break;
  770. case NETCONN_EVENT_CLOSE:
  771. espconn_close_internal(Threadmsg, NETCONN_EVENT_CLOSE);
  772. break;
  773. default:
  774. break;
  775. }
  776. }
  777. exit:
  778. return;
  779. }
  780. static void mbedtls_threadinit(void)
  781. {
  782. ets_task(mbedtls_thread, lwIPThreadPrio, lwIPThreadQueue, lwIPThreadQueueLen);
  783. lwIPThreadFlag = true;
  784. }
  785. sint8 espconn_ssl_client(struct espconn *espconn)
  786. {
  787. int ret = ESPCONN_OK;
  788. struct ip_addr ipaddr;
  789. const char *server_name = NULL;
  790. const char *server_port = NULL;
  791. espconn_msg *pclient = NULL;
  792. pmbedtls_msg mbedTLSMsg = NULL;
  793. if (lwIPThreadFlag == false)
  794. mbedtls_threadinit();
  795. lwIP_REQUIRE_ACTION(espconn, exit, ret = ESPCONN_ARG);
  796. pclient = (espconn_msg *)os_zalloc( sizeof(espconn_msg));
  797. lwIP_REQUIRE_ACTION(pclient, exit, ret = ESPCONN_MEM);
  798. mbedTLSMsg = mbedtls_msg_new();
  799. lwIP_REQUIRE_ACTION(mbedTLSMsg, exit, ret = ESPCONN_MEM);
  800. IP4_ADDR(&ipaddr, espconn->proto.tcp->remote_ip[0],espconn->proto.tcp->remote_ip[1],
  801. espconn->proto.tcp->remote_ip[2],espconn->proto.tcp->remote_ip[3]);
  802. server_name = ipaddr_ntoa(&ipaddr);
  803. server_port = (const char *)sys_itoa(espconn->proto.tcp->remote_port);
  804. /*start the connection*/
  805. ret = mbedtls_net_connect(&mbedTLSMsg->fd, server_name, server_port, MBEDTLS_NET_PROTO_TCP);
  806. lwIP_REQUIRE_NOERROR_ACTION(ret, exit, ret = ESPCONN_MEM);
  807. espconn->state = ESPCONN_WAIT;
  808. pclient->pespconn = espconn;
  809. pclient->pssl = mbedTLSMsg;
  810. pclient->preverse = NULL;
  811. /*insert the node to the active connection list*/
  812. espconn_list_creat(&plink_active, pclient);
  813. exit:
  814. if (ret != ESPCONN_OK) {
  815. if (mbedTLSMsg != NULL)
  816. mbedtls_msg_free(&mbedTLSMsg);
  817. if (pclient != NULL)
  818. os_free(pclient);
  819. }
  820. return ret;
  821. }
  822. /******************************************************************************
  823. * FunctionName : espconn_ssl_write
  824. * Description : sent data for client or server
  825. * Parameters : void *arg -- client or server to send
  826. * uint8* psent -- Data to send
  827. * uint16 length -- Length of data to send
  828. * Returns : none
  829. *******************************************************************************/
  830. void espconn_ssl_sent(void *arg, uint8 *psent, uint16 length)
  831. {
  832. espconn_msg *Threadmsg = arg;
  833. uint16 out_msglen = length;
  834. int ret = ESPCONN_OK;
  835. lwIP_ASSERT(Threadmsg);
  836. lwIP_ASSERT(psent);
  837. lwIP_ASSERT(length);
  838. pmbedtls_msg mbedTLSMsg = Threadmsg->pssl;
  839. lwIP_ASSERT(mbedTLSMsg);
  840. if (length > MBEDTLS_SSL_PLAIN_ADD) {
  841. out_msglen = MBEDTLS_SSL_PLAIN_ADD;
  842. }
  843. Threadmsg->pcommon.write_flag = true;
  844. ret = mbedtls_ssl_write(&mbedTLSMsg->ssl, psent, out_msglen);
  845. if (ret > 0) {
  846. Threadmsg->pcommon.ptrbuf = psent + ret;
  847. Threadmsg->pcommon.cntr = length - ret;
  848. } else {
  849. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE || ret == 0) {
  850. } else {
  851. mbedtls_fail_info(Threadmsg, ret);
  852. ets_post(lwIPThreadPrio, NETCONN_EVENT_CLOSE,(uint32)Threadmsg);
  853. }
  854. }
  855. }
  856. /******************************************************************************
  857. * FunctionName : espconn_ssl_disconnect
  858. * Description : A new incoming connection has been disconnected.
  859. * Parameters : espconn -- the espconn used to disconnect with host
  860. * Returns : none
  861. *******************************************************************************/
  862. void espconn_ssl_disconnect(espconn_msg *Threadmsg)
  863. {
  864. lwIP_ASSERT(Threadmsg);
  865. pmbedtls_msg mbedTLSMsg = Threadmsg->pssl;
  866. lwIP_ASSERT(mbedTLSMsg);
  867. mbedtls_net_free(&mbedTLSMsg->fd);
  868. Threadmsg->pespconn->state = ESPCONN_CLOSE;
  869. ets_post(lwIPThreadPrio, NETCONN_EVENT_CLOSE, (uint32)Threadmsg);
  870. }
  871. #endif