crypto.c 10 KB

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