crypto.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. // Module for cryptography
  2. #include <c_errno.h>
  3. #include "module.h"
  4. #include "lauxlib.h"
  5. #include "platform.h"
  6. #include "c_types.h"
  7. #include "c_stdlib.h"
  8. #include "vfs.h"
  9. #include "../crypto/digests.h"
  10. #include "../crypto/mech.h"
  11. #include "lmem.h"
  12. #include "user_interface.h"
  13. #include "rom.h"
  14. typedef struct {
  15. const digest_mech_info_t *mech_info;
  16. void *ctx;
  17. uint8_t *k_opad;
  18. } digest_user_datum_t;
  19. /**
  20. * hash = crypto.sha1(input)
  21. *
  22. * Calculates raw SHA1 hash of input string.
  23. * Input is arbitrary string, output is raw 20-byte hash as string.
  24. */
  25. static int crypto_sha1( lua_State* L )
  26. {
  27. SHA1_CTX ctx;
  28. uint8_t digest[20];
  29. // Read the string from lua (with length)
  30. int len;
  31. const char* msg = luaL_checklstring(L, 1, &len);
  32. // Use the SHA* functions in the rom
  33. SHA1Init(&ctx);
  34. SHA1Update(&ctx, msg, len);
  35. SHA1Final(digest, &ctx);
  36. // Push the result as a lua string
  37. lua_pushlstring(L, digest, 20);
  38. return 1;
  39. }
  40. #ifdef LUA_USE_MODULES_ENCODER
  41. static int call_encoder( lua_State* L, const char *function ) {
  42. if (lua_gettop(L) != 1) {
  43. luaL_error(L, "%s must have one argument", function);
  44. }
  45. lua_getfield(L, LUA_GLOBALSINDEX, "encoder");
  46. if (!lua_istable(L, -1) && !lua_isrotable(L, -1)) { // also need table just in case encoder has been overloaded
  47. luaL_error(L, "Cannot find encoder.%s", function);
  48. }
  49. lua_getfield(L, -1, function);
  50. lua_insert(L, 1); //move function below the argument
  51. lua_pop(L, 1); //and dump the encoder rotable from stack.
  52. lua_call(L,1,1); // call encoder.xxx(string)
  53. return 1;
  54. }
  55. static int crypto_base64_encode (lua_State* L) {
  56. return call_encoder(L, "toBase64");
  57. }
  58. static int crypto_hex_encode (lua_State* L) {
  59. return call_encoder(L, "toHex");
  60. }
  61. #else
  62. static const char* bytes64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  63. /**
  64. * encoded = crypto.toBase64(raw)
  65. *
  66. * Encodes raw binary string as base64 string.
  67. */
  68. static int crypto_base64_encode( lua_State* L )
  69. {
  70. int len;
  71. const char* msg = luaL_checklstring(L, 1, &len);
  72. int blen = (len + 2) / 3 * 4;
  73. char* out = (char*)c_malloc(blen);
  74. int j = 0, i;
  75. for (i = 0; i < len; i += 3) {
  76. int a = msg[i];
  77. int b = (i + 1 < len) ? msg[i + 1] : 0;
  78. int c = (i + 2 < len) ? msg[i + 2] : 0;
  79. out[j++] = bytes64[a >> 2];
  80. out[j++] = bytes64[((a & 3) << 4) | (b >> 4)];
  81. out[j++] = (i + 1 < len) ? bytes64[((b & 15) << 2) | (c >> 6)] : 61;
  82. out[j++] = (i + 2 < len) ? bytes64[(c & 63)] : 61;
  83. }
  84. lua_pushlstring(L, out, j);
  85. c_free(out);
  86. return 1;
  87. }
  88. /**
  89. * encoded = crypto.toHex(raw)
  90. *
  91. * Encodes raw binary string as hex string.
  92. */
  93. static int crypto_hex_encode( lua_State* L)
  94. {
  95. int len;
  96. const char* msg = luaL_checklstring(L, 1, &len);
  97. char* out = (char*)c_malloc(len * 2);
  98. int i, j = 0;
  99. for (i = 0; i < len; i++) {
  100. out[j++] = crypto_hexbytes[msg[i] >> 4];
  101. out[j++] = crypto_hexbytes[msg[i] & 0xf];
  102. }
  103. lua_pushlstring(L, out, len*2);
  104. c_free(out);
  105. return 1;
  106. }
  107. #endif
  108. /**
  109. * masked = crypto.mask(message, mask)
  110. *
  111. * Apply a mask (repeated if shorter than message) as XOR to each byte.
  112. */
  113. static int crypto_mask( lua_State* L )
  114. {
  115. int len, mask_len;
  116. const char* msg = luaL_checklstring(L, 1, &len);
  117. const char* mask = luaL_checklstring(L, 2, &mask_len);
  118. if(mask_len <= 0)
  119. return luaL_error(L, "invalid argument: mask");
  120. int i;
  121. char* copy = (char*)c_malloc(len);
  122. for (i = 0; i < len; i++) {
  123. copy[i] = msg[i] ^ mask[i % mask_len];
  124. }
  125. lua_pushlstring(L, copy, len);
  126. c_free(copy);
  127. return 1;
  128. }
  129. static inline int bad_mech (lua_State *L) { return luaL_error (L, "unknown hash mech"); }
  130. static inline int bad_mem (lua_State *L) { return luaL_error (L, "insufficient memory"); }
  131. static inline int bad_file (lua_State *L) { return luaL_error (L, "file does not exist"); }
  132. /* rawdigest = crypto.hash("MD5", str)
  133. * strdigest = crypto.toHex(rawdigest)
  134. */
  135. static int crypto_lhash (lua_State *L)
  136. {
  137. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  138. if (!mi)
  139. return bad_mech (L);
  140. size_t len = 0;
  141. const char *data = luaL_checklstring (L, 2, &len);
  142. uint8_t digest[mi->digest_size];
  143. if (crypto_hash (mi, data, len, digest) != 0)
  144. return bad_mem (L);
  145. lua_pushlstring (L, digest, sizeof (digest));
  146. return 1;
  147. }
  148. /* General Usage for extensible hash functions:
  149. * sha = crypto.new_hash("MD5")
  150. * sha.update("Data")
  151. * sha.update("Data2")
  152. * strdigest = crypto.toHex(sha.finalize())
  153. */
  154. #define WANT_HASH 0
  155. #define WANT_HMAC 1
  156. static int crypto_new_hash_hmac (lua_State *L, int what)
  157. {
  158. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  159. if (!mi)
  160. return bad_mech (L);
  161. size_t len = 0;
  162. const char *key = 0;
  163. uint8_t *k_opad = 0;
  164. if (what == WANT_HMAC)
  165. {
  166. key = luaL_checklstring (L, 2, &len);
  167. k_opad = luaM_malloc (L, mi->block_size);
  168. }
  169. void *ctx = luaM_malloc (L, mi->ctx_size);
  170. mi->create (ctx);
  171. if (what == WANT_HMAC)
  172. crypto_hmac_begin (ctx, mi, key, len, k_opad);
  173. // create a userdataum with specific metatable
  174. digest_user_datum_t *dudat = (digest_user_datum_t *)lua_newuserdata(L, sizeof(digest_user_datum_t));
  175. luaL_getmetatable(L, "crypto.hash");
  176. lua_setmetatable(L, -2);
  177. // Set pointers to the mechanics and CTX
  178. dudat->mech_info = mi;
  179. dudat->ctx = ctx;
  180. dudat->k_opad = k_opad;
  181. return 1; // Pass userdata object back
  182. }
  183. /* crypto.new_hash("MECHTYPE") */
  184. static int crypto_new_hash (lua_State *L)
  185. {
  186. return crypto_new_hash_hmac (L, WANT_HASH);
  187. }
  188. /* crypto.new_hmac("MECHTYPE", "KEY") */
  189. static int crypto_new_hmac (lua_State *L)
  190. {
  191. return crypto_new_hash_hmac (L, WANT_HMAC);
  192. }
  193. /* Called as object, params:
  194. 1 - userdata "this"
  195. 2 - new string to add to the hash state */
  196. static int crypto_hash_update (lua_State *L)
  197. {
  198. NODE_DBG("enter crypto_hash_update.\n");
  199. digest_user_datum_t *dudat;
  200. size_t sl;
  201. dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
  202. const digest_mech_info_t *mi = dudat->mech_info;
  203. size_t len = 0;
  204. const char *data = luaL_checklstring (L, 2, &len);
  205. mi->update (dudat->ctx, data, len);
  206. return 0; // No return value
  207. }
  208. /* Called as object, no params. Returns digest of default size. */
  209. static int crypto_hash_finalize (lua_State *L)
  210. {
  211. NODE_DBG("enter crypto_hash_update.\n");
  212. digest_user_datum_t *dudat;
  213. size_t sl;
  214. dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
  215. const digest_mech_info_t *mi = dudat->mech_info;
  216. uint8_t digest[mi->digest_size]; // Allocate as local
  217. if (dudat->k_opad)
  218. crypto_hmac_finalize (dudat->ctx, mi, dudat->k_opad, digest);
  219. else
  220. mi->finalize (digest, dudat->ctx);
  221. lua_pushlstring (L, digest, sizeof (digest));
  222. return 1;
  223. }
  224. /* Frees memory for the user datum and CTX hash state */
  225. static int crypto_hash_gcdelete (lua_State *L)
  226. {
  227. NODE_DBG("enter crypto_hash_delete.\n");
  228. digest_user_datum_t *dudat;
  229. dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
  230. // luaM_free() uses type info to obtain original size, so have to delve
  231. // one level deeper and explicitly pass the size due to void*
  232. luaM_realloc_ (L, dudat->ctx, dudat->mech_info->ctx_size, 0);
  233. luaM_free (L, dudat->k_opad);
  234. return 0;
  235. }
  236. static sint32_t vfs_read_wrap (int fd, void *ptr, size_t len)
  237. {
  238. return vfs_read (fd, ptr, len);
  239. }
  240. /* rawdigest = crypto.hash("MD5", filename)
  241. * strdigest = crypto.toHex(rawdigest)
  242. */
  243. static int crypto_flhash (lua_State *L)
  244. {
  245. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  246. if (!mi)
  247. return bad_mech (L);
  248. const char *filename = luaL_checkstring (L, 2);
  249. // Open the file
  250. int file_fd = vfs_open (filename, "r");
  251. if(!file_fd) {
  252. return bad_file(L);
  253. }
  254. // Compute hash
  255. uint8_t digest[mi->digest_size];
  256. int returncode = crypto_fhash (mi, &vfs_read_wrap, file_fd, digest);
  257. // Finish up
  258. vfs_close(file_fd);
  259. if (returncode == ENOMEM)
  260. return bad_mem (L);
  261. else if (returncode == EINVAL)
  262. return bad_mech(L);
  263. else
  264. lua_pushlstring (L, digest, sizeof (digest));
  265. return 1;
  266. }
  267. /* rawsignature = crypto.hmac("SHA1", str, key)
  268. * strsignature = crypto.toHex(rawsignature)
  269. */
  270. static int crypto_lhmac (lua_State *L)
  271. {
  272. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  273. if (!mi)
  274. return bad_mech (L);
  275. size_t len = 0;
  276. const char *data = luaL_checklstring (L, 2, &len);
  277. size_t klen = 0;
  278. const char *key = luaL_checklstring (L, 3, &klen);
  279. uint8_t digest[mi->digest_size];
  280. if (crypto_hmac (mi, data, len, key, klen, digest) != 0)
  281. return bad_mem (L);
  282. lua_pushlstring (L, digest, sizeof (digest));
  283. return 1;
  284. }
  285. static const crypto_mech_t *get_mech (lua_State *L, int idx)
  286. {
  287. const char *name = luaL_checkstring (L, idx);
  288. const crypto_mech_t *mech = crypto_encryption_mech (name);
  289. if (mech)
  290. return mech;
  291. luaL_error (L, "unknown cipher: %s", name);
  292. __builtin_unreachable ();
  293. }
  294. static int crypto_encdec (lua_State *L, bool enc)
  295. {
  296. const crypto_mech_t *mech = get_mech (L, 1);
  297. size_t klen;
  298. const char *key = luaL_checklstring (L, 2, &klen);
  299. size_t dlen;
  300. const char *data = luaL_checklstring (L, 3, &dlen);
  301. size_t ivlen;
  302. const char *iv = luaL_optlstring (L, 4, "", &ivlen);
  303. size_t bs = mech->block_size;
  304. size_t outlen = ((dlen + bs -1) / bs) * bs;
  305. char *buf = (char *)os_zalloc (outlen);
  306. if (!buf)
  307. return luaL_error (L, "crypto init failed");
  308. crypto_op_t op =
  309. {
  310. key, klen,
  311. iv, ivlen,
  312. data, dlen,
  313. buf, outlen,
  314. enc ? OP_ENCRYPT : OP_DECRYPT
  315. };
  316. if (!mech->run (&op))
  317. {
  318. os_free (buf);
  319. return luaL_error (L, "crypto op failed");
  320. }
  321. else
  322. {
  323. lua_pushlstring (L, buf, outlen);
  324. // note: if lua_pushlstring runs out of memory, we leak buf :(
  325. os_free (buf);
  326. return 1;
  327. }
  328. }
  329. static int lcrypto_encrypt (lua_State *L)
  330. {
  331. return crypto_encdec (L, true);
  332. }
  333. static int lcrypto_decrypt (lua_State *L)
  334. {
  335. return crypto_encdec (L, false);
  336. }
  337. // Hash function map
  338. static const LUA_REG_TYPE crypto_hash_map[] = {
  339. { LSTRKEY( "update" ), LFUNCVAL( crypto_hash_update ) },
  340. { LSTRKEY( "finalize" ), LFUNCVAL( crypto_hash_finalize ) },
  341. { LSTRKEY( "__gc" ), LFUNCVAL( crypto_hash_gcdelete ) },
  342. { LSTRKEY( "__index" ), LROVAL( crypto_hash_map ) },
  343. { LNILKEY, LNILVAL }
  344. };
  345. // Module function map
  346. static const LUA_REG_TYPE crypto_map[] = {
  347. { LSTRKEY( "sha1" ), LFUNCVAL( crypto_sha1 ) },
  348. { LSTRKEY( "toBase64" ), LFUNCVAL( crypto_base64_encode ) },
  349. { LSTRKEY( "toHex" ), LFUNCVAL( crypto_hex_encode ) },
  350. { LSTRKEY( "mask" ), LFUNCVAL( crypto_mask ) },
  351. { LSTRKEY( "hash" ), LFUNCVAL( crypto_lhash ) },
  352. { LSTRKEY( "fhash" ), LFUNCVAL( crypto_flhash ) },
  353. { LSTRKEY( "new_hash" ), LFUNCVAL( crypto_new_hash ) },
  354. { LSTRKEY( "hmac" ), LFUNCVAL( crypto_lhmac ) },
  355. { LSTRKEY( "new_hmac" ), LFUNCVAL( crypto_new_hmac ) },
  356. { LSTRKEY( "encrypt" ), LFUNCVAL( lcrypto_encrypt ) },
  357. { LSTRKEY( "decrypt" ), LFUNCVAL( lcrypto_decrypt ) },
  358. { LNILKEY, LNILVAL }
  359. };
  360. int luaopen_crypto ( lua_State *L )
  361. {
  362. luaL_rometatable(L, "crypto.hash", (void *)crypto_hash_map); // create metatable for crypto.hash
  363. return 0;
  364. }
  365. NODEMCU_MODULE(CRYPTO, "crypto", crypto_map, luaopen_crypto);