modussl_mbedtls.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. STATIC int _mbedtls_ssl_send(void *ctx, const byte *buf, size_t len) {
  68. mp_obj_t sock = *(mp_obj_t*)ctx;
  69. const mp_stream_p_t *sock_stream = mp_get_stream(sock);
  70. int err;
  71. mp_uint_t out_sz = sock_stream->write(sock, buf, len, &err);
  72. if (out_sz == MP_STREAM_ERROR) {
  73. if (mp_is_nonblocking_error(err)) {
  74. return MBEDTLS_ERR_SSL_WANT_WRITE;
  75. }
  76. return -err;
  77. } else {
  78. return out_sz;
  79. }
  80. }
  81. STATIC int _mbedtls_ssl_recv(void *ctx, byte *buf, size_t len) {
  82. mp_obj_t sock = *(mp_obj_t*)ctx;
  83. const mp_stream_p_t *sock_stream = mp_get_stream(sock);
  84. int err;
  85. mp_uint_t out_sz = sock_stream->read(sock, buf, len, &err);
  86. if (out_sz == MP_STREAM_ERROR) {
  87. if (mp_is_nonblocking_error(err)) {
  88. return MBEDTLS_ERR_SSL_WANT_READ;
  89. }
  90. return -err;
  91. } else {
  92. return out_sz;
  93. }
  94. }
  95. STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) {
  96. // Verify the socket object has the full stream protocol
  97. mp_get_stream_raise(sock, MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL);
  98. #if MICROPY_PY_USSL_FINALISER
  99. mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t);
  100. #else
  101. mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t);
  102. #endif
  103. o->base.type = &ussl_socket_type;
  104. o->sock = sock;
  105. int ret;
  106. mbedtls_ssl_init(&o->ssl);
  107. mbedtls_ssl_config_init(&o->conf);
  108. mbedtls_x509_crt_init(&o->cacert);
  109. mbedtls_x509_crt_init(&o->cert);
  110. mbedtls_pk_init(&o->pkey);
  111. mbedtls_ctr_drbg_init(&o->ctr_drbg);
  112. #ifdef MBEDTLS_DEBUG_C
  113. // Debug level (0-4)
  114. mbedtls_debug_set_threshold(0);
  115. #endif
  116. mbedtls_entropy_init(&o->entropy);
  117. const byte seed[] = "upy";
  118. ret = mbedtls_ctr_drbg_seed(&o->ctr_drbg, mbedtls_entropy_func, &o->entropy, seed, sizeof(seed));
  119. if (ret != 0) {
  120. goto cleanup;
  121. }
  122. ret = mbedtls_ssl_config_defaults(&o->conf,
  123. args->server_side.u_bool ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT,
  124. MBEDTLS_SSL_TRANSPORT_STREAM,
  125. MBEDTLS_SSL_PRESET_DEFAULT);
  126. if (ret != 0) {
  127. goto cleanup;
  128. }
  129. mbedtls_ssl_conf_authmode(&o->conf, MBEDTLS_SSL_VERIFY_NONE);
  130. mbedtls_ssl_conf_rng(&o->conf, mbedtls_ctr_drbg_random, &o->ctr_drbg);
  131. #ifdef MBEDTLS_DEBUG_C
  132. mbedtls_ssl_conf_dbg(&o->conf, mbedtls_debug, NULL);
  133. #endif
  134. ret = mbedtls_ssl_setup(&o->ssl, &o->conf);
  135. if (ret != 0) {
  136. goto cleanup;
  137. }
  138. if (args->server_hostname.u_obj != mp_const_none) {
  139. const char *sni = mp_obj_str_get_str(args->server_hostname.u_obj);
  140. ret = mbedtls_ssl_set_hostname(&o->ssl, sni);
  141. if (ret != 0) {
  142. goto cleanup;
  143. }
  144. }
  145. mbedtls_ssl_set_bio(&o->ssl, &o->sock, _mbedtls_ssl_send, _mbedtls_ssl_recv, NULL);
  146. if (args->key.u_obj != MP_OBJ_NULL) {
  147. size_t key_len;
  148. const byte *key = (const byte*)mp_obj_str_get_data(args->key.u_obj, &key_len);
  149. // len should include terminating null
  150. ret = mbedtls_pk_parse_key(&o->pkey, key, key_len + 1, NULL, 0);
  151. assert(ret == 0);
  152. size_t cert_len;
  153. const byte *cert = (const byte*)mp_obj_str_get_data(args->cert.u_obj, &cert_len);
  154. // len should include terminating null
  155. ret = mbedtls_x509_crt_parse(&o->cert, cert, cert_len + 1);
  156. assert(ret == 0);
  157. ret = mbedtls_ssl_conf_own_cert(&o->conf, &o->cert, &o->pkey);
  158. assert(ret == 0);
  159. }
  160. while ((ret = mbedtls_ssl_handshake(&o->ssl)) != 0) {
  161. if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  162. printf("mbedtls_ssl_handshake error: -%x\n", -ret);
  163. goto cleanup;
  164. }
  165. }
  166. return o;
  167. cleanup:
  168. mbedtls_pk_free(&o->pkey);
  169. mbedtls_x509_crt_free(&o->cert);
  170. mbedtls_x509_crt_free(&o->cacert);
  171. mbedtls_ssl_free(&o->ssl);
  172. mbedtls_ssl_config_free(&o->conf);
  173. mbedtls_ctr_drbg_free(&o->ctr_drbg);
  174. mbedtls_entropy_free(&o->entropy);
  175. if (ret == MBEDTLS_ERR_SSL_ALLOC_FAILED) {
  176. mp_raise_OSError(MP_ENOMEM);
  177. } else {
  178. mp_raise_OSError(MP_EIO);
  179. }
  180. }
  181. STATIC mp_obj_t mod_ssl_getpeercert(mp_obj_t o_in, mp_obj_t binary_form) {
  182. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
  183. if (!mp_obj_is_true(binary_form)) {
  184. mp_raise_NotImplementedError(NULL);
  185. }
  186. const mbedtls_x509_crt* peer_cert = mbedtls_ssl_get_peer_cert(&o->ssl);
  187. return mp_obj_new_bytes(peer_cert->raw.p, peer_cert->raw.len);
  188. }
  189. STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_ssl_getpeercert_obj, mod_ssl_getpeercert);
  190. STATIC void socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  191. (void)kind;
  192. mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(self_in);
  193. mp_printf(print, "<_SSLSocket %p>", self);
  194. }
  195. STATIC mp_uint_t socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) {
  196. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
  197. int ret = mbedtls_ssl_read(&o->ssl, buf, size);
  198. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  199. // end of stream
  200. return 0;
  201. }
  202. if (ret >= 0) {
  203. return ret;
  204. }
  205. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  206. ret = MP_EWOULDBLOCK;
  207. }
  208. *errcode = ret;
  209. return MP_STREAM_ERROR;
  210. }
  211. STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) {
  212. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
  213. int ret = mbedtls_ssl_write(&o->ssl, buf, size);
  214. if (ret >= 0) {
  215. return ret;
  216. }
  217. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  218. ret = MP_EWOULDBLOCK;
  219. }
  220. *errcode = ret;
  221. return MP_STREAM_ERROR;
  222. }
  223. STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) {
  224. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(self_in);
  225. mp_obj_t sock = o->sock;
  226. mp_obj_t dest[3];
  227. mp_load_method(sock, MP_QSTR_setblocking, dest);
  228. dest[2] = flag_in;
  229. return mp_call_method_n_kw(1, 0, dest);
  230. }
  231. STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking);
  232. STATIC mp_uint_t socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) {
  233. mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(o_in);
  234. if (request == MP_STREAM_CLOSE) {
  235. mbedtls_pk_free(&self->pkey);
  236. mbedtls_x509_crt_free(&self->cert);
  237. mbedtls_x509_crt_free(&self->cacert);
  238. mbedtls_ssl_free(&self->ssl);
  239. mbedtls_ssl_config_free(&self->conf);
  240. mbedtls_ctr_drbg_free(&self->ctr_drbg);
  241. mbedtls_entropy_free(&self->entropy);
  242. }
  243. // Pass all requests down to the underlying socket
  244. return mp_get_stream(self->sock)->ioctl(self->sock, request, arg, errcode);
  245. }
  246. STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = {
  247. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
  248. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
  249. { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
  250. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
  251. { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) },
  252. { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) },
  253. #if MICROPY_PY_USSL_FINALISER
  254. { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) },
  255. #endif
  256. { MP_ROM_QSTR(MP_QSTR_getpeercert), MP_ROM_PTR(&mod_ssl_getpeercert_obj) },
  257. };
  258. STATIC MP_DEFINE_CONST_DICT(ussl_socket_locals_dict, ussl_socket_locals_dict_table);
  259. STATIC const mp_stream_p_t ussl_socket_stream_p = {
  260. .read = socket_read,
  261. .write = socket_write,
  262. .ioctl = socket_ioctl,
  263. };
  264. STATIC const mp_obj_type_t ussl_socket_type = {
  265. { &mp_type_type },
  266. // Save on qstr's, reuse same as for module
  267. .name = MP_QSTR_ussl,
  268. .print = socket_print,
  269. .getiter = NULL,
  270. .iternext = NULL,
  271. .protocol = &ussl_socket_stream_p,
  272. .locals_dict = (void*)&ussl_socket_locals_dict,
  273. };
  274. STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  275. // TODO: Implement more args
  276. static const mp_arg_t allowed_args[] = {
  277. { MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
  278. { MP_QSTR_cert, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
  279. { MP_QSTR_server_side, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} },
  280. { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
  281. };
  282. // TODO: Check that sock implements stream protocol
  283. mp_obj_t sock = pos_args[0];
  284. struct ssl_args args;
  285. mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
  286. MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
  287. return MP_OBJ_FROM_PTR(socket_new(sock, &args));
  288. }
  289. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ssl_wrap_socket_obj, 1, mod_ssl_wrap_socket);
  290. STATIC const mp_rom_map_elem_t mp_module_ssl_globals_table[] = {
  291. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ussl) },
  292. { MP_ROM_QSTR(MP_QSTR_wrap_socket), MP_ROM_PTR(&mod_ssl_wrap_socket_obj) },
  293. };
  294. STATIC MP_DEFINE_CONST_DICT(mp_module_ssl_globals, mp_module_ssl_globals_table);
  295. const mp_obj_module_t mp_module_ussl = {
  296. .base = { &mp_type_module },
  297. .globals = (mp_obj_dict_t*)&mp_module_ssl_globals,
  298. };
  299. #endif // MICROPY_PY_USSL