espconn_mbedtls.c 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  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. #ifdef MEMLEAK_DEBUG
  33. static const char mem_debug_file[] ICACHE_RODATA_ATTR = __FILE__;
  34. #endif
  35. #include "sys/socket.h"
  36. #include "sys/espconn_mbedtls.h"
  37. static os_event_t lwIPThreadQueue[lwIPThreadQueueLen];
  38. static bool lwIPThreadFlag = false;
  39. extern espconn_msg *plink_active;
  40. static espconn_msg *plink_server = NULL;
  41. static pmbedtls_parame def_certificate = NULL;
  42. static pmbedtls_parame def_private_key = NULL;
  43. #if defined(ESP8266_PLATFORM)
  44. #define MBEDTLS_SSL_OUTBUFFER_LEN ( MBEDTLS_SSL_PLAIN_ADD \
  45. + MBEDTLS_SSL_COMPRESSION_ADD \
  46. + 29 /* counter + header + IV */ \
  47. + MBEDTLS_SSL_MAC_ADD \
  48. + MBEDTLS_SSL_PADDING_ADD \
  49. )
  50. #endif
  51. /* Implementation that should never be optimized out by the compiler */
  52. static void mbedtls_zeroize( void *v, size_t n ) {
  53. volatile unsigned char *p = v; while( n-- ) *p++ = 0;
  54. }
  55. static pmbedtls_parame mbedtls_parame_new(size_t capacity)
  56. {
  57. pmbedtls_parame rb = (pmbedtls_parame)os_zalloc(sizeof(mbedtls_parame));
  58. if (rb && capacity != 0){
  59. rb->parame_datalen = capacity;
  60. rb->parame_data = (uint8*)os_zalloc(rb->parame_datalen + 1);
  61. if (rb->parame_data){
  62. } else{
  63. os_free(rb);
  64. rb = NULL;
  65. }
  66. }
  67. return rb;
  68. }
  69. static void mbedtls_parame_free(pmbedtls_parame *fp)
  70. {
  71. lwIP_ASSERT(fp);
  72. lwIP_ASSERT(*fp);
  73. os_free((*fp)->parame_data);
  74. os_free(*fp);
  75. *fp = NULL;
  76. }
  77. bool mbedtls_load_default_obj(uint32 flash_sector, int obj_type, const unsigned char *load_buf, uint16 length)
  78. {
  79. pmbedtls_parame mbedtls_write = NULL;
  80. uint32 mbedtls_head = 0;
  81. bool mbedtls_load_flag = false;
  82. if (flash_sector != 0){
  83. spi_flash_read(flash_sector * FLASH_SECTOR_SIZE, (uint32*)&mbedtls_head, 4);
  84. if (mbedtls_head != ESPCONN_INVALID_TYPE){
  85. mbedtls_write = mbedtls_parame_new(0);
  86. mbedtls_write->parame_datalen = length;
  87. }
  88. } else{
  89. const char* const begin = "-----BEGIN";
  90. int format_type = ESPCONN_FORMAT_INIT;
  91. /*
  92. * Determine data content. data contains either one DER certificate or
  93. * one or more PEM certificates.
  94. */
  95. if ((char*)os_strstr(load_buf, begin) != NULL){
  96. format_type = ESPCONN_FORMAT_PEM;
  97. }else{
  98. format_type = ESPCONN_FORMAT_DER;
  99. }
  100. if (format_type == ESPCONN_FORMAT_PEM){
  101. length += 1;
  102. }
  103. mbedtls_write = mbedtls_parame_new(length);
  104. if (mbedtls_write){
  105. os_memcpy(mbedtls_write->parame_data, load_buf, length);
  106. if (format_type == ESPCONN_FORMAT_PEM)
  107. mbedtls_write->parame_data[length - 1] = '\0';
  108. }
  109. }
  110. if (mbedtls_write){
  111. mbedtls_load_flag = true;
  112. mbedtls_write->parame_type = obj_type;
  113. mbedtls_write->parame_sec = flash_sector;
  114. if (obj_type == ESPCONN_PK){
  115. def_private_key = mbedtls_write;
  116. } else{
  117. def_certificate = mbedtls_write;
  118. }
  119. }
  120. return mbedtls_load_flag;
  121. }
  122. static unsigned char* mbedtls_get_default_obj(uint32 *sec, uint32 type, uint32 *len)
  123. {
  124. const char* const begin = "-----BEGIN";
  125. unsigned char *parame_data = NULL;
  126. pmbedtls_parame mbedtls_obj = NULL;
  127. if (type == ESPCONN_PK){
  128. mbedtls_obj = def_private_key;
  129. } else{
  130. mbedtls_obj = def_certificate;
  131. }
  132. if (mbedtls_obj->parame_sec != 0){
  133. #define DATA_OFFSET 4
  134. uint32 data_len = mbedtls_obj->parame_datalen;
  135. parame_data = (unsigned char *)os_zalloc(data_len + DATA_OFFSET);
  136. if (parame_data){
  137. spi_flash_read(mbedtls_obj->parame_sec * FLASH_SECTOR_SIZE, (uint32*)parame_data, data_len);
  138. /*
  139. * Determine buffer content. Buffer contains either one DER certificate or
  140. * one or more PEM certificates.
  141. */
  142. if ((char*)os_strstr(parame_data, begin) != NULL){
  143. data_len ++;
  144. parame_data[data_len - 1] = '\0';
  145. }
  146. }
  147. *len = data_len;
  148. } else{
  149. parame_data = mbedtls_obj->parame_data;
  150. *len = mbedtls_obj->parame_datalen;
  151. }
  152. *sec = mbedtls_obj->parame_sec;
  153. return parame_data;
  154. }
  155. static int mbedtls_setsockopt(int sock_id, int level, int optname, int optval)
  156. {
  157. return setsockopt(sock_id, level, optname, (void*)&optval, sizeof(optval));
  158. }
  159. static int mbedtls_keep_alive(int sock_id, int onoff, int idle, int intvl, int cnt)
  160. {
  161. int ret = ERR_OK;
  162. if (onoff == 0)
  163. return mbedtls_setsockopt(sock_id, SOL_SOCKET, SO_KEEPALIVE, onoff);;
  164. ret = mbedtls_setsockopt(sock_id, SOL_SOCKET, SO_KEEPALIVE, onoff);
  165. lwIP_REQUIRE_NOERROR(ret, exit);
  166. ret = mbedtls_setsockopt(sock_id, IPPROTO_TCP, TCP_KEEPALIVE, onoff);
  167. lwIP_REQUIRE_NOERROR(ret, exit);
  168. ret = mbedtls_setsockopt(sock_id, IPPROTO_TCP, TCP_KEEPIDLE, idle);
  169. lwIP_REQUIRE_NOERROR(ret, exit);
  170. ret = mbedtls_setsockopt(sock_id, IPPROTO_TCP, TCP_KEEPINTVL, intvl);
  171. lwIP_REQUIRE_NOERROR(ret, exit);
  172. ret = mbedtls_setsockopt(sock_id, IPPROTO_TCP, TCP_KEEPCNT, cnt);
  173. lwIP_REQUIRE_NOERROR(ret, exit);
  174. exit:
  175. return ret;
  176. }
  177. #if defined(ESP8266_PLATFORM)
  178. static pmbedtls_finished mbedtls_finished_new(int len)
  179. {
  180. pmbedtls_finished finished = (pmbedtls_finished)os_zalloc(sizeof(mbedtls_finished));
  181. if (finished)
  182. {
  183. finished->finished_len = len;
  184. finished->finished_buf = (uint8*)os_zalloc(finished->finished_len + 1);
  185. if (finished->finished_buf)
  186. {
  187. }
  188. else
  189. {
  190. os_free(finished);
  191. finished = NULL;
  192. }
  193. }
  194. return finished;
  195. }
  196. static void mbedtls_finished_free(pmbedtls_finished *pfinished)
  197. {
  198. lwIP_ASSERT(pfinished);
  199. lwIP_ASSERT(*pfinished);
  200. os_free((*pfinished)->finished_buf);
  201. os_free(*pfinished);
  202. *pfinished = NULL;
  203. }
  204. #endif
  205. static pmbedtls_espconn mbedtls_espconn_new(void)
  206. {
  207. pmbedtls_espconn mbedtls_conn = NULL;
  208. mbedtls_conn = (pmbedtls_espconn)os_zalloc(sizeof(mbedtls_espconn));
  209. if (mbedtls_conn){
  210. mbedtls_conn->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp));
  211. if (mbedtls_conn->proto.tcp == NULL){
  212. os_free(mbedtls_conn);
  213. mbedtls_conn = NULL;
  214. }
  215. }
  216. return mbedtls_conn;
  217. }
  218. static void mbedtls_espconn_free(pmbedtls_espconn *mbedtlsconn)
  219. {
  220. lwIP_ASSERT(mbedtlsconn);
  221. lwIP_ASSERT(*mbedtlsconn);
  222. os_free((*mbedtlsconn)->proto.tcp);
  223. (*mbedtlsconn)->proto.tcp = NULL;
  224. os_free((*mbedtlsconn));
  225. *mbedtlsconn = NULL;
  226. }
  227. static pmbedtls_session mbedtls_session_new(void)
  228. {
  229. pmbedtls_session session = (pmbedtls_session)os_zalloc(sizeof(mbedtls_session));
  230. if (session){
  231. mbedtls_x509_crt_init(&session->cacert);
  232. mbedtls_x509_crt_init(&session->clicert);
  233. mbedtls_pk_init(&session->pkey);
  234. // mbedtls_entropy_init(&session->entropy);
  235. }
  236. return session;
  237. }
  238. static void mbedtls_session_free(pmbedtls_session *session)
  239. {
  240. lwIP_ASSERT(session);
  241. lwIP_ASSERT(*session);
  242. mbedtls_x509_crt_free(&(*session)->cacert);
  243. mbedtls_x509_crt_free(&(*session)->clicert);
  244. mbedtls_pk_free(&(*session)->pkey);
  245. // mbedtls_entropy_free(&(*session)->entropy);
  246. os_free(*session);
  247. *session = NULL;
  248. }
  249. static pmbedtls_msg mbedtls_msg_new(void)
  250. {
  251. pmbedtls_msg msg = (pmbedtls_msg)os_zalloc( sizeof(mbedtls_msg));
  252. if (msg) {
  253. os_bzero(msg, sizeof(mbedtls_msg));
  254. msg->psession = mbedtls_session_new();
  255. if (msg->psession){
  256. mbedtls_net_init(&msg->listen_fd);
  257. mbedtls_net_init(&msg->fd);
  258. mbedtls_ssl_init(&msg->ssl);
  259. mbedtls_ssl_config_init(&msg->conf);
  260. mbedtls_ctr_drbg_init(&msg->ctr_drbg);
  261. mbedtls_entropy_init(&msg->entropy);
  262. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && defined(SSL_MAX_FRAGMENT_LENGTH_CODE)
  263. mbedtls_ssl_conf_max_frag_len(&msg->conf, SSL_MAX_FRAGMENT_LENGTH_CODE);
  264. #endif
  265. } else{
  266. os_free(msg);
  267. msg = NULL;
  268. }
  269. }
  270. return msg;
  271. }
  272. static void mbedtls_msg_server_step(pmbedtls_msg msg)
  273. {
  274. lwIP_ASSERT(msg);
  275. /*to prevent memory leaks, ensure that each allocated is deleted at every handshake*/
  276. if (msg->psession){
  277. mbedtls_session_free(&msg->psession);
  278. }
  279. #if defined(ESP8266_PLATFORM)
  280. if (msg->quiet && msg->ssl.out_buf)
  281. {
  282. mbedtls_zeroize(msg->ssl.out_buf, MBEDTLS_SSL_OUTBUFFER_LEN);
  283. os_free(msg->ssl.out_buf);
  284. msg->ssl.out_buf = NULL;
  285. }
  286. #endif
  287. mbedtls_entropy_free(&msg->entropy);
  288. mbedtls_ssl_free(&msg->ssl);
  289. mbedtls_ssl_config_free(&msg->conf);
  290. mbedtls_ctr_drbg_free(&msg->ctr_drbg);
  291. /*New connection ensure that each initial for next handshake */
  292. os_bzero(msg, sizeof(mbedtls_msg));
  293. msg->psession = mbedtls_session_new();
  294. if (msg->psession){
  295. mbedtls_net_init(&msg->fd);
  296. mbedtls_ssl_init(&msg->ssl);
  297. mbedtls_ssl_config_init(&msg->conf);
  298. mbedtls_ctr_drbg_init(&msg->ctr_drbg);
  299. mbedtls_entropy_init(&msg->entropy);
  300. }
  301. }
  302. static void mbedtls_msg_free(pmbedtls_msg *msg)
  303. {
  304. lwIP_ASSERT(msg);
  305. lwIP_ASSERT(*msg);
  306. /*to prevent memory leaks, ensure that each allocated is deleted at every handshake*/
  307. if ((*msg)->psession){
  308. mbedtls_session_free(&((*msg)->psession));
  309. }
  310. #if defined(ESP8266_PLATFORM)
  311. if ((*msg)->quiet && (*msg)->ssl.out_buf)
  312. {
  313. mbedtls_zeroize((*msg)->ssl.out_buf, MBEDTLS_SSL_OUTBUFFER_LEN);
  314. os_free((*msg)->ssl.out_buf);
  315. (*msg)->ssl.out_buf = NULL;
  316. }
  317. if((*msg)->pfinished != NULL)
  318. mbedtls_finished_free(&(*msg)->pfinished);
  319. #endif
  320. mbedtls_entropy_free(&(*msg)->entropy);
  321. mbedtls_ssl_free(&(*msg)->ssl);
  322. mbedtls_ssl_config_free(&(*msg)->conf);
  323. mbedtls_ctr_drbg_free(&(*msg)->ctr_drbg);
  324. os_free(*msg);
  325. *msg = NULL;
  326. }
  327. static espconn_msg* mbedtls_msg_find(int sock)
  328. {
  329. espconn_msg *plist = NULL;
  330. pmbedtls_msg msg = NULL;
  331. for (plist = plink_active; plist != NULL; plist = plist->pnext) {
  332. if(plist->pssl != NULL){
  333. msg = plist->pssl;
  334. if (msg->fd.fd == sock)
  335. return plist;
  336. }
  337. }
  338. for (plist = plink_server; plist != NULL; plist = plist->pnext){
  339. if(plist->pssl != NULL){
  340. msg = plist->pssl;
  341. if (msg->listen_fd.fd == sock)
  342. return plist;
  343. }
  344. }
  345. return NULL;
  346. }
  347. void mbedtls_handshake_heap(mbedtls_ssl_context *ssl)
  348. {
  349. os_printf("mbedtls_handshake_heap %d %d\n", ssl->state, system_get_free_heap_size());
  350. }
  351. static bool mbedtls_handshake_result(const pmbedtls_msg Threadmsg)
  352. {
  353. if (Threadmsg == NULL)
  354. return false;
  355. if (Threadmsg->ssl.state == MBEDTLS_SSL_HANDSHAKE_OVER) {
  356. int ret = 0;
  357. if (Threadmsg->listen_fd.fd == -1)
  358. ret = ssl_option.client.cert_ca_sector.flag;
  359. else
  360. ret = ssl_option.server.cert_ca_sector.flag;
  361. if (ret == 1){
  362. ret = mbedtls_ssl_get_verify_result(&Threadmsg->ssl);
  363. if (ret != 0) {
  364. char vrfy_buf[512];
  365. os_memset(vrfy_buf, 0, sizeof(vrfy_buf)-1);
  366. mbedtls_x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), "!", ret);
  367. os_printf("%s\n", vrfy_buf);
  368. Threadmsg->verify_result = ret;
  369. return false;
  370. } else
  371. return true;
  372. } else
  373. return true;
  374. }else
  375. return false;
  376. }
  377. static void mbedtls_fail_info(espconn_msg *pinfo, int ret)
  378. {
  379. pmbedtls_msg TLSmsg = NULL;
  380. lwIP_REQUIRE_ACTION(pinfo,exit,);
  381. TLSmsg = pinfo->pssl;
  382. lwIP_REQUIRE_ACTION(TLSmsg,exit,);
  383. /* Don't complain to console if we've been told the other end is hanging
  384. * up. That's entirely normal and not worthy of the confusion it sows!
  385. */
  386. if (ret != MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  387. if (TLSmsg->quiet){
  388. if (pinfo->preverse != NULL) {
  389. os_printf("server's data invalid protocol\n");
  390. } else {
  391. os_printf("client's data invalid protocol\n");
  392. }
  393. mbedtls_ssl_close_notify(&TLSmsg->ssl);
  394. } else{
  395. if (pinfo->preverse != NULL) {
  396. os_printf("server handshake failed!\n");
  397. } else {
  398. os_printf("client handshake failed!\n");
  399. }
  400. }
  401. }
  402. os_printf("Reason:[-0x%2x]\n",-ret);
  403. /*Error code convert*/
  404. ret = -ret;
  405. if ((ret & 0xFF) != 0){
  406. ret = ((ret >> 8) + ret);
  407. } else{
  408. ret >>= 8;
  409. }
  410. pinfo->hs_status = -ret;
  411. pinfo->pespconn->state = ESPCONN_CLOSE;
  412. mbedtls_net_free(&TLSmsg->fd);
  413. exit:
  414. return;
  415. }
  416. #if defined(ESP8266_PLATFORM)
  417. int mbedtls_write_finished(mbedtls_ssl_context *ssl)
  418. {
  419. lwIP_ASSERT(ssl);
  420. lwIP_ASSERT(ssl->p_bio);
  421. int ret = ERR_OK;
  422. int fd = ((mbedtls_net_context *) ssl->p_bio)->fd;
  423. espconn_msg *Threadmsg = mbedtls_msg_find(fd);
  424. lwIP_REQUIRE_ACTION(Threadmsg, exit, ret = ERR_MEM);
  425. pmbedtls_msg TLSmsg = Threadmsg->pssl;
  426. lwIP_REQUIRE_ACTION(TLSmsg, exit, ret = ERR_MEM);
  427. TLSmsg->pfinished = mbedtls_finished_new(ssl->out_msglen + 29);
  428. lwIP_REQUIRE_ACTION(TLSmsg->pfinished, exit, ret = ERR_MEM);
  429. os_memcpy(TLSmsg->pfinished->finished_buf, ssl->out_ctr, TLSmsg->pfinished->finished_len);
  430. exit:
  431. return ret;
  432. }
  433. static int mbedtls_hanshake_finished(mbedtls_msg *msg)
  434. {
  435. lwIP_ASSERT(msg);
  436. int ret = ERR_OK;
  437. const size_t len = MBEDTLS_SSL_OUTBUFFER_LEN;
  438. mbedtls_ssl_context *ssl = &msg->ssl;
  439. lwIP_REQUIRE_ACTION(ssl, exit, ret = ERR_MEM);
  440. pmbedtls_finished finished = msg->pfinished;
  441. lwIP_REQUIRE_ACTION(finished, exit, ret = ERR_MEM);
  442. ssl->out_buf = (unsigned char*)os_zalloc(len);
  443. lwIP_REQUIRE_ACTION(ssl->out_buf, exit, ret = MBEDTLS_ERR_SSL_ALLOC_FAILED);
  444. ssl->out_ctr = ssl->out_buf;
  445. ssl->out_hdr = ssl->out_buf + 8;
  446. ssl->out_len = ssl->out_buf + 11;
  447. ssl->out_iv = ssl->out_buf + 13;
  448. ssl->out_msg = ssl->out_buf + 29;
  449. os_memcpy(ssl->out_ctr, finished->finished_buf, finished->finished_len);
  450. mbedtls_finished_free(&msg->pfinished);
  451. exit:
  452. return ret;
  453. }
  454. #endif
  455. static void mbedtls_handshake_succ(mbedtls_ssl_context *ssl)
  456. {
  457. lwIP_ASSERT(ssl);
  458. if( ssl->handshake )
  459. {
  460. mbedtls_ssl_handshake_free( ssl->handshake );
  461. mbedtls_ssl_transform_free( ssl->transform_negotiate );
  462. mbedtls_ssl_session_free( ssl->session_negotiate );
  463. os_free( ssl->handshake );
  464. os_free( ssl->transform_negotiate );
  465. os_free( ssl->session_negotiate );
  466. ssl->handshake = NULL;
  467. ssl->transform_negotiate = NULL;
  468. ssl->session_negotiate = NULL;
  469. }
  470. if( ssl->session )
  471. {
  472. mbedtls_ssl_session_free( ssl->session );
  473. os_free( ssl->session );
  474. ssl->session = NULL;
  475. }
  476. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  477. if( ssl->hostname != NULL )
  478. {
  479. mbedtls_zeroize( ssl->hostname, os_strlen( ssl->hostname ) );
  480. os_free( ssl->hostname );
  481. ssl->hostname = NULL;
  482. }
  483. #endif
  484. }
  485. /******************************************************************************
  486. * FunctionName : espconn_ssl_reconnect
  487. * Description : reconnect with host
  488. * Parameters : arg -- Additional argument to pass to the callback function
  489. * Returns : none
  490. *******************************************************************************/
  491. static void espconn_close_internal(void *arg, netconn_event event_type)
  492. {
  493. espconn_msg *pssl_recon = arg;
  494. struct espconn *espconn = NULL;
  495. sint8 ssl_reerr = 0;
  496. sint16 hs_status = 0;
  497. lwIP_ASSERT(pssl_recon);
  498. espconn = pssl_recon->preverse;
  499. ssl_reerr = pssl_recon->pcommon.err;
  500. hs_status = pssl_recon->hs_status;
  501. if (espconn != NULL) {
  502. //clear pcommon parameters.
  503. pssl_recon->pcommon.write_flag = false;
  504. pssl_recon->pcommon.ptrbuf = NULL;
  505. pssl_recon->pcommon.cntr = 0;
  506. pssl_recon->pcommon.err = 0;
  507. espconn = pssl_recon->preverse;
  508. } else {
  509. espconn = pssl_recon->pespconn;
  510. os_free(pssl_recon);
  511. pssl_recon = NULL;
  512. }
  513. espconn_kill_oldest_pcb();
  514. switch (event_type){
  515. case NETCONN_EVENT_ERROR:
  516. if (hs_status == ESPCONN_OK)
  517. ESPCONN_EVENT_ERROR(espconn, ssl_reerr);
  518. else
  519. ESPCONN_EVENT_ERROR(espconn, hs_status);
  520. break;
  521. case NETCONN_EVENT_CLOSE:
  522. if (hs_status == ESPCONN_OK)
  523. ESPCONN_EVENT_CLOSED(espconn);
  524. else
  525. ESPCONN_EVENT_ERROR(espconn, hs_status);
  526. break;
  527. default:
  528. break;
  529. }
  530. }
  531. /******************************************************************************
  532. * FunctionName : espconn_ssl_read_param_from_flash
  533. * Description : load parameter from flash, toggle use two sector by flag value.
  534. * Parameters : param--the parame point which write the flash
  535. * Returns : none
  536. *******************************************************************************/
  537. static bool espconn_ssl_read_param_from_flash(void *param, uint16 len, int32 offset, mbedtls_auth_info *auth_info)
  538. {
  539. if (param == NULL || (len + offset) > ESPCONN_SECURE_MAX_SIZE) {
  540. return false;
  541. }
  542. uint32 FILE_PARAM_START_SEC = 0x3B;
  543. switch (auth_info->auth_level) {
  544. case ESPCONN_CLIENT:
  545. switch (auth_info->auth_type) {
  546. case ESPCONN_CERT_AUTH:
  547. FILE_PARAM_START_SEC = ssl_option.client.cert_ca_sector.sector;
  548. break;
  549. case ESPCONN_CERT_OWN:
  550. case ESPCONN_PK:
  551. FILE_PARAM_START_SEC = ssl_option.client.cert_req_sector.sector;
  552. break;
  553. default:
  554. return false;
  555. }
  556. break;
  557. case ESPCONN_SERVER:
  558. switch (auth_info->auth_type) {
  559. case ESPCONN_CERT_AUTH:
  560. FILE_PARAM_START_SEC = ssl_option.server.cert_ca_sector.sector;
  561. break;
  562. case ESPCONN_CERT_OWN:
  563. case ESPCONN_PK:
  564. FILE_PARAM_START_SEC = ssl_option.server.cert_req_sector.sector;
  565. break;
  566. default:
  567. return false;
  568. }
  569. break;
  570. default:
  571. return false;
  572. break;
  573. }
  574. spi_flash_read(FILE_PARAM_START_SEC * 4096 + offset, param, len);
  575. return true;
  576. }
  577. static bool mbedtls_msg_info_load(mbedtls_msg *msg, mbedtls_auth_info *auth_info)
  578. {
  579. const char* const begin = "-----BEGIN";
  580. const char* const type_name = "private_key";
  581. #define FILE_OFFSET 4
  582. int ret = 0;
  583. int32 offerset = 0;
  584. uint8* load_buf = NULL;
  585. size_t load_len = 0;
  586. file_param *pfile_param = NULL;
  587. pfile_param = (file_param *)os_zalloc( sizeof(file_param));
  588. if (pfile_param==NULL)
  589. return false;
  590. again:
  591. espconn_ssl_read_param_from_flash(&pfile_param->file_head, sizeof(file_head), offerset, auth_info);
  592. pfile_param->file_offerset = offerset;
  593. os_printf("%s %d, type[%s],length[%d]\n", __FILE__, __LINE__, pfile_param->file_head.file_name, pfile_param->file_head.file_length);
  594. if (pfile_param->file_head.file_length == 0xFFFF){
  595. os_free(pfile_param);
  596. return false;
  597. } else{
  598. /*Optional is load the private key*/
  599. if (auth_info->auth_type == ESPCONN_PK && os_memcmp(pfile_param->file_head.file_name, type_name, os_strlen(type_name)) != 0){
  600. offerset += sizeof(file_head) + pfile_param->file_head.file_length;
  601. goto again;
  602. }
  603. /*Optional is load the cert*/
  604. if (auth_info->auth_type == ESPCONN_CERT_OWN && os_memcmp(pfile_param->file_head.file_name, "certificate", os_strlen("certificate")) != 0){
  605. offerset += sizeof(file_head) + pfile_param->file_head.file_length;
  606. goto again;
  607. }
  608. load_buf = (uint8_t *) os_zalloc( pfile_param->file_head.file_length + FILE_OFFSET);
  609. if (load_buf == NULL){
  610. os_free(pfile_param);
  611. return false;
  612. }
  613. offerset = sizeof(file_head) + pfile_param->file_offerset;
  614. espconn_ssl_read_param_from_flash(load_buf, pfile_param->file_head.file_length, offerset, auth_info);
  615. }
  616. load_len = pfile_param->file_head.file_length;
  617. /*
  618. * Determine buffer content. Buffer contains either one DER certificate or
  619. * one or more PEM certificates.
  620. */
  621. if ((char*)os_strstr(load_buf, begin) != NULL){
  622. load_len += 1;
  623. load_buf[load_len - 1] = '\0';
  624. }
  625. switch (auth_info->auth_type){
  626. case ESPCONN_CERT_AUTH:
  627. /*Optional is not optimal for security*/
  628. ret = mbedtls_x509_crt_parse(&msg->psession->cacert, (const uint8*) load_buf,load_len);
  629. lwIP_REQUIRE_NOERROR(ret, exit);
  630. mbedtls_ssl_conf_authmode(&msg->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  631. mbedtls_ssl_conf_ca_chain(&msg->conf, &msg->psession->cacert, NULL);
  632. break;
  633. case ESPCONN_CERT_OWN:
  634. ret = mbedtls_x509_crt_parse(&msg->psession->clicert, (const uint8*) load_buf,load_len);
  635. break;
  636. case ESPCONN_PK:
  637. ret = mbedtls_pk_parse_key(&msg->psession->pkey, (const uint8*) load_buf,load_len, NULL, 0);
  638. lwIP_REQUIRE_NOERROR(ret, exit);
  639. ret = mbedtls_ssl_conf_own_cert(&msg->conf, &msg->psession->clicert, &msg->psession->pkey);
  640. break;
  641. }
  642. exit:
  643. os_free(load_buf);
  644. os_free(pfile_param);
  645. if (ret < 0){
  646. return false;
  647. }else{
  648. return true;
  649. }
  650. }
  651. static void
  652. mbedtls_dbg(void *p, int level, const char *file, int line, const char *str)
  653. {
  654. os_printf("TLS<%d> (heap=%d): %s:%d %s", level, system_get_free_heap_size(), file, line, str);
  655. }
  656. static bool mbedtls_msg_config(mbedtls_msg *msg)
  657. {
  658. const char *pers = NULL;
  659. uint8 auth_type = 0;
  660. bool load_flag = false;
  661. int ret = ESPCONN_OK;
  662. mbedtls_auth_info auth_info;
  663. /*end_point mode*/
  664. if (msg->listen_fd.fd == -1){
  665. pers = "client";
  666. auth_type = MBEDTLS_SSL_IS_CLIENT;
  667. } else {
  668. pers = "server";
  669. auth_type = MBEDTLS_SSL_IS_SERVER;
  670. }
  671. /*Initialize the RNG and the session data*/
  672. ret = mbedtls_ctr_drbg_seed(&msg->ctr_drbg, mbedtls_entropy_func, &msg->entropy, (const unsigned char*) pers, os_strlen(pers));
  673. lwIP_REQUIRE_NOERROR(ret, exit);
  674. if (auth_type == MBEDTLS_SSL_IS_SERVER){
  675. uint32 flash_sector = 0;
  676. /*Load the certificate*/
  677. unsigned int def_certificate_len = 0;unsigned char *def_certificate = NULL;
  678. def_certificate = (unsigned char *)mbedtls_get_default_obj(&flash_sector,ESPCONN_CERT_OWN, &def_certificate_len);
  679. lwIP_REQUIRE_ACTION(def_certificate, exit, ret = MBEDTLS_ERR_SSL_ALLOC_FAILED);
  680. ret = mbedtls_x509_crt_parse(&msg->psession->clicert, (const unsigned char *)def_certificate, def_certificate_len);
  681. if (flash_sector != 0)
  682. os_free(def_certificate);
  683. lwIP_REQUIRE_NOERROR(ret, exit);
  684. /*Load the private RSA key*/
  685. unsigned int def_private_key_len = 0;unsigned char *def_private_key = NULL;
  686. def_private_key = (unsigned char *)mbedtls_get_default_obj(&flash_sector,ESPCONN_PK, &def_private_key_len);
  687. lwIP_REQUIRE_ACTION(def_private_key, exit, ret = MBEDTLS_ERR_SSL_ALLOC_FAILED);
  688. ret = mbedtls_pk_parse_key(&msg->psession->pkey, (const unsigned char *)def_private_key, def_private_key_len, NULL, 0);
  689. if (flash_sector != 0)
  690. os_free(def_private_key);
  691. lwIP_REQUIRE_NOERROR(ret, exit);
  692. ret = mbedtls_ssl_conf_own_cert(&msg->conf, &msg->psession->clicert, &msg->psession->pkey);
  693. lwIP_REQUIRE_NOERROR(ret, exit);
  694. /*Load the trusted CA*/
  695. if (ssl_option.server.cert_ca_sector.flag) {
  696. auth_info.auth_level = ESPCONN_SERVER;
  697. auth_info.auth_type = ESPCONN_CERT_AUTH;
  698. load_flag = mbedtls_msg_info_load(msg, &auth_info);
  699. lwIP_REQUIRE_ACTION(load_flag, exit, ret = ESPCONN_MEM);
  700. }
  701. } else{
  702. /*Load the certificate and private RSA key*/
  703. if (ssl_option.client.cert_req_sector.flag) {
  704. auth_info.auth_level = ESPCONN_CLIENT;
  705. auth_info.auth_type = ESPCONN_CERT_OWN;
  706. load_flag = mbedtls_msg_info_load(msg, &auth_info);
  707. lwIP_REQUIRE_ACTION(load_flag, exit, ret = ESPCONN_MEM);
  708. auth_info.auth_type = ESPCONN_PK;
  709. load_flag = mbedtls_msg_info_load(msg, &auth_info);
  710. lwIP_REQUIRE_ACTION(load_flag, exit, ret = ESPCONN_MEM);
  711. }
  712. /*Load the trusted CA*/
  713. if(ssl_option.client.cert_ca_sector.flag){
  714. auth_info.auth_level = ESPCONN_CLIENT;
  715. auth_info.auth_type = ESPCONN_CERT_AUTH;
  716. load_flag = mbedtls_msg_info_load(msg, &auth_info);
  717. lwIP_REQUIRE_ACTION(load_flag, exit, ret = ESPCONN_MEM);
  718. }
  719. }
  720. /*Setup the stuff*/
  721. ret = mbedtls_ssl_config_defaults(&msg->conf, auth_type, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);
  722. lwIP_REQUIRE_NOERROR(ret, exit);
  723. /*OPTIONAL is not optimal for security, but makes interop easier in this session*/
  724. if (auth_type == MBEDTLS_SSL_IS_CLIENT && ssl_option.client.cert_ca_sector.flag == false){
  725. mbedtls_ssl_conf_authmode(&msg->conf, MBEDTLS_SSL_VERIFY_NONE);
  726. }
  727. mbedtls_ssl_conf_rng(&msg->conf, mbedtls_ctr_drbg_random, &msg->ctr_drbg);
  728. mbedtls_ssl_conf_dbg(&msg->conf, mbedtls_dbg, NULL);
  729. ret = mbedtls_ssl_setup(&msg->ssl, &msg->conf);
  730. lwIP_REQUIRE_NOERROR(ret, exit);
  731. mbedtls_ssl_set_bio(&msg->ssl, &msg->fd, mbedtls_net_send, mbedtls_net_recv, NULL);
  732. exit:
  733. if (ret != 0){
  734. return false;
  735. } else{
  736. return true;
  737. }
  738. }
  739. int __attribute__((weak)) mbedtls_parse_internal(int socket, sint8 error)
  740. {
  741. int ret = ERR_OK;
  742. bool config_flag = false;
  743. espconn_msg *Threadmsg = NULL;
  744. pmbedtls_msg TLSmsg = NULL;
  745. Threadmsg = mbedtls_msg_find(socket);
  746. lwIP_REQUIRE_ACTION(Threadmsg, exit, ret = ERR_MEM);
  747. TLSmsg = Threadmsg->pssl;
  748. lwIP_REQUIRE_ACTION(TLSmsg, exit, ret = ERR_MEM);
  749. if (error == ERR_OK){
  750. if (TLSmsg->quiet){
  751. uint8 *TheadBuff = NULL;
  752. size_t ThreadLen = MBEDTLS_SSL_PLAIN_ADD;
  753. TheadBuff = (uint8 *)os_zalloc(ThreadLen + 1);
  754. lwIP_REQUIRE_ACTION(TheadBuff, exit, ret = ERR_MEM);
  755. do {
  756. os_memset(TheadBuff, 0, ThreadLen);
  757. ret = mbedtls_ssl_read(&TLSmsg->ssl, TheadBuff, ThreadLen);
  758. if (ret > 0){
  759. ESPCONN_EVENT_RECV(Threadmsg->pespconn, TheadBuff, ret);
  760. } else{
  761. if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == 0){
  762. ret = ESPCONN_OK;
  763. break;
  764. } else if(ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY){
  765. ret = ESPCONN_OK;
  766. mbedtls_ssl_close_notify(&TLSmsg->ssl);
  767. } else{
  768. break;
  769. }
  770. }
  771. } while(1);
  772. os_free(TheadBuff);
  773. TheadBuff = NULL;
  774. lwIP_REQUIRE_NOERROR(ret, exit);
  775. } else{
  776. if (TLSmsg->ssl.state == MBEDTLS_SSL_HELLO_REQUEST){
  777. if (Threadmsg->preverse != NULL){
  778. struct espconn *accept_conn = NULL;
  779. struct espconn *espconn = Threadmsg->preverse;
  780. struct sockaddr_in name;
  781. socklen_t name_len = sizeof(name);
  782. remot_info *pinfo = NULL;
  783. espconn_get_connection_info(espconn, &pinfo , ESPCONN_SSL);
  784. if (espconn->link_cnt == 0x01)
  785. return ERR_ISCONN;
  786. ret = mbedtls_net_accept(&TLSmsg->listen_fd, &TLSmsg->fd, NULL, 0, NULL);
  787. lwIP_REQUIRE_NOERROR(ret, exit);
  788. accept_conn = mbedtls_espconn_new();
  789. lwIP_REQUIRE_ACTION(accept_conn, exit, ret = ERR_MEM);
  790. Threadmsg->pespconn = accept_conn;
  791. /*get the remote information*/
  792. getpeername(TLSmsg->fd.fd, (struct sockaddr*)&name, &name_len);
  793. Threadmsg->pcommon.remote_port = htons(name.sin_port);
  794. os_memcpy(Threadmsg->pcommon.remote_ip, &name.sin_addr.s_addr, 4);
  795. espconn->proto.tcp->remote_port = htons(name.sin_port);
  796. os_memcpy(espconn->proto.tcp->remote_ip, &name.sin_addr.s_addr, 4);
  797. espconn_copy_partial(accept_conn, espconn);
  798. /*insert the node to the active connection list*/
  799. espconn_list_creat(&plink_active, Threadmsg);
  800. os_printf("server handshake start.\n");
  801. } else{
  802. os_printf("client handshake start.\n");
  803. }
  804. config_flag = mbedtls_msg_config(TLSmsg);
  805. if (config_flag){
  806. // mbedtls_keep_alive(TLSmsg->fd.fd, 1, SSL_KEEP_IDLE, SSL_KEEP_INTVL, SSL_KEEP_CNT);
  807. system_overclock();
  808. } else{
  809. ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
  810. lwIP_REQUIRE_NOERROR(ret, exit);
  811. }
  812. }
  813. system_soft_wdt_stop();
  814. uint8 cpu_freq;
  815. cpu_freq = system_get_cpu_freq();
  816. system_update_cpu_freq(160);
  817. while ((ret = mbedtls_ssl_handshake(&TLSmsg->ssl)) != 0) {
  818. if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  819. ret = ESPCONN_OK;
  820. break;
  821. } else{
  822. break;
  823. }
  824. }
  825. system_soft_wdt_restart();
  826. system_update_cpu_freq(cpu_freq);
  827. lwIP_REQUIRE_NOERROR(ret, exit);
  828. /**/
  829. TLSmsg->quiet = mbedtls_handshake_result(TLSmsg);
  830. if (TLSmsg->quiet){
  831. if (Threadmsg->preverse != NULL) {
  832. os_printf("server handshake ok!\n");
  833. } else {
  834. os_printf("client handshake ok!\n");
  835. }
  836. // mbedtls_keep_alive(TLSmsg->fd.fd, 0, SSL_KEEP_IDLE, SSL_KEEP_INTVL, SSL_KEEP_CNT);
  837. mbedtls_session_free(&TLSmsg->psession);
  838. mbedtls_handshake_succ(&TLSmsg->ssl);
  839. #if defined(ESP8266_PLATFORM)
  840. mbedtls_hanshake_finished(TLSmsg);
  841. #endif
  842. system_restoreclock();
  843. TLSmsg->SentFnFlag = true;
  844. ESPCONN_EVENT_CONNECTED(Threadmsg->pespconn);
  845. } else{
  846. lwIP_REQUIRE_NOERROR_ACTION(TLSmsg->verify_result, exit, ret = TLSmsg->verify_result);
  847. }
  848. }
  849. } else if (error < 0){
  850. Threadmsg->pcommon.err = error;
  851. Threadmsg->pespconn->state = ESPCONN_CLOSE;
  852. mbedtls_net_free(&TLSmsg->fd);
  853. ets_post(lwIPThreadPrio, NETCONN_EVENT_ERROR, (uint32)Threadmsg);
  854. } else {
  855. ret = MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY;
  856. lwIP_REQUIRE_NOERROR(ret, exit);
  857. }
  858. exit:
  859. if (ret != ESPCONN_OK){
  860. mbedtls_fail_info(Threadmsg, ret);
  861. if(ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY){
  862. Threadmsg->hs_status = ESPCONN_OK;
  863. }
  864. ets_post(lwIPThreadPrio, NETCONN_EVENT_CLOSE,(uint32)Threadmsg);
  865. }
  866. return ret;
  867. }
  868. int __attribute__((weak)) mbedtls_parse_thread(int socket, int event, int error)
  869. {
  870. int ret = ERR_OK;
  871. espconn_msg *Threadmsg = NULL;
  872. pmbedtls_msg TLSmsg = NULL;
  873. Threadmsg = mbedtls_msg_find(socket);
  874. lwIP_REQUIRE_ACTION(Threadmsg, exit, ret = ERR_MEM);
  875. TLSmsg = Threadmsg->pssl;
  876. lwIP_REQUIRE_ACTION(TLSmsg, exit, ret = ERR_MEM);
  877. if (TLSmsg->quiet){
  878. int out_msglen = TLSmsg->ssl.out_msglen + 5;
  879. if (Threadmsg->pcommon.write_flag)
  880. TLSmsg->record.record_len += error;
  881. if (TLSmsg->record.record_len == out_msglen){
  882. TLSmsg->record.record_len = 0;
  883. Threadmsg->pcommon.write_flag = false;
  884. if (Threadmsg->pcommon.cntr != 0){
  885. espconn_ssl_sent(Threadmsg, Threadmsg->pcommon.ptrbuf, Threadmsg->pcommon.cntr);
  886. } else{
  887. TLSmsg->SentFnFlag = true;
  888. ESPCONN_EVENT_SEND(Threadmsg->pespconn);
  889. }
  890. } else{
  891. }
  892. } else{
  893. }
  894. exit:
  895. return ret;
  896. }
  897. /**
  898. * @brief Api_Thread.
  899. * @param events: contain the Api_Thread processing data
  900. * @retval None
  901. */
  902. static void
  903. mbedtls_thread(os_event_t *events)
  904. {
  905. int ret = ESP_OK;
  906. bool active_flag = false;
  907. espconn_msg *Threadmsg = NULL;
  908. espconn_msg *ListMsg = NULL;
  909. pmbedtls_msg TLSmsg = NULL;
  910. Threadmsg = (espconn_msg *)events->par;
  911. lwIP_REQUIRE_ACTION(Threadmsg,exit,ret = ERR_ARG);
  912. TLSmsg = Threadmsg->pssl;
  913. lwIP_REQUIRE_ACTION(TLSmsg,exit,ret = ERR_ARG);
  914. lwIP_REQUIRE_ACTION(Threadmsg->pespconn,exit,ret = ERR_ARG);
  915. /*find the active connection*/
  916. for (ListMsg = plink_active; ListMsg != NULL; ListMsg = ListMsg->pnext){
  917. if (Threadmsg == ListMsg){
  918. active_flag = true;
  919. break;
  920. }
  921. }
  922. if (active_flag){
  923. /*remove the node from the active connection list*/
  924. espconn_list_delete(&plink_active, Threadmsg);
  925. if (TLSmsg->listen_fd.fd != -1){
  926. mbedtls_msg_server_step(TLSmsg);
  927. espconn_copy_partial(Threadmsg->preverse, Threadmsg->pespconn);
  928. mbedtls_espconn_free(&Threadmsg->pespconn);
  929. } else{
  930. mbedtls_msg_free(&TLSmsg);
  931. Threadmsg->pssl = NULL;
  932. }
  933. switch (events->sig){
  934. case NETCONN_EVENT_ERROR:
  935. espconn_close_internal(Threadmsg, NETCONN_EVENT_ERROR);
  936. break;
  937. case NETCONN_EVENT_CLOSE:
  938. espconn_close_internal(Threadmsg, NETCONN_EVENT_CLOSE);
  939. break;
  940. default:
  941. break;
  942. }
  943. }
  944. exit:
  945. return;
  946. }
  947. static void mbedtls_threadinit(void)
  948. {
  949. ets_task(mbedtls_thread, lwIPThreadPrio, lwIPThreadQueue, lwIPThreadQueueLen);
  950. lwIPThreadFlag = true;
  951. }
  952. sint8 espconn_ssl_client(struct espconn *espconn)
  953. {
  954. int ret = ESPCONN_OK;
  955. struct ip_addr ipaddr;
  956. const char *server_name = NULL;
  957. const char *server_port = NULL;
  958. espconn_msg *pclient = NULL;
  959. pmbedtls_msg mbedTLSMsg = NULL;
  960. if (lwIPThreadFlag == false)
  961. mbedtls_threadinit();
  962. lwIP_REQUIRE_ACTION(espconn, exit, ret = ESPCONN_ARG);
  963. pclient = (espconn_msg *)os_zalloc( sizeof(espconn_msg));
  964. lwIP_REQUIRE_ACTION(pclient, exit, ret = ESPCONN_MEM);
  965. mbedTLSMsg = mbedtls_msg_new();
  966. lwIP_REQUIRE_ACTION(mbedTLSMsg, exit, ret = ESPCONN_MEM);
  967. IP4_ADDR(&ipaddr, espconn->proto.tcp->remote_ip[0],espconn->proto.tcp->remote_ip[1],
  968. espconn->proto.tcp->remote_ip[2],espconn->proto.tcp->remote_ip[3]);
  969. server_name = ipaddr_ntoa(&ipaddr);
  970. server_port = (const char *)sys_itoa(espconn->proto.tcp->remote_port);
  971. /*start the connection*/
  972. ret = mbedtls_net_connect(&mbedTLSMsg->fd, server_name, server_port, MBEDTLS_NET_PROTO_TCP);
  973. lwIP_REQUIRE_NOERROR_ACTION(ret, exit, ret = ESPCONN_MEM);
  974. espconn->state = ESPCONN_WAIT;
  975. pclient->pespconn = espconn;
  976. pclient->pssl = mbedTLSMsg;
  977. pclient->preverse = NULL;
  978. /*insert the node to the active connection list*/
  979. espconn_list_creat(&plink_active, pclient);
  980. exit:
  981. if (ret != ESPCONN_OK){
  982. if (mbedTLSMsg != NULL)
  983. mbedtls_msg_free(&mbedTLSMsg);
  984. if (pclient != NULL)
  985. os_free(pclient);
  986. }
  987. return ret;
  988. }
  989. /******************************************************************************
  990. * FunctionName : espconn_ssl_server
  991. * Description : as
  992. * Parameters :
  993. * Returns :
  994. *******************************************************************************/
  995. sint8 espconn_ssl_server(struct espconn *espconn)
  996. {
  997. int ret = ESPCONN_OK;
  998. struct ip_addr ipaddr;
  999. const char *server_port = NULL;
  1000. espconn_msg *pserver = NULL;
  1001. pmbedtls_msg mbedTLSMsg = NULL;
  1002. if (lwIPThreadFlag == false)
  1003. mbedtls_threadinit();
  1004. if (plink_server != NULL)
  1005. return ESPCONN_INPROGRESS;
  1006. lwIP_REQUIRE_ACTION(espconn, exit, ret = ESPCONN_ARG);
  1007. /*Creates a new server control message*/
  1008. pserver = (espconn_msg *) os_zalloc( sizeof(espconn_msg));
  1009. lwIP_REQUIRE_ACTION(espconn, exit, ret = ESPCONN_MEM);
  1010. mbedTLSMsg = mbedtls_msg_new();
  1011. lwIP_REQUIRE_ACTION(mbedTLSMsg, exit, ret = ESPCONN_MEM);
  1012. server_port = (const char *)sys_itoa(espconn->proto.tcp->local_port);
  1013. /*start the connection*/
  1014. ret = mbedtls_net_bind(&mbedTLSMsg->listen_fd, NULL, server_port, MBEDTLS_NET_PROTO_TCP);
  1015. lwIP_REQUIRE_NOERROR_ACTION(ret, exit, ret = ESPCONN_MEM);
  1016. espconn->state = ESPCONN_LISTEN;
  1017. pserver->pespconn = NULL;
  1018. pserver->pssl = mbedTLSMsg;
  1019. pserver->preverse = espconn;
  1020. pserver->count_opt = MEMP_NUM_TCP_PCB;
  1021. pserver->pcommon.timeout = 0x0a;
  1022. espconn->state = ESPCONN_LISTEN;
  1023. plink_server = pserver;
  1024. exit:
  1025. if (ret != ESPCONN_OK) {
  1026. if (mbedTLSMsg != NULL)
  1027. mbedtls_msg_free(&mbedTLSMsg);
  1028. if (pserver != NULL)
  1029. os_free(pserver);
  1030. }
  1031. return ret;
  1032. }
  1033. /******************************************************************************
  1034. * FunctionName : espconn_ssl_delete
  1035. * Description : delete the server: delete a listening PCB and free it
  1036. * Parameters : pdeletecon -- the espconn used to delete a server
  1037. * Returns : none
  1038. *******************************************************************************/
  1039. sint8 espconn_ssl_delete(struct espconn *pdeletecon)
  1040. {
  1041. remot_info *pinfo = NULL;
  1042. espconn_msg *pdelete_msg = NULL;
  1043. pmbedtls_msg mbedTLSMsg = NULL;
  1044. if (pdeletecon == NULL)
  1045. return ESPCONN_ARG;
  1046. espconn_get_connection_info(pdeletecon, &pinfo, ESPCONN_SSL);
  1047. /*make sure all the active connection have been disconnect*/
  1048. if (pdeletecon->link_cnt != 0)
  1049. return ESPCONN_INPROGRESS;
  1050. else {
  1051. pdelete_msg = plink_server;
  1052. if (pdelete_msg != NULL && pdelete_msg->preverse == pdeletecon) {
  1053. mbedTLSMsg = pdelete_msg->pssl;
  1054. espconn_kill_pcb(pdeletecon->proto.tcp->local_port);
  1055. mbedtls_net_free(&mbedTLSMsg->listen_fd);
  1056. mbedtls_msg_free(&mbedTLSMsg);
  1057. pdelete_msg->pssl = mbedTLSMsg;
  1058. os_free(pdelete_msg);
  1059. pdelete_msg = NULL;
  1060. plink_server = pdelete_msg;
  1061. mbedtls_parame_free(&def_private_key);
  1062. mbedtls_parame_free(&def_certificate);
  1063. return ESPCONN_OK;
  1064. } else {
  1065. return ESPCONN_ARG;
  1066. }
  1067. }
  1068. }
  1069. /******************************************************************************
  1070. * FunctionName : espconn_ssl_write
  1071. * Description : sent data for client or server
  1072. * Parameters : void *arg -- client or server to send
  1073. * uint8* psent -- Data to send
  1074. * uint16 length -- Length of data to send
  1075. * Returns : none
  1076. *******************************************************************************/
  1077. void espconn_ssl_sent(void *arg, uint8 *psent, uint16 length)
  1078. {
  1079. espconn_msg *Threadmsg = arg;
  1080. uint16 out_msglen = length;
  1081. int ret = ESPCONN_OK;
  1082. lwIP_ASSERT(Threadmsg);
  1083. lwIP_ASSERT(psent);
  1084. lwIP_ASSERT(length);
  1085. pmbedtls_msg mbedTLSMsg = Threadmsg->pssl;
  1086. lwIP_ASSERT(mbedTLSMsg);
  1087. if (length > MBEDTLS_SSL_PLAIN_ADD){
  1088. out_msglen = MBEDTLS_SSL_PLAIN_ADD;
  1089. }
  1090. Threadmsg->pcommon.write_flag = true;
  1091. ret = mbedtls_ssl_write(&mbedTLSMsg->ssl, psent, out_msglen);
  1092. if (ret > 0){
  1093. Threadmsg->pcommon.ptrbuf = psent + ret;
  1094. Threadmsg->pcommon.cntr = length - ret;
  1095. } else{
  1096. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE || ret == 0) {
  1097. } else{
  1098. mbedtls_fail_info(Threadmsg, ret);
  1099. ets_post(lwIPThreadPrio, NETCONN_EVENT_CLOSE,(uint32)Threadmsg);
  1100. }
  1101. }
  1102. }
  1103. /******************************************************************************
  1104. * FunctionName : espconn_ssl_disconnect
  1105. * Description : A new incoming connection has been disconnected.
  1106. * Parameters : espconn -- the espconn used to disconnect with host
  1107. * Returns : none
  1108. *******************************************************************************/
  1109. void espconn_ssl_disconnect(espconn_msg *Threadmsg)
  1110. {
  1111. lwIP_ASSERT(Threadmsg);
  1112. pmbedtls_msg mbedTLSMsg = Threadmsg->pssl;
  1113. lwIP_ASSERT(mbedTLSMsg);
  1114. mbedtls_net_free(&mbedTLSMsg->fd);
  1115. Threadmsg->pespconn->state = ESPCONN_CLOSE;
  1116. ets_post(lwIPThreadPrio, NETCONN_EVENT_CLOSE, (uint32)Threadmsg);
  1117. }
  1118. /*
  1119. * Checkup routine
  1120. */
  1121. int mbedtls_x509_test(int verbose, char *ca_crt, size_t ca_crt_len, char *cli_crt, size_t cli_crt_len)
  1122. {
  1123. #if defined(MBEDTLS_SHA1_C)
  1124. int ret;
  1125. uint32_t flags;
  1126. mbedtls_x509_crt cacert;
  1127. mbedtls_x509_crt clicert;
  1128. if( verbose != 0 )
  1129. os_printf( " X.509 certificate load: " );
  1130. mbedtls_x509_crt_init( &clicert );
  1131. ret = mbedtls_x509_crt_parse( &clicert, (const unsigned char *) cli_crt,
  1132. cli_crt_len );
  1133. if( ret != 0 )
  1134. {
  1135. if( verbose != 0 )
  1136. os_printf( "failed\n" );
  1137. return( ret );
  1138. }
  1139. mbedtls_x509_crt_init( &cacert );
  1140. ret = mbedtls_x509_crt_parse( &cacert, (const unsigned char *) ca_crt,
  1141. ca_crt_len );
  1142. if( ret != 0 )
  1143. {
  1144. if( verbose != 0 )
  1145. os_printf( "failed\n" );
  1146. return( ret );
  1147. }
  1148. if( verbose != 0 )
  1149. os_printf( "passed\n X.509 signature verify: ");
  1150. ret = mbedtls_x509_crt_verify( &clicert, &cacert, NULL, NULL, &flags, NULL, NULL );
  1151. if( ret != 0 )
  1152. {
  1153. if( verbose != 0 )
  1154. os_printf( "failed\n" );
  1155. return( ret );
  1156. }
  1157. if( verbose != 0 )
  1158. os_printf( "passed\n\n");
  1159. mbedtls_x509_crt_free( &cacert );
  1160. mbedtls_x509_crt_free( &clicert );
  1161. return( 0 );
  1162. #else
  1163. ((void) verbose);
  1164. return( 0 );
  1165. #endif /* MBEDTLS_CERTS_C && MBEDTLS_SHA1_C */
  1166. }
  1167. #endif