tls.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. // Module for TLS
  2. #include "module.h"
  3. #if defined(CLIENT_SSL_ENABLE) && defined(LUA_USE_MODULES_NET)
  4. #include "lauxlib.h"
  5. #include "platform.h"
  6. #include "lmem.h"
  7. #include "c_string.h"
  8. #include "c_stdlib.h"
  9. #include "c_types.h"
  10. #include "mem.h"
  11. #include "lwip/ip_addr.h"
  12. #include "espconn.h"
  13. #include "sys/espconn_mbedtls.h"
  14. #include "lwip/err.h"
  15. #include "lwip/dns.h"
  16. #include "mbedtls/debug.h"
  17. #include "user_mbedtls.h"
  18. #ifdef HAVE_SSL_SERVER_CRT
  19. #include HAVE_SSL_SERVER_CRT
  20. #else
  21. __attribute__((section(".servercert.flash"))) unsigned char tls_server_cert_area[INTERNAL_FLASH_SECTOR_SIZE];
  22. #endif
  23. __attribute__((section(".clientcert.flash"))) unsigned char tls_client_cert_area[INTERNAL_FLASH_SECTOR_SIZE];
  24. extern int tls_socket_create( lua_State *L );
  25. extern const LUA_REG_TYPE tls_cert_map[];
  26. typedef struct {
  27. struct espconn *pesp_conn;
  28. int self_ref;
  29. int cb_connect_ref;
  30. int cb_reconnect_ref;
  31. int cb_disconnect_ref;
  32. int cb_sent_ref;
  33. int cb_receive_ref;
  34. int cb_dns_ref;
  35. } tls_socket_ud;
  36. int tls_socket_create( lua_State *L ) {
  37. tls_socket_ud *ud = (tls_socket_ud*) lua_newuserdata(L, sizeof(tls_socket_ud));
  38. ud->pesp_conn = NULL;
  39. ud->self_ref =
  40. ud->cb_connect_ref =
  41. ud->cb_reconnect_ref =
  42. ud->cb_disconnect_ref =
  43. ud->cb_sent_ref =
  44. ud->cb_receive_ref =
  45. ud->cb_dns_ref = LUA_NOREF;
  46. luaL_getmetatable(L, "tls.socket");
  47. lua_setmetatable(L, -2);
  48. return 1;
  49. }
  50. static void tls_socket_onconnect( struct espconn *pesp_conn ) {
  51. tls_socket_ud *ud = (tls_socket_ud *)pesp_conn->reverse;
  52. if (!ud || ud->self_ref == LUA_NOREF) return;
  53. if (ud->cb_connect_ref != LUA_NOREF) {
  54. lua_State *L = lua_getstate();
  55. lua_rawgeti(L, LUA_REGISTRYINDEX, ud->cb_connect_ref);
  56. lua_rawgeti(L, LUA_REGISTRYINDEX, ud->self_ref);
  57. lua_call(L, 1, 0);
  58. }
  59. }
  60. static void tls_socket_cleanup(tls_socket_ud *ud) {
  61. if (ud->pesp_conn) {
  62. espconn_secure_disconnect(ud->pesp_conn);
  63. if (ud->pesp_conn->proto.tcp) {
  64. c_free(ud->pesp_conn->proto.tcp);
  65. ud->pesp_conn->proto.tcp = NULL;
  66. }
  67. c_free(ud->pesp_conn);
  68. ud->pesp_conn = NULL;
  69. }
  70. lua_State *L = lua_getstate();
  71. lua_gc(L, LUA_GCSTOP, 0);
  72. luaL_unref(L, LUA_REGISTRYINDEX, ud->self_ref);
  73. ud->self_ref = LUA_NOREF;
  74. lua_gc(L, LUA_GCRESTART, 0);
  75. }
  76. static void tls_socket_ondisconnect( struct espconn *pesp_conn ) {
  77. tls_socket_ud *ud = (tls_socket_ud *)pesp_conn->reverse;
  78. if (!ud || ud->self_ref == LUA_NOREF) return;
  79. tls_socket_cleanup(ud);
  80. if (ud->cb_disconnect_ref != LUA_NOREF) {
  81. lua_State *L = lua_getstate();
  82. lua_rawgeti(L, LUA_REGISTRYINDEX, ud->cb_disconnect_ref);
  83. lua_rawgeti(L, LUA_REGISTRYINDEX, ud->self_ref);
  84. tls_socket_cleanup(ud);
  85. lua_call(L, 1, 0);
  86. } else tls_socket_cleanup(ud);
  87. }
  88. static void tls_socket_onreconnect( struct espconn *pesp_conn, s8 err ) {
  89. tls_socket_ud *ud = (tls_socket_ud *)pesp_conn->reverse;
  90. if (!ud || ud->self_ref == LUA_NOREF) return;
  91. if (ud->cb_reconnect_ref != LUA_NOREF) {
  92. const char* reason = NULL;
  93. switch (err) {
  94. case(ESPCONN_MEM): reason = "Out of memory"; break;
  95. case(ESPCONN_TIMEOUT): reason = "Timeout"; break;
  96. case(ESPCONN_RTE): reason = "Routing problem"; break;
  97. case(ESPCONN_ABRT): reason = "Connection aborted"; break;
  98. case(ESPCONN_RST): reason = "Connection reset"; break;
  99. case(ESPCONN_CLSD): reason = "Connection closed"; break;
  100. case(ESPCONN_HANDSHAKE): reason = "SSL handshake failed"; break;
  101. case(ESPCONN_SSL_INVALID_DATA): reason = "SSL application invalid"; break;
  102. }
  103. lua_State *L = lua_getstate();
  104. lua_rawgeti(L, LUA_REGISTRYINDEX, ud->cb_reconnect_ref);
  105. lua_rawgeti(L, LUA_REGISTRYINDEX, ud->self_ref);
  106. if (reason != NULL) {
  107. lua_pushstring(L, reason);
  108. } else {
  109. lua_pushnil(L);
  110. }
  111. tls_socket_cleanup(ud);
  112. lua_call(L, 2, 0);
  113. } else tls_socket_cleanup(ud);
  114. }
  115. static void tls_socket_onrecv( struct espconn *pesp_conn, char *buf, u16 length ) {
  116. tls_socket_ud *ud = (tls_socket_ud *)pesp_conn->reverse;
  117. if (!ud || ud->self_ref == LUA_NOREF) return;
  118. if (ud->cb_receive_ref != LUA_NOREF) {
  119. lua_State *L = lua_getstate();
  120. lua_rawgeti(L, LUA_REGISTRYINDEX, ud->cb_receive_ref);
  121. lua_rawgeti(L, LUA_REGISTRYINDEX, ud->self_ref);
  122. lua_pushlstring(L, buf, length);
  123. lua_call(L, 2, 0);
  124. }
  125. }
  126. static void tls_socket_onsent( struct espconn *pesp_conn ) {
  127. tls_socket_ud *ud = (tls_socket_ud *)pesp_conn->reverse;
  128. if (!ud || ud->self_ref == LUA_NOREF) return;
  129. if (ud->cb_sent_ref != LUA_NOREF) {
  130. lua_State *L = lua_getstate();
  131. lua_rawgeti(L, LUA_REGISTRYINDEX, ud->cb_sent_ref);
  132. lua_rawgeti(L, LUA_REGISTRYINDEX, ud->self_ref);
  133. lua_call(L, 1, 0);
  134. }
  135. }
  136. static void tls_socket_dns_cb( const char* domain, const ip_addr_t *ip_addr, tls_socket_ud *ud ) {
  137. if (ud->self_ref == LUA_NOREF) return;
  138. ip_addr_t addr;
  139. if (ip_addr) addr = *ip_addr;
  140. else addr.addr = 0xFFFFFFFF;
  141. lua_State *L = lua_getstate();
  142. if (ud->cb_dns_ref != LUA_NOREF) {
  143. lua_rawgeti(L, LUA_REGISTRYINDEX, ud->cb_dns_ref);
  144. lua_rawgeti(L, LUA_REGISTRYINDEX, ud->self_ref);
  145. if (addr.addr == 0xFFFFFFFF) {
  146. lua_pushnil(L);
  147. } else {
  148. char tmp[20];
  149. c_sprintf(tmp, IPSTR, IP2STR(&addr.addr));
  150. lua_pushstring(L, tmp);
  151. }
  152. lua_call(L, 2, 0);
  153. }
  154. if (addr.addr == 0xFFFFFFFF) {
  155. lua_gc(L, LUA_GCSTOP, 0);
  156. luaL_unref(L, LUA_REGISTRYINDEX, ud->self_ref);
  157. ud->self_ref = LUA_NOREF;
  158. lua_gc(L, LUA_GCRESTART, 0);
  159. } else {
  160. os_memcpy(ud->pesp_conn->proto.tcp->remote_ip, &addr.addr, 4);
  161. espconn_secure_connect(ud->pesp_conn);
  162. }
  163. }
  164. static int tls_socket_connect( lua_State *L ) {
  165. tls_socket_ud *ud = (tls_socket_ud *)luaL_checkudata(L, 1, "tls.socket");
  166. luaL_argcheck(L, ud, 1, "TLS socket expected");
  167. if(ud==NULL){
  168. NODE_DBG("userdata is nil.\n");
  169. return 0;
  170. }
  171. if (ud->pesp_conn) {
  172. return luaL_error(L, "already connected");
  173. }
  174. u16 port = luaL_checkinteger( L, 2 );
  175. size_t il;
  176. const char *domain = "127.0.0.1";
  177. if( lua_isstring(L, 3) )
  178. domain = luaL_checklstring( L, 3, &il );
  179. if (port == 0)
  180. return luaL_error(L, "invalid port");
  181. if (domain == NULL)
  182. return luaL_error(L, "invalid domain");
  183. ud->pesp_conn = (struct espconn*)c_zalloc(sizeof(struct espconn));
  184. if(!ud->pesp_conn)
  185. return luaL_error(L, "not enough memory");
  186. ud->pesp_conn->proto.udp = NULL;
  187. ud->pesp_conn->proto.tcp = (esp_tcp *)c_zalloc(sizeof(esp_tcp));
  188. if(!ud->pesp_conn->proto.tcp){
  189. c_free(ud->pesp_conn);
  190. ud->pesp_conn = NULL;
  191. return luaL_error(L, "not enough memory");
  192. }
  193. ud->pesp_conn->type = ESPCONN_TCP;
  194. ud->pesp_conn->state = ESPCONN_NONE;
  195. ud->pesp_conn->reverse = ud;
  196. ud->pesp_conn->proto.tcp->remote_port = port;
  197. espconn_regist_connectcb(ud->pesp_conn, (espconn_connect_callback)tls_socket_onconnect);
  198. espconn_regist_disconcb(ud->pesp_conn, (espconn_connect_callback)tls_socket_ondisconnect);
  199. espconn_regist_reconcb(ud->pesp_conn, (espconn_reconnect_callback)tls_socket_onreconnect);
  200. espconn_regist_recvcb(ud->pesp_conn, (espconn_recv_callback)tls_socket_onrecv);
  201. espconn_regist_sentcb(ud->pesp_conn, (espconn_sent_callback)tls_socket_onsent);
  202. if (ud->self_ref == LUA_NOREF) {
  203. lua_pushvalue(L, 1); // copy to the top of stack
  204. ud->self_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  205. }
  206. ip_addr_t addr;
  207. err_t err = dns_gethostbyname(domain, &addr, (dns_found_callback)tls_socket_dns_cb, ud);
  208. if (err == ERR_OK) {
  209. tls_socket_dns_cb(domain, &addr, ud);
  210. } else if (err != ERR_INPROGRESS) {
  211. tls_socket_dns_cb(domain, NULL, ud);
  212. }
  213. return 0;
  214. }
  215. static int tls_socket_on( lua_State *L ) {
  216. tls_socket_ud *ud = (tls_socket_ud *)luaL_checkudata(L, 1, "tls.socket");
  217. luaL_argcheck(L, ud, 1, "TLS socket expected");
  218. if(ud==NULL){
  219. NODE_DBG("userdata is nil.\n");
  220. return 0;
  221. }
  222. size_t sl;
  223. const char *method = luaL_checklstring( L, 2, &sl );
  224. if (method == NULL)
  225. return luaL_error( L, "wrong arg type" );
  226. luaL_checkanyfunction(L, 3);
  227. lua_pushvalue(L, 3); // copy argument (func) to the top of stack
  228. if (strcmp(method, "connection") == 0) {
  229. luaL_unref(L, LUA_REGISTRYINDEX, ud->cb_connect_ref);
  230. ud->cb_connect_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  231. } else if (strcmp(method, "disconnection") == 0) {
  232. luaL_unref(L, LUA_REGISTRYINDEX, ud->cb_disconnect_ref);
  233. ud->cb_disconnect_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  234. } else if (strcmp(method, "reconnection") == 0) {
  235. luaL_unref(L, LUA_REGISTRYINDEX, ud->cb_reconnect_ref);
  236. ud->cb_reconnect_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  237. } else if (strcmp(method, "receive") == 0) {
  238. luaL_unref(L, LUA_REGISTRYINDEX, ud->cb_receive_ref);
  239. ud->cb_receive_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  240. } else if (strcmp(method, "sent") == 0) {
  241. luaL_unref(L, LUA_REGISTRYINDEX, ud->cb_sent_ref);
  242. ud->cb_sent_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  243. } else if (strcmp(method, "dns") == 0) {
  244. luaL_unref(L, LUA_REGISTRYINDEX, ud->cb_dns_ref);
  245. ud->cb_dns_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  246. } else {
  247. return luaL_error(L, "invalid method");
  248. }
  249. return 0;
  250. }
  251. static int tls_socket_send( lua_State *L ) {
  252. tls_socket_ud *ud = (tls_socket_ud *)luaL_checkudata(L, 1, "tls.socket");
  253. luaL_argcheck(L, ud, 1, "TLS socket expected");
  254. if(ud==NULL){
  255. NODE_DBG("userdata is nil.\n");
  256. return 0;
  257. }
  258. if(ud->pesp_conn == NULL) {
  259. NODE_DBG("not connected");
  260. return 0;
  261. }
  262. size_t sl;
  263. const char* buf = luaL_checklstring(L, 2, &sl);
  264. if (!buf) {
  265. return luaL_error(L, "wrong arg type");
  266. }
  267. espconn_secure_send(ud->pesp_conn, (void*)buf, sl);
  268. return 0;
  269. }
  270. static int tls_socket_hold( lua_State *L ) {
  271. tls_socket_ud *ud = (tls_socket_ud *)luaL_checkudata(L, 1, "tls.socket");
  272. luaL_argcheck(L, ud, 1, "TLS socket expected");
  273. if(ud==NULL){
  274. NODE_DBG("userdata is nil.\n");
  275. return 0;
  276. }
  277. if(ud->pesp_conn == NULL) {
  278. NODE_DBG("not connected");
  279. return 0;
  280. }
  281. espconn_recv_hold(ud->pesp_conn);
  282. return 0;
  283. }
  284. static int tls_socket_unhold( lua_State *L ) {
  285. tls_socket_ud *ud = (tls_socket_ud *)luaL_checkudata(L, 1, "tls.socket");
  286. luaL_argcheck(L, ud, 1, "TLS socket expected");
  287. if(ud==NULL){
  288. NODE_DBG("userdata is nil.\n");
  289. return 0;
  290. }
  291. if(ud->pesp_conn == NULL) {
  292. NODE_DBG("not connected");
  293. return 0;
  294. }
  295. espconn_recv_unhold(ud->pesp_conn);
  296. return 0;
  297. }
  298. static int tls_socket_dns( lua_State *L ) {
  299. tls_socket_ud *ud = (tls_socket_ud *)luaL_checkudata(L, 1, "tls.socket");
  300. luaL_argcheck(L, ud, 1, "TLS socket expected");
  301. if(ud==NULL){
  302. NODE_DBG("userdata is nil.\n");
  303. return 0;
  304. }
  305. return 0;
  306. }
  307. static int tls_socket_getpeer( lua_State *L ) {
  308. tls_socket_ud *ud = (tls_socket_ud *)luaL_checkudata(L, 1, "tls.socket");
  309. luaL_argcheck(L, ud, 1, "TLS socket expected");
  310. if(ud==NULL){
  311. NODE_DBG("userdata is nil.\n");
  312. return 0;
  313. }
  314. if(ud->pesp_conn && ud->pesp_conn->proto.tcp->remote_port != 0){
  315. char temp[20] = {0};
  316. c_sprintf(temp, IPSTR, IP2STR( &(ud->pesp_conn->proto.tcp->remote_ip) ) );
  317. lua_pushstring( L, temp );
  318. lua_pushinteger( L, ud->pesp_conn->proto.tcp->remote_port );
  319. } else {
  320. lua_pushnil( L );
  321. lua_pushnil( L );
  322. }
  323. return 2;
  324. }
  325. static int tls_socket_close( lua_State *L ) {
  326. tls_socket_ud *ud = (tls_socket_ud *)luaL_checkudata(L, 1, "tls.socket");
  327. luaL_argcheck(L, ud, 1, "TLS socket expected");
  328. if(ud==NULL){
  329. NODE_DBG("userdata is nil.\n");
  330. return 0;
  331. }
  332. if (ud->pesp_conn) {
  333. espconn_secure_disconnect(ud->pesp_conn);
  334. }
  335. return 0;
  336. }
  337. static int tls_socket_delete( lua_State *L ) {
  338. tls_socket_ud *ud = (tls_socket_ud *)luaL_checkudata(L, 1, "tls.socket");
  339. luaL_argcheck(L, ud, 1, "TLS socket expected");
  340. if(ud==NULL){
  341. NODE_DBG("userdata is nil.\n");
  342. return 0;
  343. }
  344. if (ud->pesp_conn) {
  345. espconn_secure_disconnect(ud->pesp_conn);
  346. if (ud->pesp_conn->proto.tcp) {
  347. c_free(ud->pesp_conn->proto.tcp);
  348. ud->pesp_conn->proto.tcp = NULL;
  349. }
  350. c_free(ud->pesp_conn);
  351. ud->pesp_conn = NULL;
  352. }
  353. luaL_unref(L, LUA_REGISTRYINDEX, ud->cb_connect_ref);
  354. ud->cb_connect_ref = LUA_NOREF;
  355. luaL_unref(L, LUA_REGISTRYINDEX, ud->cb_disconnect_ref);
  356. ud->cb_disconnect_ref = LUA_NOREF;
  357. luaL_unref(L, LUA_REGISTRYINDEX, ud->cb_reconnect_ref);
  358. ud->cb_reconnect_ref = LUA_NOREF;
  359. luaL_unref(L, LUA_REGISTRYINDEX, ud->cb_dns_ref);
  360. ud->cb_dns_ref = LUA_NOREF;
  361. luaL_unref(L, LUA_REGISTRYINDEX, ud->cb_receive_ref);
  362. ud->cb_receive_ref = LUA_NOREF;
  363. luaL_unref(L, LUA_REGISTRYINDEX, ud->cb_sent_ref);
  364. ud->cb_sent_ref = LUA_NOREF;
  365. lua_gc(L, LUA_GCSTOP, 0);
  366. luaL_unref(L, LUA_REGISTRYINDEX, ud->self_ref);
  367. ud->self_ref = LUA_NOREF;
  368. lua_gc(L, LUA_GCRESTART, 0);
  369. return 0;
  370. }
  371. // Returns NULL on success, error message otherwise
  372. static const char *append_pem_blob(const char *pem, const char *type, uint8_t **buffer_p, uint8_t *buffer_limit, const char *name) {
  373. char unb64[256];
  374. memset(unb64, 0xff, sizeof(unb64));
  375. int i;
  376. for (i = 0; i < 64; i++) {
  377. unb64["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i]] = i;
  378. }
  379. if (!pem) {
  380. return "No PEM blob";
  381. }
  382. // Scan for -----BEGIN CERT
  383. pem = strstr(pem, "-----BEGIN ");
  384. if (!pem) {
  385. return "No PEM header";
  386. }
  387. if (strncmp(pem + 11, type, strlen(type))) {
  388. return "Wrong PEM type";
  389. }
  390. pem = strchr(pem, '\n');
  391. if (!pem) {
  392. return "Incorrect PEM format";
  393. }
  394. //
  395. // Base64 encoded data starts here
  396. // Get all the base64 data into a single buffer....
  397. // We will use the back end of the buffer....
  398. //
  399. uint8_t *buffer = *buffer_p;
  400. uint8_t *dest = buffer + 32 + 2; // Leave space for name and length
  401. int bitcount = 0;
  402. int accumulator = 0;
  403. for (; *pem && dest < buffer_limit; pem++) {
  404. int val = unb64[*(uint8_t*) pem];
  405. if (val & 0xC0) {
  406. // not a base64 character
  407. if (isspace(*(uint8_t*) pem)) {
  408. continue;
  409. }
  410. if (*pem == '=') {
  411. // just ignore -- at the end
  412. bitcount = 0;
  413. continue;
  414. }
  415. if (*pem == '-') {
  416. break;
  417. }
  418. return "Invalid character in PEM";
  419. } else {
  420. bitcount += 6;
  421. accumulator = (accumulator << 6) + val;
  422. if (bitcount >= 8) {
  423. bitcount -= 8;
  424. *dest++ = accumulator >> bitcount;
  425. }
  426. }
  427. }
  428. if (dest >= buffer_limit || strncmp(pem, "-----END ", 9) || strncmp(pem + 9, type, strlen(type)) || bitcount) {
  429. return "Invalid PEM format data";
  430. }
  431. size_t len = dest - (buffer + 32 + 2);
  432. memset(buffer, 0, 32);
  433. strcpy(buffer, name);
  434. buffer[32] = len & 0xff;
  435. buffer[33] = (len >> 8) & 0xff;
  436. *buffer_p = dest;
  437. return NULL;
  438. }
  439. static const char *fill_page_with_pem(lua_State *L, const unsigned char *flash_memory, int flash_offset, const char **types, const char **names)
  440. {
  441. uint8_t *buffer = luaM_malloc(L, INTERNAL_FLASH_SECTOR_SIZE);
  442. uint8_t *buffer_base = buffer;
  443. uint8_t *buffer_limit = buffer + INTERNAL_FLASH_SECTOR_SIZE;
  444. int argno;
  445. for (argno = 1; argno <= lua_gettop(L) && types[argno - 1]; argno++) {
  446. const char *pem = lua_tostring(L, argno);
  447. const char *error = append_pem_blob(pem, types[argno - 1], &buffer, buffer_limit, names[argno - 1]);
  448. if (error) {
  449. luaM_free(L, buffer_base);
  450. return error;
  451. }
  452. }
  453. memset(buffer, 0xff, buffer_limit - buffer);
  454. // Lets see if it matches what is already there....
  455. if (c_memcmp(buffer_base, flash_memory, INTERNAL_FLASH_SECTOR_SIZE) != 0) {
  456. // Starts being dangerous
  457. if (platform_flash_erase_sector(flash_offset / INTERNAL_FLASH_SECTOR_SIZE) != PLATFORM_OK) {
  458. luaM_free(L, buffer_base);
  459. return "Failed to erase sector";
  460. }
  461. if (platform_s_flash_write(buffer_base, flash_offset, INTERNAL_FLASH_SECTOR_SIZE) != INTERNAL_FLASH_SECTOR_SIZE) {
  462. luaM_free(L, buffer_base);
  463. return "Failed to write sector";
  464. }
  465. // ends being dangerous
  466. }
  467. luaM_free(L, buffer_base);
  468. return NULL;
  469. }
  470. // Lua: tls.cert.auth(true / false | PEM data [, PEM data] )
  471. static int tls_cert_auth(lua_State *L)
  472. {
  473. int enable;
  474. uint32_t flash_offset = platform_flash_mapped2phys((uint32_t) &tls_client_cert_area[0]);
  475. if ((flash_offset & 0xfff) || flash_offset > 0xff000 || INTERNAL_FLASH_SECTOR_SIZE != 0x1000) {
  476. // THis should never happen
  477. return luaL_error( L, "bad offset" );
  478. }
  479. if (lua_type(L, 1) == LUA_TSTRING) {
  480. const char *types[3] = { "CERTIFICATE", "RSA PRIVATE KEY", NULL };
  481. const char *names[2] = { "certificate", "private_key" };
  482. const char *error = fill_page_with_pem(L, &tls_client_cert_area[0], flash_offset, types, names);
  483. if (error) {
  484. return luaL_error(L, error);
  485. }
  486. enable = 1;
  487. } else {
  488. enable = lua_toboolean(L, 1);
  489. }
  490. bool rc;
  491. if (enable) {
  492. // See if there is a cert there
  493. if (tls_client_cert_area[0] == 0x00 || tls_client_cert_area[0] == 0xff) {
  494. return luaL_error( L, "no certificates found" );
  495. }
  496. rc = espconn_secure_cert_req_enable(1, flash_offset / INTERNAL_FLASH_SECTOR_SIZE);
  497. } else {
  498. rc = espconn_secure_cert_req_disable(1);
  499. }
  500. lua_pushboolean(L, rc);
  501. return 1;
  502. }
  503. // Lua: tls.cert.verify(true / false | PEM data [, PEM data] )
  504. static int tls_cert_verify(lua_State *L)
  505. {
  506. int enable;
  507. uint32_t flash_offset = platform_flash_mapped2phys((uint32_t) &tls_server_cert_area[0]);
  508. if ((flash_offset & 0xfff) || flash_offset > 0xff000 || INTERNAL_FLASH_SECTOR_SIZE != 0x1000) {
  509. // THis should never happen
  510. return luaL_error( L, "bad offset" );
  511. }
  512. if (lua_type(L, 1) == LUA_TSTRING) {
  513. const char *types[2] = { "CERTIFICATE", NULL };
  514. const char *names[1] = { "certificate" };
  515. const char *error = fill_page_with_pem(L, &tls_server_cert_area[0], flash_offset, types, names);
  516. if (error) {
  517. return luaL_error(L, error);
  518. }
  519. enable = 1;
  520. } else {
  521. enable = lua_toboolean(L, 1);
  522. }
  523. bool rc;
  524. if (enable) {
  525. // See if there is a cert there
  526. if (tls_server_cert_area[0] == 0x00 || tls_server_cert_area[0] == 0xff) {
  527. return luaL_error( L, "no certificates found" );
  528. }
  529. rc = espconn_secure_ca_enable(1, flash_offset / INTERNAL_FLASH_SECTOR_SIZE);
  530. } else {
  531. rc = espconn_secure_ca_disable(1);
  532. }
  533. lua_pushboolean(L, rc);
  534. return 1;
  535. }
  536. #if defined(MBEDTLS_DEBUG_C)
  537. static int tls_set_debug_threshold(lua_State *L) {
  538. mbedtls_debug_set_threshold(luaL_checkint( L, 1 ));
  539. return 0;
  540. }
  541. #endif
  542. static const LUA_REG_TYPE tls_socket_map[] = {
  543. { LSTRKEY( "connect" ), LFUNCVAL( tls_socket_connect ) },
  544. { LSTRKEY( "close" ), LFUNCVAL( tls_socket_close ) },
  545. { LSTRKEY( "on" ), LFUNCVAL( tls_socket_on ) },
  546. { LSTRKEY( "send" ), LFUNCVAL( tls_socket_send ) },
  547. { LSTRKEY( "hold" ), LFUNCVAL( tls_socket_hold ) },
  548. { LSTRKEY( "unhold" ), LFUNCVAL( tls_socket_unhold ) },
  549. { LSTRKEY( "dns" ), LFUNCVAL( tls_socket_dns ) },
  550. { LSTRKEY( "getpeer" ), LFUNCVAL( tls_socket_getpeer ) },
  551. { LSTRKEY( "__gc" ), LFUNCVAL( tls_socket_delete ) },
  552. { LSTRKEY( "__index" ), LROVAL( tls_socket_map ) },
  553. { LNILKEY, LNILVAL }
  554. };
  555. const LUA_REG_TYPE tls_cert_map[] = {
  556. { LSTRKEY( "verify" ), LFUNCVAL( tls_cert_verify ) },
  557. { LSTRKEY( "auth" ), LFUNCVAL( tls_cert_auth ) },
  558. { LSTRKEY( "__index" ), LROVAL( tls_cert_map ) },
  559. { LNILKEY, LNILVAL }
  560. };
  561. static const LUA_REG_TYPE tls_map[] = {
  562. { LSTRKEY( "createConnection" ), LFUNCVAL( tls_socket_create ) },
  563. #if defined(MBEDTLS_DEBUG_C)
  564. { LSTRKEY( "setDebug" ), LFUNCVAL( tls_set_debug_threshold ) },
  565. #endif
  566. { LSTRKEY( "cert" ), LROVAL( tls_cert_map ) },
  567. { LSTRKEY( "__metatable" ), LROVAL( tls_map ) },
  568. { LNILKEY, LNILVAL }
  569. };
  570. int luaopen_tls( lua_State *L ) {
  571. luaL_rometatable(L, "tls.socket", (void *)tls_socket_map); // create metatable for net.server
  572. espconn_secure_set_size(ESPCONN_CLIENT, 4096);
  573. return 0;
  574. }
  575. NODEMCU_MODULE(TLS, "tls", tls_map, luaopen_tls);
  576. #endif