modussl_mbedtls.c 11 KB

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