crypto.c 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. /**
  41. * masked = crypto.mask(message, mask)
  42. *
  43. * Apply a mask (repeated if shorter than message) as XOR to each byte.
  44. */
  45. static int crypto_mask( lua_State* L )
  46. {
  47. int len, mask_len, i;
  48. const char* msg = luaL_checklstring(L, 1, &len);
  49. const char* mask = luaL_checklstring(L, 2, &mask_len);
  50. luaL_Buffer b;
  51. if(mask_len <= 0)
  52. return luaL_error(L, "invalid argument: mask");
  53. luaL_buffinit(L, &b);
  54. for (i = 0; i < len; i++) {
  55. luaL_addchar(&b, msg[i] ^ mask[i % mask_len]);
  56. }
  57. luaL_pushresult(&b);
  58. return 1;
  59. }
  60. static inline int bad_mech (lua_State *L) { return luaL_error (L, "unknown hash mech"); }
  61. static inline int bad_mem (lua_State *L) { return luaL_error (L, "insufficient memory"); }
  62. static inline int bad_file (lua_State *L) { return luaL_error (L, "file does not exist"); }
  63. /* rawdigest = crypto.hash("MD5", str)
  64. * strdigest = encoder.toHex(rawdigest)
  65. */
  66. static int crypto_lhash (lua_State *L)
  67. {
  68. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  69. if (!mi)
  70. return bad_mech (L);
  71. size_t len = 0;
  72. const char *data = luaL_checklstring (L, 2, &len);
  73. uint8_t digest[mi->digest_size];
  74. if (crypto_hash (mi, data, len, digest) != 0)
  75. return bad_mem (L);
  76. lua_pushlstring (L, digest, sizeof (digest));
  77. return 1;
  78. }
  79. /* General Usage for extensible hash functions:
  80. * sha = crypto.new_hash("MD5")
  81. * sha.update("Data")
  82. * sha.update("Data2")
  83. * strdigest = encoder.toHex(sha.finalize())
  84. */
  85. #define WANT_HASH 0
  86. #define WANT_HMAC 1
  87. static int crypto_new_hash_hmac (lua_State *L, int what)
  88. {
  89. // get pointer to relevant hash_mechs table entry in app/crypto/digest.c. Note that
  90. // the size of the table needed is dependent on the the digest type
  91. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  92. if (!mi)
  93. return bad_mech (L);
  94. size_t len = 0, k_opad_len = 0, udlen;
  95. const char *key = NULL;
  96. uint8_t *k_opad = NULL;
  97. if (what == WANT_HMAC)
  98. { // The key and k_opad are only used for HMAC; these default to NULLs for HASH
  99. key = luaL_checklstring (L, 2, &len);
  100. k_opad_len = mi->block_size;
  101. }
  102. // create a userdatum with specific metatable. This comprises the ud header,
  103. // the encrypto context block, and an optional HMAC block as a single allocation
  104. // unit
  105. udlen = sizeof(digest_user_datum_t) + mi->ctx_size + k_opad_len;
  106. digest_user_datum_t *dudat = (digest_user_datum_t *)lua_newuserdata(L, udlen);
  107. luaL_getmetatable(L, "crypto.hash"); // and set its metatable to the crypto.hash table
  108. lua_setmetatable(L, -2);
  109. void *ctx = dudat + 1; // The context block immediately follows the digest_user_datum
  110. mi->create (ctx);
  111. if (what == WANT_HMAC) {
  112. // The k_opad block immediately follows the context block
  113. k_opad = (char *)ctx + mi->ctx_size;
  114. crypto_hmac_begin (ctx, mi, key, len, k_opad);
  115. }
  116. // Set pointers to the mechanics and CTX
  117. dudat->mech_info = mi;
  118. dudat->ctx = ctx;
  119. dudat->k_opad = k_opad;
  120. return 1; // Pass userdata object back
  121. }
  122. /* crypto.new_hash("MECHTYPE") */
  123. static int crypto_new_hash (lua_State *L)
  124. {
  125. return crypto_new_hash_hmac (L, WANT_HASH);
  126. }
  127. /* crypto.new_hmac("MECHTYPE", "KEY") */
  128. static int crypto_new_hmac (lua_State *L)
  129. {
  130. return crypto_new_hash_hmac (L, WANT_HMAC);
  131. }
  132. /* Called as object, params:
  133. 1 - userdata "this"
  134. 2 - new string to add to the hash state */
  135. static int crypto_hash_update (lua_State *L)
  136. {
  137. NODE_DBG("enter crypto_hash_update.\n");
  138. digest_user_datum_t *dudat;
  139. size_t sl;
  140. dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
  141. const digest_mech_info_t *mi = dudat->mech_info;
  142. size_t len = 0;
  143. const char *data = luaL_checklstring (L, 2, &len);
  144. mi->update (dudat->ctx, data, len);
  145. return 0; // No return value
  146. }
  147. /* Called as object, no params. Returns digest of default size. */
  148. static int crypto_hash_finalize (lua_State *L)
  149. {
  150. NODE_DBG("enter crypto_hash_update.\n");
  151. digest_user_datum_t *dudat;
  152. size_t sl;
  153. dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
  154. const digest_mech_info_t *mi = dudat->mech_info;
  155. uint8_t digest[mi->digest_size]; // Allocate as local
  156. if (dudat->k_opad)
  157. crypto_hmac_finalize (dudat->ctx, mi, dudat->k_opad, digest);
  158. else
  159. mi->finalize (digest, dudat->ctx);
  160. lua_pushlstring (L, digest, sizeof (digest));
  161. return 1;
  162. }
  163. static sint32_t vfs_read_wrap (int fd, void *ptr, size_t len)
  164. {
  165. return vfs_read (fd, ptr, len);
  166. }
  167. /* rawdigest = crypto.hash("MD5", filename)
  168. * strdigest = encoder.toHex(rawdigest)
  169. */
  170. static int crypto_flhash (lua_State *L)
  171. {
  172. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  173. if (!mi)
  174. return bad_mech (L);
  175. const char *filename = luaL_checkstring (L, 2);
  176. // Open the file
  177. int file_fd = vfs_open (filename, "r");
  178. if(!file_fd) {
  179. return bad_file(L);
  180. }
  181. // Compute hash
  182. uint8_t digest[mi->digest_size];
  183. int returncode = crypto_fhash (mi, &vfs_read_wrap, file_fd, digest);
  184. // Finish up
  185. vfs_close(file_fd);
  186. if (returncode == ENOMEM)
  187. return bad_mem (L);
  188. else if (returncode == EINVAL)
  189. return bad_mech(L);
  190. else
  191. lua_pushlstring (L, digest, sizeof (digest));
  192. return 1;
  193. }
  194. /* rawsignature = crypto.hmac("SHA1", str, key)
  195. * strsignature = encoder.toHex(rawsignature)
  196. */
  197. static int crypto_lhmac (lua_State *L)
  198. {
  199. const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  200. if (!mi)
  201. return bad_mech (L);
  202. size_t len = 0;
  203. const char *data = luaL_checklstring (L, 2, &len);
  204. size_t klen = 0;
  205. const char *key = luaL_checklstring (L, 3, &klen);
  206. uint8_t digest[mi->digest_size];
  207. if (crypto_hmac (mi, data, len, key, klen, digest) != 0)
  208. return bad_mem (L);
  209. lua_pushlstring (L, digest, sizeof (digest));
  210. return 1;
  211. }
  212. static const crypto_mech_t *get_mech (lua_State *L, int idx)
  213. {
  214. const char *name = luaL_checkstring (L, idx);
  215. const crypto_mech_t *mech = crypto_encryption_mech (name);
  216. if (mech)
  217. return mech;
  218. luaL_error (L, "unknown cipher: %s", name);
  219. __builtin_unreachable ();
  220. }
  221. static int crypto_encdec (lua_State *L, bool enc)
  222. {
  223. const crypto_mech_t *mech = get_mech (L, 1);
  224. size_t klen, dlen, ivlen, bs = mech->block_size;
  225. const char *key = luaL_checklstring (L, 2, &klen);
  226. const char *data = luaL_checklstring (L, 3, &dlen);
  227. const char *iv = luaL_optlstring (L, 4, "", &ivlen);
  228. size_t outlen = ((dlen + bs -1) / bs) * bs;
  229. char *buf = luaM_newvector(L, outlen, char);
  230. crypto_op_t op = {
  231. key, klen,
  232. iv, ivlen,
  233. data, dlen,
  234. buf, outlen,
  235. enc ? OP_ENCRYPT : OP_DECRYPT
  236. };
  237. int status = mech->run (&op);
  238. lua_pushlstring (L, buf, outlen); /* discarded on error but what the hell */
  239. luaN_freearray(L, buf, outlen);
  240. return status ? 1 : luaL_error (L, "crypto op failed");
  241. }
  242. static int lcrypto_encrypt (lua_State *L)
  243. {
  244. return crypto_encdec (L, true);
  245. }
  246. static int lcrypto_decrypt (lua_State *L)
  247. {
  248. return crypto_encdec (L, false);
  249. }
  250. // Hash function map
  251. LROT_BEGIN(crypto_hash_map, NULL, LROT_MASK_INDEX)
  252. LROT_TABENTRY( __index, crypto_hash_map )
  253. LROT_FUNCENTRY( update, crypto_hash_update )
  254. LROT_FUNCENTRY( finalize, crypto_hash_finalize )
  255. LROT_END(crypto_hash_map, NULL, LROT_MASK_INDEX)
  256. // Module function map
  257. LROT_BEGIN(crypto, NULL, 0)
  258. LROT_FUNCENTRY( sha1, crypto_sha1 )
  259. LROT_FUNCENTRY( mask, crypto_mask )
  260. LROT_FUNCENTRY( hash, crypto_lhash )
  261. LROT_FUNCENTRY( fhash, crypto_flhash )
  262. LROT_FUNCENTRY( new_hash, crypto_new_hash )
  263. LROT_FUNCENTRY( hmac, crypto_lhmac )
  264. LROT_FUNCENTRY( new_hmac, crypto_new_hmac )
  265. LROT_FUNCENTRY( encrypt, lcrypto_encrypt )
  266. LROT_FUNCENTRY( decrypt, lcrypto_decrypt )
  267. LROT_END(crypto, NULL, 0)
  268. int luaopen_crypto ( lua_State *L )
  269. {
  270. luaL_rometatable(L, "crypto.hash", LROT_TABLEREF(crypto_hash_map));
  271. return 0;
  272. }
  273. NODEMCU_MODULE(CRYPTO, "crypto", crypto, luaopen_crypto);