moducryptolib.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2017-2018 Paul Sokolovsky
  7. * Copyright (c) 2018 Yonatan Goldschmidt
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. */
  27. #include "py/mpconfig.h"
  28. #if MICROPY_PY_UCRYPTOLIB
  29. #include <assert.h>
  30. #include <string.h>
  31. #include "py/runtime.h"
  32. // This module implements crypto ciphers API, roughly following
  33. // https://www.python.org/dev/peps/pep-0272/ . Exact implementation
  34. // of PEP 272 can be made with a simple wrapper which adds all the
  35. // needed boilerplate.
  36. // values follow PEP 272
  37. enum {
  38. UCRYPTOLIB_MODE_ECB = 1,
  39. UCRYPTOLIB_MODE_CBC = 2,
  40. UCRYPTOLIB_MODE_CTR = 6,
  41. };
  42. struct ctr_params {
  43. // counter is the IV of the AES context.
  44. size_t offset; // in encrypted_counter
  45. // encrypted counter
  46. uint8_t encrypted_counter[16];
  47. };
  48. #if MICROPY_SSL_AXTLS
  49. #include "lib/axtls/crypto/crypto.h"
  50. #define AES_CTX_IMPL AES_CTX
  51. #endif
  52. #if MICROPY_SSL_MBEDTLS
  53. #include <mbedtls/aes.h>
  54. // we can't run mbedtls AES key schedule until we know whether we're used for encrypt or decrypt.
  55. // therefore, we store the key & keysize and on the first call to encrypt/decrypt we override them
  56. // with the mbedtls_aes_context, as they are not longer required. (this is done to save space)
  57. struct mbedtls_aes_ctx_with_key {
  58. union {
  59. mbedtls_aes_context mbedtls_ctx;
  60. struct {
  61. uint8_t key[32];
  62. uint8_t keysize;
  63. } init_data;
  64. } u;
  65. unsigned char iv[16];
  66. };
  67. #define AES_CTX_IMPL struct mbedtls_aes_ctx_with_key
  68. #endif
  69. typedef struct _mp_obj_aes_t {
  70. mp_obj_base_t base;
  71. AES_CTX_IMPL ctx;
  72. uint8_t block_mode: 6;
  73. #define AES_KEYTYPE_NONE 0
  74. #define AES_KEYTYPE_ENC 1
  75. #define AES_KEYTYPE_DEC 2
  76. uint8_t key_type: 2;
  77. } mp_obj_aes_t;
  78. static inline bool is_ctr_mode(int block_mode) {
  79. #if MICROPY_PY_UCRYPTOLIB_CTR
  80. return block_mode == UCRYPTOLIB_MODE_CTR;
  81. #else
  82. return false;
  83. #endif
  84. }
  85. static inline struct ctr_params *ctr_params_from_aes(mp_obj_aes_t *o) {
  86. // ctr_params follows aes object struct
  87. return (struct ctr_params*)&o[1];
  88. }
  89. #if MICROPY_SSL_AXTLS
  90. STATIC void aes_initial_set_key_impl(AES_CTX_IMPL *ctx, const uint8_t *key, size_t keysize, const uint8_t iv[16]) {
  91. assert(16 == keysize || 32 == keysize);
  92. AES_set_key(ctx, key, iv, (16 == keysize) ? AES_MODE_128 : AES_MODE_256);
  93. }
  94. STATIC void aes_final_set_key_impl(AES_CTX_IMPL *ctx, bool encrypt) {
  95. if (!encrypt) {
  96. AES_convert_key(ctx);
  97. }
  98. }
  99. STATIC void aes_process_ecb_impl(AES_CTX_IMPL *ctx, const uint8_t in[16], uint8_t out[16], bool encrypt) {
  100. memcpy(out, in, 16);
  101. // We assume that out (vstr.buf or given output buffer) is uint32_t aligned
  102. uint32_t *p = (uint32_t*)out;
  103. // axTLS likes it weird and complicated with byteswaps
  104. for (int i = 0; i < 4; i++) {
  105. p[i] = MP_HTOBE32(p[i]);
  106. }
  107. if (encrypt) {
  108. AES_encrypt(ctx, p);
  109. } else {
  110. AES_decrypt(ctx, p);
  111. }
  112. for (int i = 0; i < 4; i++) {
  113. p[i] = MP_BE32TOH(p[i]);
  114. }
  115. }
  116. STATIC void aes_process_cbc_impl(AES_CTX_IMPL *ctx, const uint8_t *in, uint8_t *out, size_t in_len, bool encrypt) {
  117. if (encrypt) {
  118. AES_cbc_encrypt(ctx, in, out, in_len);
  119. } else {
  120. AES_cbc_decrypt(ctx, in, out, in_len);
  121. }
  122. }
  123. #if MICROPY_PY_UCRYPTOLIB_CTR
  124. // axTLS doesn't have CTR support out of the box. This implements the counter part using the ECB primitive.
  125. STATIC void aes_process_ctr_impl(AES_CTX_IMPL *ctx, const uint8_t *in, uint8_t *out, size_t in_len, struct ctr_params *ctr_params) {
  126. size_t n = ctr_params->offset;
  127. uint8_t *const counter = ctx->iv;
  128. while (in_len--) {
  129. if (n == 0) {
  130. aes_process_ecb_impl(ctx, counter, ctr_params->encrypted_counter, true);
  131. // increment the 128-bit counter
  132. for (int i = 15; i >= 0; --i) {
  133. if (++counter[i] != 0) {
  134. break;
  135. }
  136. }
  137. }
  138. *out++ = *in++ ^ ctr_params->encrypted_counter[n];
  139. n = (n + 1) & 0xf;
  140. }
  141. ctr_params->offset = n;
  142. }
  143. #endif
  144. #endif
  145. #if MICROPY_SSL_MBEDTLS
  146. STATIC void aes_initial_set_key_impl(AES_CTX_IMPL *ctx, const uint8_t *key, size_t keysize, const uint8_t iv[16]) {
  147. ctx->u.init_data.keysize = keysize;
  148. memcpy(ctx->u.init_data.key, key, keysize);
  149. if (NULL != iv) {
  150. memcpy(ctx->iv, iv, sizeof(ctx->iv));
  151. }
  152. }
  153. STATIC void aes_final_set_key_impl(AES_CTX_IMPL *ctx, bool encrypt) {
  154. // first, copy key aside
  155. uint8_t key[32];
  156. uint8_t keysize = ctx->u.init_data.keysize;
  157. memcpy(key, ctx->u.init_data.key, keysize);
  158. // now, override key with the mbedtls context object
  159. mbedtls_aes_init(&ctx->u.mbedtls_ctx);
  160. // setkey call will succeed, we've already checked the keysize earlier.
  161. assert(16 == keysize || 32 == keysize);
  162. if (encrypt) {
  163. mbedtls_aes_setkey_enc(&ctx->u.mbedtls_ctx, key, keysize * 8);
  164. } else {
  165. mbedtls_aes_setkey_dec(&ctx->u.mbedtls_ctx, key, keysize * 8);
  166. }
  167. }
  168. STATIC void aes_process_ecb_impl(AES_CTX_IMPL *ctx, const uint8_t in[16], uint8_t out[16], bool encrypt) {
  169. mbedtls_aes_crypt_ecb(&ctx->u.mbedtls_ctx, encrypt ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT, in, out);
  170. }
  171. STATIC void aes_process_cbc_impl(AES_CTX_IMPL *ctx, const uint8_t *in, uint8_t *out, size_t in_len, bool encrypt) {
  172. mbedtls_aes_crypt_cbc(&ctx->u.mbedtls_ctx, encrypt ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT, in_len, ctx->iv, in, out);
  173. }
  174. #if MICROPY_PY_UCRYPTOLIB_CTR
  175. STATIC void aes_process_ctr_impl(AES_CTX_IMPL *ctx, const uint8_t *in, uint8_t *out, size_t in_len, struct ctr_params *ctr_params) {
  176. mbedtls_aes_crypt_ctr(&ctx->u.mbedtls_ctx, in_len, &ctr_params->offset, ctx->iv, ctr_params->encrypted_counter, in, out);
  177. }
  178. #endif
  179. #endif
  180. STATIC mp_obj_t ucryptolib_aes_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  181. mp_arg_check_num(n_args, n_kw, 2, 3, false);
  182. const mp_int_t block_mode = mp_obj_get_int(args[1]);
  183. switch (block_mode) {
  184. case UCRYPTOLIB_MODE_ECB:
  185. case UCRYPTOLIB_MODE_CBC:
  186. #if MICROPY_PY_UCRYPTOLIB_CTR
  187. case UCRYPTOLIB_MODE_CTR:
  188. #endif
  189. break;
  190. default:
  191. mp_raise_ValueError("mode");
  192. }
  193. mp_obj_aes_t *o = m_new_obj_var(mp_obj_aes_t, struct ctr_params, !!is_ctr_mode(block_mode));
  194. o->base.type = type;
  195. o->block_mode = block_mode;
  196. o->key_type = AES_KEYTYPE_NONE;
  197. mp_buffer_info_t keyinfo;
  198. mp_get_buffer_raise(args[0], &keyinfo, MP_BUFFER_READ);
  199. if (32 != keyinfo.len && 16 != keyinfo.len) {
  200. mp_raise_ValueError("key");
  201. }
  202. mp_buffer_info_t ivinfo;
  203. ivinfo.buf = NULL;
  204. if (n_args > 2 && args[2] != mp_const_none) {
  205. mp_get_buffer_raise(args[2], &ivinfo, MP_BUFFER_READ);
  206. if (16 != ivinfo.len) {
  207. mp_raise_ValueError("IV");
  208. }
  209. } else if (o->block_mode == UCRYPTOLIB_MODE_CBC || is_ctr_mode(o->block_mode)) {
  210. mp_raise_ValueError("IV");
  211. }
  212. if (is_ctr_mode(block_mode)) {
  213. ctr_params_from_aes(o)->offset = 0;
  214. }
  215. aes_initial_set_key_impl(&o->ctx, keyinfo.buf, keyinfo.len, ivinfo.buf);
  216. return MP_OBJ_FROM_PTR(o);
  217. }
  218. STATIC mp_obj_t aes_process(size_t n_args, const mp_obj_t *args, bool encrypt) {
  219. mp_obj_aes_t *self = MP_OBJ_TO_PTR(args[0]);
  220. mp_obj_t in_buf = args[1];
  221. mp_obj_t out_buf = MP_OBJ_NULL;
  222. if (n_args > 2) {
  223. out_buf = args[2];
  224. }
  225. mp_buffer_info_t in_bufinfo;
  226. mp_get_buffer_raise(in_buf, &in_bufinfo, MP_BUFFER_READ);
  227. if (!is_ctr_mode(self->block_mode) && in_bufinfo.len % 16 != 0) {
  228. mp_raise_ValueError("blksize % 16");
  229. }
  230. vstr_t vstr;
  231. mp_buffer_info_t out_bufinfo;
  232. uint8_t *out_buf_ptr;
  233. if (out_buf != MP_OBJ_NULL) {
  234. mp_get_buffer_raise(out_buf, &out_bufinfo, MP_BUFFER_WRITE);
  235. if (out_bufinfo.len < in_bufinfo.len) {
  236. mp_raise_ValueError("output too small");
  237. }
  238. out_buf_ptr = out_bufinfo.buf;
  239. } else {
  240. vstr_init_len(&vstr, in_bufinfo.len);
  241. out_buf_ptr = (uint8_t*)vstr.buf;
  242. }
  243. if (AES_KEYTYPE_NONE == self->key_type) {
  244. // always set key for encryption if CTR mode.
  245. const bool encrypt_mode = encrypt || is_ctr_mode(self->block_mode);
  246. aes_final_set_key_impl(&self->ctx, encrypt_mode);
  247. self->key_type = encrypt ? AES_KEYTYPE_ENC : AES_KEYTYPE_DEC;
  248. } else {
  249. if ((encrypt && self->key_type == AES_KEYTYPE_DEC) ||
  250. (!encrypt && self->key_type == AES_KEYTYPE_ENC)) {
  251. mp_raise_ValueError("can't encrypt & decrypt");
  252. }
  253. }
  254. switch (self->block_mode) {
  255. case UCRYPTOLIB_MODE_ECB: {
  256. uint8_t *in = in_bufinfo.buf, *out = out_buf_ptr;
  257. uint8_t *top = in + in_bufinfo.len;
  258. for (; in < top; in += 16, out += 16) {
  259. aes_process_ecb_impl(&self->ctx, in, out, encrypt);
  260. }
  261. break;
  262. }
  263. case UCRYPTOLIB_MODE_CBC:
  264. aes_process_cbc_impl(&self->ctx, in_bufinfo.buf, out_buf_ptr, in_bufinfo.len, encrypt);
  265. break;
  266. #if MICROPY_PY_UCRYPTOLIB_CTR
  267. case UCRYPTOLIB_MODE_CTR:
  268. aes_process_ctr_impl(&self->ctx, in_bufinfo.buf, out_buf_ptr, in_bufinfo.len,
  269. ctr_params_from_aes(self));
  270. break;
  271. #endif
  272. }
  273. if (out_buf != MP_OBJ_NULL) {
  274. return out_buf;
  275. }
  276. return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
  277. }
  278. STATIC mp_obj_t ucryptolib_aes_encrypt(size_t n_args, const mp_obj_t *args) {
  279. return aes_process(n_args, args, true);
  280. }
  281. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ucryptolib_aes_encrypt_obj, 2, 3, ucryptolib_aes_encrypt);
  282. STATIC mp_obj_t ucryptolib_aes_decrypt(size_t n_args, const mp_obj_t *args) {
  283. return aes_process(n_args, args, false);
  284. }
  285. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ucryptolib_aes_decrypt_obj, 2, 3, ucryptolib_aes_decrypt);
  286. STATIC const mp_rom_map_elem_t ucryptolib_aes_locals_dict_table[] = {
  287. { MP_ROM_QSTR(MP_QSTR_encrypt), MP_ROM_PTR(&ucryptolib_aes_encrypt_obj) },
  288. { MP_ROM_QSTR(MP_QSTR_decrypt), MP_ROM_PTR(&ucryptolib_aes_decrypt_obj) },
  289. };
  290. STATIC MP_DEFINE_CONST_DICT(ucryptolib_aes_locals_dict, ucryptolib_aes_locals_dict_table);
  291. STATIC const mp_obj_type_t ucryptolib_aes_type = {
  292. { &mp_type_type },
  293. .name = MP_QSTR_aes,
  294. .make_new = ucryptolib_aes_make_new,
  295. .locals_dict = (void*)&ucryptolib_aes_locals_dict,
  296. };
  297. STATIC const mp_rom_map_elem_t mp_module_ucryptolib_globals_table[] = {
  298. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ucryptolib) },
  299. { MP_ROM_QSTR(MP_QSTR_aes), MP_ROM_PTR(&ucryptolib_aes_type) },
  300. #if MICROPY_PY_UCRYPTOLIB_CONSTS
  301. { MP_ROM_QSTR(MP_QSTR_MODE_ECB), MP_ROM_INT(UCRYPTOLIB_MODE_ECB) },
  302. { MP_ROM_QSTR(MP_QSTR_MODE_CBC), MP_ROM_INT(UCRYPTOLIB_MODE_CBC) },
  303. #if MICROPY_PY_UCRYPTOLIB_CTR
  304. { MP_ROM_QSTR(MP_QSTR_MODE_CTR), MP_ROM_INT(UCRYPTOLIB_MODE_CTR) },
  305. #endif
  306. #endif
  307. };
  308. STATIC MP_DEFINE_CONST_DICT(mp_module_ucryptolib_globals, mp_module_ucryptolib_globals_table);
  309. const mp_obj_module_t mp_module_ucryptolib = {
  310. .base = { &mp_type_module },
  311. .globals = (mp_obj_dict_t*)&mp_module_ucryptolib_globals,
  312. };
  313. #endif //MICROPY_PY_UCRYPTOLIB