moducryptolib.c 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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_MIN = 0,
  39. UCRYPTOLIB_MODE_ECB,
  40. UCRYPTOLIB_MODE_CBC,
  41. UCRYPTOLIB_MODE_MAX,
  42. };
  43. #if MICROPY_SSL_AXTLS
  44. #include "lib/axtls/crypto/crypto.h"
  45. #define AES_CTX_IMPL AES_CTX
  46. #endif
  47. #if MICROPY_SSL_MBEDTLS
  48. #include <mbedtls/aes.h>
  49. // we can't run mbedtls AES key schedule until we know whether we're used for encrypt or decrypt.
  50. // therefore, we store the key & keysize and on the first call to encrypt/decrypt we override them
  51. // with the mbedtls_aes_context, as they are not longer required. (this is done to save space)
  52. struct mbedtls_aes_ctx_with_key {
  53. union {
  54. mbedtls_aes_context mbedtls_ctx;
  55. struct {
  56. uint8_t key[32];
  57. uint8_t keysize;
  58. } init_data;
  59. } u;
  60. unsigned char iv[16];
  61. };
  62. #define AES_CTX_IMPL struct mbedtls_aes_ctx_with_key
  63. #endif
  64. typedef struct _mp_obj_aes_t {
  65. mp_obj_base_t base;
  66. AES_CTX_IMPL ctx;
  67. uint8_t block_mode: 6;
  68. #define AES_KEYTYPE_NONE 0
  69. #define AES_KEYTYPE_ENC 1
  70. #define AES_KEYTYPE_DEC 2
  71. uint8_t key_type: 2;
  72. } mp_obj_aes_t;
  73. #if MICROPY_SSL_AXTLS
  74. STATIC void aes_initial_set_key_impl(AES_CTX_IMPL *ctx, const uint8_t *key, size_t keysize, const uint8_t iv[16]) {
  75. assert(16 == keysize || 32 == keysize);
  76. AES_set_key(ctx, key, iv, (16 == keysize) ? AES_MODE_128 : AES_MODE_256);
  77. }
  78. STATIC void aes_final_set_key_impl(AES_CTX_IMPL *ctx, bool encrypt) {
  79. if (!encrypt) {
  80. AES_convert_key(ctx);
  81. }
  82. }
  83. STATIC void aes_process_ecb_impl(AES_CTX_IMPL *ctx, const uint8_t in[16], uint8_t out[16], bool encrypt) {
  84. memcpy(out, in, 16);
  85. // We assume that out (vstr.buf or given output buffer) is uint32_t aligned
  86. uint32_t *p = (uint32_t*)out;
  87. // axTLS likes it weird and complicated with byteswaps
  88. for (int i = 0; i < 4; i++) {
  89. p[i] = MP_HTOBE32(p[i]);
  90. }
  91. if (encrypt) {
  92. AES_encrypt(ctx, p);
  93. } else {
  94. AES_decrypt(ctx, p);
  95. }
  96. for (int i = 0; i < 4; i++) {
  97. p[i] = MP_BE32TOH(p[i]);
  98. }
  99. }
  100. STATIC void aes_process_cbc_impl(AES_CTX_IMPL *ctx, const uint8_t *in, uint8_t *out, size_t in_len, bool encrypt) {
  101. if (encrypt) {
  102. AES_cbc_encrypt(ctx, in, out, in_len);
  103. } else {
  104. AES_cbc_decrypt(ctx, in, out, in_len);
  105. }
  106. }
  107. #endif
  108. #if MICROPY_SSL_MBEDTLS
  109. STATIC void aes_initial_set_key_impl(AES_CTX_IMPL *ctx, const uint8_t *key, size_t keysize, const uint8_t iv[16]) {
  110. ctx->u.init_data.keysize = keysize;
  111. memcpy(ctx->u.init_data.key, key, keysize);
  112. if (NULL != iv) {
  113. memcpy(ctx->iv, iv, sizeof(ctx->iv));
  114. }
  115. }
  116. STATIC void aes_final_set_key_impl(AES_CTX_IMPL *ctx, bool encrypt) {
  117. // first, copy key aside
  118. uint8_t key[32];
  119. uint8_t keysize = ctx->u.init_data.keysize;
  120. memcpy(key, ctx->u.init_data.key, keysize);
  121. // now, override key with the mbedtls context object
  122. mbedtls_aes_init(&ctx->u.mbedtls_ctx);
  123. // setkey call will succeed, we've already checked the keysize earlier.
  124. assert(16 == keysize || 32 == keysize);
  125. if (encrypt) {
  126. mbedtls_aes_setkey_enc(&ctx->u.mbedtls_ctx, key, keysize * 8);
  127. } else {
  128. mbedtls_aes_setkey_dec(&ctx->u.mbedtls_ctx, key, keysize * 8);
  129. }
  130. }
  131. STATIC void aes_process_ecb_impl(AES_CTX_IMPL *ctx, const uint8_t in[16], uint8_t out[16], bool encrypt) {
  132. mbedtls_aes_crypt_ecb(&ctx->u.mbedtls_ctx, encrypt ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT, in, out);
  133. }
  134. STATIC void aes_process_cbc_impl(AES_CTX_IMPL *ctx, const uint8_t *in, uint8_t *out, size_t in_len, bool encrypt) {
  135. mbedtls_aes_crypt_cbc(&ctx->u.mbedtls_ctx, encrypt ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT, in_len, ctx->iv, in, out);
  136. }
  137. #endif
  138. 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) {
  139. mp_arg_check_num(n_args, n_kw, 2, 3, false);
  140. mp_obj_aes_t *o = m_new_obj(mp_obj_aes_t);
  141. o->base.type = type;
  142. o->block_mode = mp_obj_get_int(args[1]);
  143. o->key_type = AES_KEYTYPE_NONE;
  144. if (o->block_mode <= UCRYPTOLIB_MODE_MIN || o->block_mode >= UCRYPTOLIB_MODE_MAX) {
  145. mp_raise_ValueError("mode");
  146. }
  147. mp_buffer_info_t keyinfo;
  148. mp_get_buffer_raise(args[0], &keyinfo, MP_BUFFER_READ);
  149. if (32 != keyinfo.len && 16 != keyinfo.len) {
  150. mp_raise_ValueError("key");
  151. }
  152. mp_buffer_info_t ivinfo;
  153. ivinfo.buf = NULL;
  154. if (n_args > 2 && args[2] != mp_const_none) {
  155. mp_get_buffer_raise(args[2], &ivinfo, MP_BUFFER_READ);
  156. if (16 != ivinfo.len) {
  157. mp_raise_ValueError("IV");
  158. }
  159. } else if (o->block_mode == UCRYPTOLIB_MODE_CBC) {
  160. mp_raise_ValueError("IV");
  161. }
  162. aes_initial_set_key_impl(&o->ctx, keyinfo.buf, keyinfo.len, ivinfo.buf);
  163. return MP_OBJ_FROM_PTR(o);
  164. }
  165. STATIC mp_obj_t aes_process(size_t n_args, const mp_obj_t *args, bool encrypt) {
  166. mp_obj_aes_t *self = MP_OBJ_TO_PTR(args[0]);
  167. mp_obj_t in_buf = args[1];
  168. mp_obj_t out_buf = MP_OBJ_NULL;
  169. if (n_args > 2) {
  170. out_buf = args[2];
  171. }
  172. mp_buffer_info_t in_bufinfo;
  173. mp_get_buffer_raise(in_buf, &in_bufinfo, MP_BUFFER_READ);
  174. if (in_bufinfo.len % 16 != 0) {
  175. mp_raise_ValueError("blksize % 16");
  176. }
  177. vstr_t vstr;
  178. mp_buffer_info_t out_bufinfo;
  179. uint8_t *out_buf_ptr;
  180. if (out_buf != MP_OBJ_NULL) {
  181. mp_get_buffer_raise(out_buf, &out_bufinfo, MP_BUFFER_WRITE);
  182. if (out_bufinfo.len < in_bufinfo.len) {
  183. mp_raise_ValueError("output too small");
  184. }
  185. out_buf_ptr = out_bufinfo.buf;
  186. } else {
  187. vstr_init_len(&vstr, in_bufinfo.len);
  188. out_buf_ptr = (uint8_t*)vstr.buf;
  189. }
  190. if (AES_KEYTYPE_NONE == self->key_type) {
  191. aes_final_set_key_impl(&self->ctx, encrypt);
  192. self->key_type = encrypt ? AES_KEYTYPE_ENC : AES_KEYTYPE_DEC;
  193. } else {
  194. if ((encrypt && self->key_type == AES_KEYTYPE_DEC) ||
  195. (!encrypt && self->key_type == AES_KEYTYPE_ENC)) {
  196. mp_raise_ValueError("can't encrypt & decrypt");
  197. }
  198. }
  199. if (self->block_mode == UCRYPTOLIB_MODE_ECB) {
  200. uint8_t *in = in_bufinfo.buf, *out = out_buf_ptr;
  201. uint8_t *top = in + in_bufinfo.len;
  202. for (; in < top; in += 16, out += 16) {
  203. aes_process_ecb_impl(&self->ctx, in, out, encrypt);
  204. }
  205. } else {
  206. aes_process_cbc_impl(&self->ctx, in_bufinfo.buf, out_buf_ptr, in_bufinfo.len, encrypt);
  207. }
  208. if (out_buf != MP_OBJ_NULL) {
  209. return out_buf;
  210. }
  211. return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
  212. }
  213. STATIC mp_obj_t ucryptolib_aes_encrypt(size_t n_args, const mp_obj_t *args) {
  214. return aes_process(n_args, args, true);
  215. }
  216. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ucryptolib_aes_encrypt_obj, 2, 3, ucryptolib_aes_encrypt);
  217. STATIC mp_obj_t ucryptolib_aes_decrypt(size_t n_args, const mp_obj_t *args) {
  218. return aes_process(n_args, args, false);
  219. }
  220. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ucryptolib_aes_decrypt_obj, 2, 3, ucryptolib_aes_decrypt);
  221. STATIC const mp_rom_map_elem_t ucryptolib_aes_locals_dict_table[] = {
  222. { MP_ROM_QSTR(MP_QSTR_encrypt), MP_ROM_PTR(&ucryptolib_aes_encrypt_obj) },
  223. { MP_ROM_QSTR(MP_QSTR_decrypt), MP_ROM_PTR(&ucryptolib_aes_decrypt_obj) },
  224. };
  225. STATIC MP_DEFINE_CONST_DICT(ucryptolib_aes_locals_dict, ucryptolib_aes_locals_dict_table);
  226. STATIC const mp_obj_type_t ucryptolib_aes_type = {
  227. { &mp_type_type },
  228. .name = MP_QSTR_aes,
  229. .make_new = ucryptolib_aes_make_new,
  230. .locals_dict = (void*)&ucryptolib_aes_locals_dict,
  231. };
  232. STATIC const mp_rom_map_elem_t mp_module_ucryptolib_globals_table[] = {
  233. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ucryptolib) },
  234. { MP_ROM_QSTR(MP_QSTR_aes), MP_ROM_PTR(&ucryptolib_aes_type) },
  235. #if MICROPY_PY_UCRYPTOLIB_CONSTS
  236. { MP_ROM_QSTR(MP_QSTR_MODE_ECB), MP_ROM_INT(UCRYPTOLIB_MODE_ECB) },
  237. { MP_ROM_QSTR(MP_QSTR_MODE_CBC), MP_ROM_INT(UCRYPTOLIB_MODE_CBC) },
  238. #endif
  239. };
  240. STATIC MP_DEFINE_CONST_DICT(mp_module_ucryptolib_globals, mp_module_ucryptolib_globals_table);
  241. const mp_obj_module_t mp_module_ucryptolib = {
  242. .base = { &mp_type_module },
  243. .globals = (mp_obj_dict_t*)&mp_module_ucryptolib_globals,
  244. };
  245. #endif //MICROPY_PY_UCRYPTOLIB