modussl_mbedtls.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2016 Linaro Ltd.
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include "py/mpconfig.h"
  27. #if MICROPY_PY_USSL && MICROPY_SSL_MBEDTLS
  28. #include <stdio.h>
  29. #include <string.h>
  30. #include <errno.h> // needed because mp_is_nonblocking_error uses system error codes
  31. #include "py/runtime.h"
  32. #include "py/stream.h"
  33. // mbedtls_time_t
  34. #include "mbedtls/platform.h"
  35. #include "mbedtls/net.h"
  36. #include "mbedtls/ssl.h"
  37. #include "mbedtls/x509_crt.h"
  38. #include "mbedtls/pk.h"
  39. #include "mbedtls/entropy.h"
  40. #include "mbedtls/ctr_drbg.h"
  41. #include "mbedtls/debug.h"
  42. typedef struct _mp_obj_ssl_socket_t {
  43. mp_obj_base_t base;
  44. mp_obj_t sock;
  45. mbedtls_entropy_context entropy;
  46. mbedtls_ctr_drbg_context ctr_drbg;
  47. mbedtls_ssl_context ssl;
  48. mbedtls_ssl_config conf;
  49. mbedtls_x509_crt cacert;
  50. mbedtls_x509_crt cert;
  51. mbedtls_pk_context pkey;
  52. } mp_obj_ssl_socket_t;
  53. struct ssl_args {
  54. mp_arg_val_t key;
  55. mp_arg_val_t cert;
  56. mp_arg_val_t server_side;
  57. mp_arg_val_t server_hostname;
  58. };
  59. STATIC const mp_obj_type_t ussl_socket_type;
  60. #ifdef MBEDTLS_DEBUG_C
  61. STATIC void mbedtls_debug(void *ctx, int level, const char *file, int line, const char *str) {
  62. (void)ctx;
  63. (void)level;
  64. printf("DBG:%s:%04d: %s\n", file, line, str);
  65. }
  66. #endif
  67. // TODO: FIXME!
  68. STATIC int null_entropy_func(void *data, unsigned char *output, size_t len) {
  69. (void)data;
  70. (void)output;
  71. (void)len;
  72. // enjoy random bytes
  73. return 0;
  74. }
  75. STATIC int _mbedtls_ssl_send(void *ctx, const byte *buf, size_t len) {
  76. mp_obj_t sock = *(mp_obj_t*)ctx;
  77. const mp_stream_p_t *sock_stream = mp_get_stream_raise(sock, MP_STREAM_OP_WRITE);
  78. int err;
  79. mp_uint_t out_sz = sock_stream->write(sock, buf, len, &err);
  80. if (out_sz == MP_STREAM_ERROR) {
  81. if (mp_is_nonblocking_error(err)) {
  82. return MBEDTLS_ERR_SSL_WANT_WRITE;
  83. }
  84. return -err;
  85. } else {
  86. return out_sz;
  87. }
  88. }
  89. STATIC int _mbedtls_ssl_recv(void *ctx, byte *buf, size_t len) {
  90. mp_obj_t sock = *(mp_obj_t*)ctx;
  91. const mp_stream_p_t *sock_stream = mp_get_stream_raise(sock, MP_STREAM_OP_READ);
  92. int err;
  93. mp_uint_t out_sz = sock_stream->read(sock, buf, len, &err);
  94. if (out_sz == MP_STREAM_ERROR) {
  95. if (mp_is_nonblocking_error(err)) {
  96. return MBEDTLS_ERR_SSL_WANT_READ;
  97. }
  98. return -err;
  99. } else {
  100. return out_sz;
  101. }
  102. }
  103. STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) {
  104. #if MICROPY_PY_USSL_FINALISER
  105. mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t);
  106. #else
  107. mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t);
  108. #endif
  109. o->base.type = &ussl_socket_type;
  110. int ret;
  111. mbedtls_ssl_init(&o->ssl);
  112. mbedtls_ssl_config_init(&o->conf);
  113. mbedtls_x509_crt_init(&o->cacert);
  114. mbedtls_x509_crt_init(&o->cert);
  115. mbedtls_pk_init(&o->pkey);
  116. mbedtls_ctr_drbg_init(&o->ctr_drbg);
  117. #ifdef MBEDTLS_DEBUG_C
  118. // Debug level (0-4)
  119. mbedtls_debug_set_threshold(0);
  120. #endif
  121. mbedtls_entropy_init(&o->entropy);
  122. const byte seed[] = "upy";
  123. ret = mbedtls_ctr_drbg_seed(&o->ctr_drbg, null_entropy_func/*mbedtls_entropy_func*/, &o->entropy, seed, sizeof(seed));
  124. if (ret != 0) {
  125. printf("ret=%d\n", ret);
  126. assert(0);
  127. }
  128. ret = mbedtls_ssl_config_defaults(&o->conf,
  129. args->server_side.u_bool ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT,
  130. MBEDTLS_SSL_TRANSPORT_STREAM,
  131. MBEDTLS_SSL_PRESET_DEFAULT);
  132. if (ret != 0) {
  133. assert(0);
  134. }
  135. mbedtls_ssl_conf_authmode(&o->conf, MBEDTLS_SSL_VERIFY_NONE);
  136. mbedtls_ssl_conf_rng(&o->conf, mbedtls_ctr_drbg_random, &o->ctr_drbg);
  137. #ifdef MBEDTLS_DEBUG_C
  138. mbedtls_ssl_conf_dbg(&o->conf, mbedtls_debug, NULL);
  139. #endif
  140. ret = mbedtls_ssl_setup(&o->ssl, &o->conf);
  141. if (ret != 0) {
  142. assert(0);
  143. }
  144. if (args->server_hostname.u_obj != mp_const_none) {
  145. const char *sni = mp_obj_str_get_str(args->server_hostname.u_obj);
  146. ret = mbedtls_ssl_set_hostname(&o->ssl, sni);
  147. if (ret != 0) {
  148. assert(0);
  149. }
  150. }
  151. o->sock = sock;
  152. mbedtls_ssl_set_bio(&o->ssl, &o->sock, _mbedtls_ssl_send, _mbedtls_ssl_recv, NULL);
  153. if (args->key.u_obj != MP_OBJ_NULL) {
  154. size_t key_len;
  155. const byte *key = (const byte*)mp_obj_str_get_data(args->key.u_obj, &key_len);
  156. // len should include terminating null
  157. ret = mbedtls_pk_parse_key(&o->pkey, key, key_len + 1, NULL, 0);
  158. assert(ret == 0);
  159. size_t cert_len;
  160. const byte *cert = (const byte*)mp_obj_str_get_data(args->cert.u_obj, &cert_len);
  161. // len should include terminating null
  162. ret = mbedtls_x509_crt_parse(&o->cert, cert, cert_len + 1);
  163. assert(ret == 0);
  164. ret = mbedtls_ssl_conf_own_cert(&o->conf, &o->cert, &o->pkey);
  165. assert(ret == 0);
  166. }
  167. while ((ret = mbedtls_ssl_handshake(&o->ssl)) != 0) {
  168. if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  169. //assert(0);
  170. printf("mbedtls_ssl_handshake error: -%x\n", -ret);
  171. mp_raise_OSError(MP_EIO);
  172. }
  173. }
  174. return o;
  175. }
  176. STATIC mp_obj_t mod_ssl_getpeercert(mp_obj_t o_in, mp_obj_t binary_form) {
  177. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
  178. if (!mp_obj_is_true(binary_form)) {
  179. mp_raise_NotImplementedError(NULL);
  180. }
  181. const mbedtls_x509_crt* peer_cert = mbedtls_ssl_get_peer_cert(&o->ssl);
  182. return mp_obj_new_bytes(peer_cert->raw.p, peer_cert->raw.len);
  183. }
  184. STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_ssl_getpeercert_obj, mod_ssl_getpeercert);
  185. STATIC void socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  186. (void)kind;
  187. mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(self_in);
  188. mp_printf(print, "<_SSLSocket %p>", self);
  189. }
  190. STATIC mp_uint_t socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) {
  191. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
  192. int ret = mbedtls_ssl_read(&o->ssl, buf, size);
  193. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  194. // end of stream
  195. return 0;
  196. }
  197. if (ret >= 0) {
  198. return ret;
  199. }
  200. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  201. ret = MP_EWOULDBLOCK;
  202. }
  203. *errcode = ret;
  204. return MP_STREAM_ERROR;
  205. }
  206. STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) {
  207. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
  208. int ret = mbedtls_ssl_write(&o->ssl, buf, size);
  209. if (ret >= 0) {
  210. return ret;
  211. }
  212. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  213. ret = MP_EWOULDBLOCK;
  214. }
  215. *errcode = ret;
  216. return MP_STREAM_ERROR;
  217. }
  218. STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) {
  219. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(self_in);
  220. mp_obj_t sock = o->sock;
  221. mp_obj_t dest[3];
  222. mp_load_method(sock, MP_QSTR_setblocking, dest);
  223. dest[2] = flag_in;
  224. return mp_call_method_n_kw(1, 0, dest);
  225. }
  226. STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking);
  227. STATIC mp_obj_t socket_close(mp_obj_t self_in) {
  228. mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(self_in);
  229. mbedtls_pk_free(&self->pkey);
  230. mbedtls_x509_crt_free(&self->cert);
  231. mbedtls_x509_crt_free(&self->cacert);
  232. mbedtls_ssl_free(&self->ssl);
  233. mbedtls_ssl_config_free(&self->conf);
  234. mbedtls_ctr_drbg_free(&self->ctr_drbg);
  235. mbedtls_entropy_free(&self->entropy);
  236. return mp_stream_close(self->sock);
  237. }
  238. STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_close_obj, socket_close);
  239. STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = {
  240. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
  241. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
  242. { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
  243. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
  244. { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) },
  245. { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&socket_close_obj) },
  246. #if MICROPY_PY_USSL_FINALISER
  247. { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&socket_close_obj) },
  248. #endif
  249. { MP_ROM_QSTR(MP_QSTR_getpeercert), MP_ROM_PTR(&mod_ssl_getpeercert_obj) },
  250. };
  251. STATIC MP_DEFINE_CONST_DICT(ussl_socket_locals_dict, ussl_socket_locals_dict_table);
  252. STATIC const mp_stream_p_t ussl_socket_stream_p = {
  253. .read = socket_read,
  254. .write = socket_write,
  255. };
  256. STATIC const mp_obj_type_t ussl_socket_type = {
  257. { &mp_type_type },
  258. // Save on qstr's, reuse same as for module
  259. .name = MP_QSTR_ussl,
  260. .print = socket_print,
  261. .getiter = NULL,
  262. .iternext = NULL,
  263. .protocol = &ussl_socket_stream_p,
  264. .locals_dict = (void*)&ussl_socket_locals_dict,
  265. };
  266. STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  267. // TODO: Implement more args
  268. static const mp_arg_t allowed_args[] = {
  269. { MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
  270. { MP_QSTR_cert, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
  271. { MP_QSTR_server_side, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} },
  272. { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
  273. };
  274. // TODO: Check that sock implements stream protocol
  275. mp_obj_t sock = pos_args[0];
  276. struct ssl_args args;
  277. mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
  278. MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
  279. return MP_OBJ_FROM_PTR(socket_new(sock, &args));
  280. }
  281. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ssl_wrap_socket_obj, 1, mod_ssl_wrap_socket);
  282. STATIC const mp_rom_map_elem_t mp_module_ssl_globals_table[] = {
  283. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ussl) },
  284. { MP_ROM_QSTR(MP_QSTR_wrap_socket), MP_ROM_PTR(&mod_ssl_wrap_socket_obj) },
  285. };
  286. STATIC MP_DEFINE_CONST_DICT(mp_module_ssl_globals, mp_module_ssl_globals_table);
  287. const mp_obj_module_t mp_module_ussl = {
  288. .base = { &mp_type_module },
  289. .globals = (mp_obj_dict_t*)&mp_module_ssl_globals,
  290. };
  291. #endif // MICROPY_PY_USSL