crypto.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. int i;
  119. char* copy = (char*)c_malloc(len);
  120. for (i = 0; i < len; i++) {
  121. copy[i] = msg[i] ^ mask[i % 4];
  122. }
  123. lua_pushlstring(L, copy, len);
  124. c_free(copy);
  125. return 1;
  126. }
  127. static inline int bad_mech (lua_State *L) { return luaL_error (L, "unknown hash mech"); }
  128. static inline int bad_mem (lua_State *L) { return luaL_error (L, "insufficient memory"); }
  129. static inline int bad_file (lua_State *L) { return luaL_error (L, "file does not exist"); }
  130. /* rawdigest = crypto.hash("MD5", str)
  131. * strdigest = crypto.toHex(rawdigest)
  132. */
  133. static int crypto_lhash (lua_State *L)
  134. {
  135. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  136. if (!mi)
  137. return bad_mech (L);
  138. size_t len = 0;
  139. const char *data = luaL_checklstring (L, 2, &len);
  140. uint8_t digest[mi->digest_size];
  141. if (crypto_hash (mi, data, len, digest) != 0)
  142. return bad_mem (L);
  143. lua_pushlstring (L, digest, sizeof (digest));
  144. return 1;
  145. }
  146. /* General Usage for extensible hash functions:
  147. * sha = crypto.new_hash("MD5")
  148. * sha.update("Data")
  149. * sha.update("Data2")
  150. * strdigest = crypto.toHex(sha.finalize())
  151. */
  152. #define WANT_HASH 0
  153. #define WANT_HMAC 1
  154. static int crypto_new_hash_hmac (lua_State *L, int what)
  155. {
  156. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  157. if (!mi)
  158. return bad_mech (L);
  159. size_t len = 0;
  160. const char *key = 0;
  161. uint8_t *k_opad = 0;
  162. if (what == WANT_HMAC)
  163. {
  164. key = luaL_checklstring (L, 2, &len);
  165. k_opad = luaM_malloc (L, mi->block_size);
  166. }
  167. void *ctx = luaM_malloc (L, mi->ctx_size);
  168. mi->create (ctx);
  169. if (what == WANT_HMAC)
  170. crypto_hmac_begin (ctx, mi, key, len, k_opad);
  171. // create a userdataum with specific metatable
  172. digest_user_datum_t *dudat = (digest_user_datum_t *)lua_newuserdata(L, sizeof(digest_user_datum_t));
  173. luaL_getmetatable(L, "crypto.hash");
  174. lua_setmetatable(L, -2);
  175. // Set pointers to the mechanics and CTX
  176. dudat->mech_info = mi;
  177. dudat->ctx = ctx;
  178. dudat->k_opad = k_opad;
  179. return 1; // Pass userdata object back
  180. }
  181. /* crypto.new_hash("MECHTYPE") */
  182. static int crypto_new_hash (lua_State *L)
  183. {
  184. return crypto_new_hash_hmac (L, WANT_HASH);
  185. }
  186. /* crypto.new_hmac("MECHTYPE", "KEY") */
  187. static int crypto_new_hmac (lua_State *L)
  188. {
  189. return crypto_new_hash_hmac (L, WANT_HMAC);
  190. }
  191. /* Called as object, params:
  192. 1 - userdata "this"
  193. 2 - new string to add to the hash state */
  194. static int crypto_hash_update (lua_State *L)
  195. {
  196. NODE_DBG("enter crypto_hash_update.\n");
  197. digest_user_datum_t *dudat;
  198. size_t sl;
  199. dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
  200. const digest_mech_info_t *mi = dudat->mech_info;
  201. size_t len = 0;
  202. const char *data = luaL_checklstring (L, 2, &len);
  203. mi->update (dudat->ctx, data, len);
  204. return 0; // No return value
  205. }
  206. /* Called as object, no params. Returns digest of default size. */
  207. static int crypto_hash_finalize (lua_State *L)
  208. {
  209. NODE_DBG("enter crypto_hash_update.\n");
  210. digest_user_datum_t *dudat;
  211. size_t sl;
  212. dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
  213. const digest_mech_info_t *mi = dudat->mech_info;
  214. uint8_t digest[mi->digest_size]; // Allocate as local
  215. if (dudat->k_opad)
  216. crypto_hmac_finalize (dudat->ctx, mi, dudat->k_opad, digest);
  217. else
  218. mi->finalize (digest, dudat->ctx);
  219. lua_pushlstring (L, digest, sizeof (digest));
  220. return 1;
  221. }
  222. /* Frees memory for the user datum and CTX hash state */
  223. static int crypto_hash_gcdelete (lua_State *L)
  224. {
  225. NODE_DBG("enter crypto_hash_delete.\n");
  226. digest_user_datum_t *dudat;
  227. dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
  228. // luaM_free() uses type info to obtain original size, so have to delve
  229. // one level deeper and explicitly pass the size due to void*
  230. luaM_realloc_ (L, dudat->ctx, dudat->mech_info->ctx_size, 0);
  231. luaM_free (L, dudat->k_opad);
  232. return 0;
  233. }
  234. static sint32_t vfs_read_wrap (int fd, void *ptr, size_t len)
  235. {
  236. return vfs_read (fd, ptr, len);
  237. }
  238. /* rawdigest = crypto.hash("MD5", filename)
  239. * strdigest = crypto.toHex(rawdigest)
  240. */
  241. static int crypto_flhash (lua_State *L)
  242. {
  243. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  244. if (!mi)
  245. return bad_mech (L);
  246. const char *filename = luaL_checkstring (L, 2);
  247. // Open the file
  248. int file_fd = vfs_open (filename, "r");
  249. if(!file_fd) {
  250. return bad_file(L);
  251. }
  252. // Compute hash
  253. uint8_t digest[mi->digest_size];
  254. int returncode = crypto_fhash (mi, &vfs_read_wrap, file_fd, digest);
  255. // Finish up
  256. vfs_close(file_fd);
  257. if (returncode == ENOMEM)
  258. return bad_mem (L);
  259. else if (returncode == EINVAL)
  260. return bad_mech(L);
  261. else
  262. lua_pushlstring (L, digest, sizeof (digest));
  263. return 1;
  264. }
  265. /* rawsignature = crypto.hmac("SHA1", str, key)
  266. * strsignature = crypto.toHex(rawsignature)
  267. */
  268. static int crypto_lhmac (lua_State *L)
  269. {
  270. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  271. if (!mi)
  272. return bad_mech (L);
  273. size_t len = 0;
  274. const char *data = luaL_checklstring (L, 2, &len);
  275. size_t klen = 0;
  276. const char *key = luaL_checklstring (L, 3, &klen);
  277. uint8_t digest[mi->digest_size];
  278. if (crypto_hmac (mi, data, len, key, klen, digest) != 0)
  279. return bad_mem (L);
  280. lua_pushlstring (L, digest, sizeof (digest));
  281. return 1;
  282. }
  283. static const crypto_mech_t *get_mech (lua_State *L, int idx)
  284. {
  285. const char *name = luaL_checkstring (L, idx);
  286. const crypto_mech_t *mech = crypto_encryption_mech (name);
  287. if (mech)
  288. return mech;
  289. luaL_error (L, "unknown cipher: %s", name);
  290. __builtin_unreachable ();
  291. }
  292. static int crypto_encdec (lua_State *L, bool enc)
  293. {
  294. const crypto_mech_t *mech = get_mech (L, 1);
  295. size_t klen;
  296. const char *key = luaL_checklstring (L, 2, &klen);
  297. size_t dlen;
  298. const char *data = luaL_checklstring (L, 3, &dlen);
  299. size_t ivlen;
  300. const char *iv = luaL_optlstring (L, 4, "", &ivlen);
  301. size_t bs = mech->block_size;
  302. size_t outlen = ((dlen + bs -1) / bs) * bs;
  303. char *buf = (char *)os_zalloc (outlen);
  304. if (!buf)
  305. return luaL_error (L, "crypto init failed");
  306. crypto_op_t op =
  307. {
  308. key, klen,
  309. iv, ivlen,
  310. data, dlen,
  311. buf, outlen,
  312. enc ? OP_ENCRYPT : OP_DECRYPT
  313. };
  314. if (!mech->run (&op))
  315. {
  316. os_free (buf);
  317. return luaL_error (L, "crypto op failed");
  318. }
  319. else
  320. {
  321. lua_pushlstring (L, buf, outlen);
  322. // note: if lua_pushlstring runs out of memory, we leak buf :(
  323. os_free (buf);
  324. return 1;
  325. }
  326. }
  327. static int lcrypto_encrypt (lua_State *L)
  328. {
  329. return crypto_encdec (L, true);
  330. }
  331. static int lcrypto_decrypt (lua_State *L)
  332. {
  333. return crypto_encdec (L, false);
  334. }
  335. // Hash function map
  336. static const LUA_REG_TYPE crypto_hash_map[] = {
  337. { LSTRKEY( "update" ), LFUNCVAL( crypto_hash_update ) },
  338. { LSTRKEY( "finalize" ), LFUNCVAL( crypto_hash_finalize ) },
  339. { LSTRKEY( "__gc" ), LFUNCVAL( crypto_hash_gcdelete ) },
  340. { LSTRKEY( "__index" ), LROVAL( crypto_hash_map ) },
  341. { LNILKEY, LNILVAL }
  342. };
  343. // Module function map
  344. static const LUA_REG_TYPE crypto_map[] = {
  345. { LSTRKEY( "sha1" ), LFUNCVAL( crypto_sha1 ) },
  346. { LSTRKEY( "toBase64" ), LFUNCVAL( crypto_base64_encode ) },
  347. { LSTRKEY( "toHex" ), LFUNCVAL( crypto_hex_encode ) },
  348. { LSTRKEY( "mask" ), LFUNCVAL( crypto_mask ) },
  349. { LSTRKEY( "hash" ), LFUNCVAL( crypto_lhash ) },
  350. { LSTRKEY( "fhash" ), LFUNCVAL( crypto_flhash ) },
  351. { LSTRKEY( "new_hash" ), LFUNCVAL( crypto_new_hash ) },
  352. { LSTRKEY( "hmac" ), LFUNCVAL( crypto_lhmac ) },
  353. { LSTRKEY( "new_hmac" ), LFUNCVAL( crypto_new_hmac ) },
  354. { LSTRKEY( "encrypt" ), LFUNCVAL( lcrypto_encrypt ) },
  355. { LSTRKEY( "decrypt" ), LFUNCVAL( lcrypto_decrypt ) },
  356. { LNILKEY, LNILVAL }
  357. };
  358. int luaopen_crypto ( lua_State *L )
  359. {
  360. luaL_rometatable(L, "crypto.hash", (void *)crypto_hash_map); // create metatable for crypto.hash
  361. return 0;
  362. }
  363. NODEMCU_MODULE(CRYPTO, "crypto", crypto_map, luaopen_crypto);