modussl_mbedtls.c 13 KB

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