crypto.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. // Module for cryptography
  2. #include <errno.h>
  3. #include "module.h"
  4. #include "lauxlib.h"
  5. #include "platform.h"
  6. #include <stdint.h>
  7. #include <stddef.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_getglobal(L, "encoder");
  46. luaL_checktype(L, -1, LUA_TTABLE);
  47. lua_getfield(L, -1, function);
  48. lua_insert(L, 1); //move function below the argument
  49. lua_pop(L, 1); //and dump the encoder rotable from stack.
  50. lua_call(L,1,1); // Normal call encoder.xxx(string)
  51. // (errors thrown back to caller)
  52. return 1;
  53. }
  54. static int crypto_base64_encode (lua_State* L) {
  55. platform_print_deprecation_note("crypto.toBase64", "in the next version");
  56. return call_encoder(L, "toBase64");
  57. }
  58. static int crypto_hex_encode (lua_State* L) {
  59. platform_print_deprecation_note("crypto.toHex", "in the next version");
  60. return call_encoder(L, "toHex");
  61. }
  62. #else
  63. static const char* bytes64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  64. /**
  65. * encoded = crypto.toBase64(raw)
  66. *
  67. * Encodes raw binary string as base64 string.
  68. */
  69. static int crypto_base64_encode( lua_State* L )
  70. {
  71. int len, i;
  72. const char* msg = luaL_checklstring(L, 1, &len);
  73. luaL_Buffer out;
  74. platform_print_deprecation_note("crypto.toBase64", "in the next version");
  75. luaL_buffinit(L, &out);
  76. for (i = 0; i < len; i += 3) {
  77. int a = msg[i];
  78. int b = (i + 1 < len) ? msg[i + 1] : 0;
  79. int c = (i + 2 < len) ? msg[i + 2] : 0;
  80. luaL_addchar(&out, bytes64[a >> 2]);
  81. luaL_addchar(&out, bytes64[((a & 3) << 4) | (b >> 4)]);
  82. luaL_addchar(&out, (i + 1 < len) ? bytes64[((b & 15) << 2) | (c >> 6)] : 61);
  83. luaL_addchar(&out, (i + 2 < len) ? bytes64[(c & 63)] : 61);
  84. }
  85. luaL_pushresult(&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, i;
  96. const char* msg = luaL_checklstring(L, 1, &len);
  97. luaL_Buffer out;
  98. platform_print_deprecation_note("crypto.toHex", "in the next version");
  99. luaL_buffinit(L, &out);
  100. for (i = 0; i < len; i++) {
  101. luaL_addchar(&out, crypto_hexbytes[msg[i] >> 4]);
  102. luaL_addchar(&out, crypto_hexbytes[msg[i] & 0xf]);
  103. }
  104. luaL_pushresult(&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, i;
  116. const char* msg = luaL_checklstring(L, 1, &len);
  117. const char* mask = luaL_checklstring(L, 2, &mask_len);
  118. luaL_Buffer b;
  119. if(mask_len <= 0)
  120. return luaL_error(L, "invalid argument: mask");
  121. luaL_buffinit(L, &b);
  122. for (i = 0; i < len; i++) {
  123. luaL_addchar(&b, msg[i] ^ mask[i % mask_len]);
  124. }
  125. luaL_pushresult(&b);
  126. return 1;
  127. }
  128. static inline int bad_mech (lua_State *L) { return luaL_error (L, "unknown hash mech"); }
  129. static inline int bad_mem (lua_State *L) { return luaL_error (L, "insufficient memory"); }
  130. static inline int bad_file (lua_State *L) { return luaL_error (L, "file does not exist"); }
  131. /* rawdigest = crypto.hash("MD5", str)
  132. * strdigest = crypto.toHex(rawdigest)
  133. */
  134. static int crypto_lhash (lua_State *L)
  135. {
  136. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  137. if (!mi)
  138. return bad_mech (L);
  139. size_t len = 0;
  140. const char *data = luaL_checklstring (L, 2, &len);
  141. uint8_t digest[mi->digest_size];
  142. if (crypto_hash (mi, data, len, digest) != 0)
  143. return bad_mem (L);
  144. lua_pushlstring (L, digest, sizeof (digest));
  145. return 1;
  146. }
  147. /* General Usage for extensible hash functions:
  148. * sha = crypto.new_hash("MD5")
  149. * sha.update("Data")
  150. * sha.update("Data2")
  151. * strdigest = crypto.toHex(sha.finalize())
  152. */
  153. #define WANT_HASH 0
  154. #define WANT_HMAC 1
  155. static int crypto_new_hash_hmac (lua_State *L, int what)
  156. {
  157. // get pointer to relevant hash_mechs table entry in app/crypto/digest.c. Note that
  158. // the size of the table needed is dependent on the the digest type
  159. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  160. if (!mi)
  161. return bad_mech (L);
  162. size_t len = 0, k_opad_len = 0, udlen;
  163. const char *key = NULL;
  164. uint8_t *k_opad = NULL;
  165. if (what == WANT_HMAC)
  166. { // The key and k_opad are only used for HMAC; these default to NULLs for HASH
  167. key = luaL_checklstring (L, 2, &len);
  168. k_opad_len = mi->block_size;
  169. }
  170. // create a userdatum with specific metatable. This comprises the ud header,
  171. // the encrypto context block, and an optional HMAC block as a single allocation
  172. // unit
  173. udlen = sizeof(digest_user_datum_t) + mi->ctx_size + k_opad_len;
  174. digest_user_datum_t *dudat = (digest_user_datum_t *)lua_newuserdata(L, udlen);
  175. luaL_getmetatable(L, "crypto.hash"); // and set its metatable to the crypto.hash table
  176. lua_setmetatable(L, -2);
  177. void *ctx = dudat + 1; // The context block immediately follows the digest_user_datum
  178. mi->create (ctx);
  179. if (what == WANT_HMAC) {
  180. // The k_opad block immediately follows the context block
  181. k_opad = (char *)ctx + mi->ctx_size;
  182. crypto_hmac_begin (ctx, mi, key, len, k_opad);
  183. }
  184. // Set pointers to the mechanics and CTX
  185. dudat->mech_info = mi;
  186. dudat->ctx = ctx;
  187. dudat->k_opad = k_opad;
  188. return 1; // Pass userdata object back
  189. }
  190. /* crypto.new_hash("MECHTYPE") */
  191. static int crypto_new_hash (lua_State *L)
  192. {
  193. return crypto_new_hash_hmac (L, WANT_HASH);
  194. }
  195. /* crypto.new_hmac("MECHTYPE", "KEY") */
  196. static int crypto_new_hmac (lua_State *L)
  197. {
  198. return crypto_new_hash_hmac (L, WANT_HMAC);
  199. }
  200. /* Called as object, params:
  201. 1 - userdata "this"
  202. 2 - new string to add to the hash state */
  203. static int crypto_hash_update (lua_State *L)
  204. {
  205. NODE_DBG("enter crypto_hash_update.\n");
  206. digest_user_datum_t *dudat;
  207. size_t sl;
  208. dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
  209. const digest_mech_info_t *mi = dudat->mech_info;
  210. size_t len = 0;
  211. const char *data = luaL_checklstring (L, 2, &len);
  212. mi->update (dudat->ctx, data, len);
  213. return 0; // No return value
  214. }
  215. /* Called as object, no params. Returns digest of default size. */
  216. static int crypto_hash_finalize (lua_State *L)
  217. {
  218. NODE_DBG("enter crypto_hash_update.\n");
  219. digest_user_datum_t *dudat;
  220. size_t sl;
  221. dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
  222. const digest_mech_info_t *mi = dudat->mech_info;
  223. uint8_t digest[mi->digest_size]; // Allocate as local
  224. if (dudat->k_opad)
  225. crypto_hmac_finalize (dudat->ctx, mi, dudat->k_opad, digest);
  226. else
  227. mi->finalize (digest, dudat->ctx);
  228. lua_pushlstring (L, digest, sizeof (digest));
  229. return 1;
  230. }
  231. static sint32_t vfs_read_wrap (int fd, void *ptr, size_t len)
  232. {
  233. return vfs_read (fd, ptr, len);
  234. }
  235. /* rawdigest = crypto.hash("MD5", filename)
  236. * strdigest = crypto.toHex(rawdigest)
  237. */
  238. static int crypto_flhash (lua_State *L)
  239. {
  240. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  241. if (!mi)
  242. return bad_mech (L);
  243. const char *filename = luaL_checkstring (L, 2);
  244. // Open the file
  245. int file_fd = vfs_open (filename, "r");
  246. if(!file_fd) {
  247. return bad_file(L);
  248. }
  249. // Compute hash
  250. uint8_t digest[mi->digest_size];
  251. int returncode = crypto_fhash (mi, &vfs_read_wrap, file_fd, digest);
  252. // Finish up
  253. vfs_close(file_fd);
  254. if (returncode == ENOMEM)
  255. return bad_mem (L);
  256. else if (returncode == EINVAL)
  257. return bad_mech(L);
  258. else
  259. lua_pushlstring (L, digest, sizeof (digest));
  260. return 1;
  261. }
  262. /* rawsignature = crypto.hmac("SHA1", str, key)
  263. * strsignature = crypto.toHex(rawsignature)
  264. */
  265. static int crypto_lhmac (lua_State *L)
  266. {
  267. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  268. if (!mi)
  269. return bad_mech (L);
  270. size_t len = 0;
  271. const char *data = luaL_checklstring (L, 2, &len);
  272. size_t klen = 0;
  273. const char *key = luaL_checklstring (L, 3, &klen);
  274. uint8_t digest[mi->digest_size];
  275. if (crypto_hmac (mi, data, len, key, klen, digest) != 0)
  276. return bad_mem (L);
  277. lua_pushlstring (L, digest, sizeof (digest));
  278. return 1;
  279. }
  280. static const crypto_mech_t *get_mech (lua_State *L, int idx)
  281. {
  282. const char *name = luaL_checkstring (L, idx);
  283. const crypto_mech_t *mech = crypto_encryption_mech (name);
  284. if (mech)
  285. return mech;
  286. luaL_error (L, "unknown cipher: %s", name);
  287. __builtin_unreachable ();
  288. }
  289. static int crypto_encdec (lua_State *L, bool enc)
  290. {
  291. const crypto_mech_t *mech = get_mech (L, 1);
  292. size_t klen, dlen, ivlen, bs = mech->block_size;
  293. const char *key = luaL_checklstring (L, 2, &klen);
  294. const char *data = luaL_checklstring (L, 3, &dlen);
  295. const char *iv = luaL_optlstring (L, 4, "", &ivlen);
  296. size_t outlen = ((dlen + bs -1) / bs) * bs;
  297. char *buf = luaM_newvector(L, outlen, char);
  298. crypto_op_t op = {
  299. key, klen,
  300. iv, ivlen,
  301. data, dlen,
  302. buf, outlen,
  303. enc ? OP_ENCRYPT : OP_DECRYPT
  304. };
  305. int status = mech->run (&op);
  306. lua_pushlstring (L, buf, outlen); /* discarded on error but what the hell */
  307. luaN_freearray(L, buf, outlen);
  308. return status ? 1 : luaL_error (L, "crypto op failed");
  309. }
  310. static int lcrypto_encrypt (lua_State *L)
  311. {
  312. return crypto_encdec (L, true);
  313. }
  314. static int lcrypto_decrypt (lua_State *L)
  315. {
  316. return crypto_encdec (L, false);
  317. }
  318. // Hash function map
  319. LROT_BEGIN(crypto_hash_map, NULL, LROT_MASK_INDEX)
  320. LROT_TABENTRY( __index, crypto_hash_map )
  321. LROT_FUNCENTRY( update, crypto_hash_update )
  322. LROT_FUNCENTRY( finalize, crypto_hash_finalize )
  323. LROT_END(crypto_hash_map, NULL, LROT_MASK_INDEX)
  324. // Module function map
  325. LROT_BEGIN(crypto, NULL, 0)
  326. LROT_FUNCENTRY( sha1, crypto_sha1 )
  327. LROT_FUNCENTRY( toBase64, crypto_base64_encode )
  328. LROT_FUNCENTRY( toHex, crypto_hex_encode )
  329. LROT_FUNCENTRY( mask, crypto_mask )
  330. LROT_FUNCENTRY( hash, crypto_lhash )
  331. LROT_FUNCENTRY( fhash, crypto_flhash )
  332. LROT_FUNCENTRY( new_hash, crypto_new_hash )
  333. LROT_FUNCENTRY( hmac, crypto_lhmac )
  334. LROT_FUNCENTRY( new_hmac, crypto_new_hmac )
  335. LROT_FUNCENTRY( encrypt, lcrypto_encrypt )
  336. LROT_FUNCENTRY( decrypt, lcrypto_decrypt )
  337. LROT_END(crypto, NULL, 0)
  338. int luaopen_crypto ( lua_State *L )
  339. {
  340. luaL_rometatable(L, "crypto.hash", LROT_TABLEREF(crypto_hash_map));
  341. return 0;
  342. }
  343. NODEMCU_MODULE(CRYPTO, "crypto", crypto, luaopen_crypto);