modussl_mbedtls.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. #include "py/objstr.h"
  35. // mbedtls_time_t
  36. #include "mbedtls/platform.h"
  37. #include "mbedtls/ssl.h"
  38. #include "mbedtls/x509_crt.h"
  39. #include "mbedtls/pk.h"
  40. #include "mbedtls/entropy.h"
  41. #include "mbedtls/ctr_drbg.h"
  42. #include "mbedtls/debug.h"
  43. #include "mbedtls/error.h"
  44. typedef struct _mp_obj_ssl_socket_t {
  45. mp_obj_base_t base;
  46. mp_obj_t sock;
  47. mbedtls_entropy_context entropy;
  48. mbedtls_ctr_drbg_context ctr_drbg;
  49. mbedtls_ssl_context ssl;
  50. mbedtls_ssl_config conf;
  51. mbedtls_x509_crt cacert;
  52. mbedtls_x509_crt cert;
  53. mbedtls_pk_context pkey;
  54. } mp_obj_ssl_socket_t;
  55. struct ssl_args {
  56. mp_arg_val_t key;
  57. mp_arg_val_t cert;
  58. mp_arg_val_t server_side;
  59. mp_arg_val_t server_hostname;
  60. mp_arg_val_t do_handshake;
  61. };
  62. STATIC const mp_obj_type_t ussl_socket_type;
  63. #ifdef MBEDTLS_DEBUG_C
  64. STATIC void mbedtls_debug(void *ctx, int level, const char *file, int line, const char *str) {
  65. (void)ctx;
  66. (void)level;
  67. printf("DBG:%s:%04d: %s\n", file, line, str);
  68. }
  69. #endif
  70. STATIC NORETURN void mbedtls_raise_error(int err) {
  71. // _mbedtls_ssl_send and _mbedtls_ssl_recv (below) turn positive error codes from the
  72. // underlying socket into negative codes to pass them through mbedtls. Here we turn them
  73. // positive again so they get interpreted as the OSError they really are. The
  74. // cut-off of -256 is a bit hacky, sigh.
  75. if (err < 0 && err > -256) {
  76. mp_raise_OSError(-err);
  77. }
  78. #if defined(MBEDTLS_ERROR_C)
  79. // Including mbedtls_strerror takes about 1.5KB due to the error strings.
  80. // MBEDTLS_ERROR_C is the define used by mbedtls to conditionally include mbedtls_strerror.
  81. // It is set/unset in the MBEDTLS_CONFIG_FILE which is defined in the Makefile.
  82. // Try to allocate memory for the message
  83. #define ERR_STR_MAX 80 // mbedtls_strerror truncates if it doesn't fit
  84. mp_obj_str_t *o_str = m_new_obj_maybe(mp_obj_str_t);
  85. byte *o_str_buf = m_new_maybe(byte, ERR_STR_MAX);
  86. if (o_str == NULL || o_str_buf == NULL) {
  87. mp_raise_OSError(err);
  88. }
  89. // print the error message into the allocated buffer
  90. mbedtls_strerror(err, (char *)o_str_buf, ERR_STR_MAX);
  91. size_t len = strlen((char *)o_str_buf);
  92. // Put the exception object together
  93. o_str->base.type = &mp_type_str;
  94. o_str->data = o_str_buf;
  95. o_str->len = len;
  96. o_str->hash = qstr_compute_hash(o_str->data, o_str->len);
  97. // raise
  98. mp_obj_t args[2] = { MP_OBJ_NEW_SMALL_INT(err), MP_OBJ_FROM_PTR(o_str)};
  99. nlr_raise(mp_obj_exception_make_new(&mp_type_OSError, 2, 0, args));
  100. #else
  101. // mbedtls is compiled without error strings so we simply return the err number
  102. mp_raise_OSError(err); // err is typically a large negative number
  103. #endif
  104. }
  105. STATIC int _mbedtls_ssl_send(void *ctx, const byte *buf, size_t len) {
  106. mp_obj_t sock = *(mp_obj_t *)ctx;
  107. const mp_stream_p_t *sock_stream = mp_get_stream(sock);
  108. int err;
  109. mp_uint_t out_sz = sock_stream->write(sock, buf, len, &err);
  110. if (out_sz == MP_STREAM_ERROR) {
  111. if (mp_is_nonblocking_error(err)) {
  112. return MBEDTLS_ERR_SSL_WANT_WRITE;
  113. }
  114. return -err; // convert an MP_ERRNO to something mbedtls passes through as error
  115. } else {
  116. return out_sz;
  117. }
  118. }
  119. STATIC int _mbedtls_ssl_recv(void *ctx, byte *buf, size_t len) {
  120. mp_obj_t sock = *(mp_obj_t *)ctx;
  121. const mp_stream_p_t *sock_stream = mp_get_stream(sock);
  122. int err;
  123. mp_uint_t out_sz = sock_stream->read(sock, buf, len, &err);
  124. if (out_sz == MP_STREAM_ERROR) {
  125. if (mp_is_nonblocking_error(err)) {
  126. return MBEDTLS_ERR_SSL_WANT_READ;
  127. }
  128. return -err;
  129. } else {
  130. return out_sz;
  131. }
  132. }
  133. STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) {
  134. // Verify the socket object has the full stream protocol
  135. mp_get_stream_raise(sock, MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL);
  136. #if MICROPY_PY_USSL_FINALISER
  137. mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t);
  138. #else
  139. mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t);
  140. #endif
  141. o->base.type = &ussl_socket_type;
  142. o->sock = sock;
  143. int ret;
  144. mbedtls_ssl_init(&o->ssl);
  145. mbedtls_ssl_config_init(&o->conf);
  146. mbedtls_x509_crt_init(&o->cacert);
  147. mbedtls_x509_crt_init(&o->cert);
  148. mbedtls_pk_init(&o->pkey);
  149. mbedtls_ctr_drbg_init(&o->ctr_drbg);
  150. #ifdef MBEDTLS_DEBUG_C
  151. // Debug level (0-4)
  152. mbedtls_debug_set_threshold(0);
  153. #endif
  154. mbedtls_entropy_init(&o->entropy);
  155. const byte seed[] = "upy";
  156. ret = mbedtls_ctr_drbg_seed(&o->ctr_drbg, mbedtls_entropy_func, &o->entropy, seed, sizeof(seed));
  157. if (ret != 0) {
  158. goto cleanup;
  159. }
  160. ret = mbedtls_ssl_config_defaults(&o->conf,
  161. args->server_side.u_bool ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT,
  162. MBEDTLS_SSL_TRANSPORT_STREAM,
  163. MBEDTLS_SSL_PRESET_DEFAULT);
  164. if (ret != 0) {
  165. goto cleanup;
  166. }
  167. mbedtls_ssl_conf_authmode(&o->conf, MBEDTLS_SSL_VERIFY_NONE);
  168. mbedtls_ssl_conf_rng(&o->conf, mbedtls_ctr_drbg_random, &o->ctr_drbg);
  169. #ifdef MBEDTLS_DEBUG_C
  170. mbedtls_ssl_conf_dbg(&o->conf, mbedtls_debug, NULL);
  171. #endif
  172. ret = mbedtls_ssl_setup(&o->ssl, &o->conf);
  173. if (ret != 0) {
  174. goto cleanup;
  175. }
  176. if (args->server_hostname.u_obj != mp_const_none) {
  177. const char *sni = mp_obj_str_get_str(args->server_hostname.u_obj);
  178. ret = mbedtls_ssl_set_hostname(&o->ssl, sni);
  179. if (ret != 0) {
  180. goto cleanup;
  181. }
  182. }
  183. mbedtls_ssl_set_bio(&o->ssl, &o->sock, _mbedtls_ssl_send, _mbedtls_ssl_recv, NULL);
  184. if (args->key.u_obj != mp_const_none) {
  185. size_t key_len;
  186. const byte *key = (const byte *)mp_obj_str_get_data(args->key.u_obj, &key_len);
  187. // len should include terminating null
  188. ret = mbedtls_pk_parse_key(&o->pkey, key, key_len + 1, NULL, 0);
  189. if (ret != 0) {
  190. ret = MBEDTLS_ERR_PK_BAD_INPUT_DATA; // use general error for all key errors
  191. goto cleanup;
  192. }
  193. size_t cert_len;
  194. const byte *cert = (const byte *)mp_obj_str_get_data(args->cert.u_obj, &cert_len);
  195. // len should include terminating null
  196. ret = mbedtls_x509_crt_parse(&o->cert, cert, cert_len + 1);
  197. if (ret != 0) {
  198. ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA; // use general error for all cert errors
  199. goto cleanup;
  200. }
  201. ret = mbedtls_ssl_conf_own_cert(&o->conf, &o->cert, &o->pkey);
  202. if (ret != 0) {
  203. goto cleanup;
  204. }
  205. }
  206. if (args->do_handshake.u_bool) {
  207. while ((ret = mbedtls_ssl_handshake(&o->ssl)) != 0) {
  208. if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  209. goto cleanup;
  210. }
  211. }
  212. }
  213. return o;
  214. cleanup:
  215. mbedtls_pk_free(&o->pkey);
  216. mbedtls_x509_crt_free(&o->cert);
  217. mbedtls_x509_crt_free(&o->cacert);
  218. mbedtls_ssl_free(&o->ssl);
  219. mbedtls_ssl_config_free(&o->conf);
  220. mbedtls_ctr_drbg_free(&o->ctr_drbg);
  221. mbedtls_entropy_free(&o->entropy);
  222. if (ret == MBEDTLS_ERR_SSL_ALLOC_FAILED) {
  223. mp_raise_OSError(MP_ENOMEM);
  224. } else if (ret == MBEDTLS_ERR_PK_BAD_INPUT_DATA) {
  225. mp_raise_ValueError(MP_ERROR_TEXT("invalid key"));
  226. } else if (ret == MBEDTLS_ERR_X509_BAD_INPUT_DATA) {
  227. mp_raise_ValueError(MP_ERROR_TEXT("invalid cert"));
  228. } else {
  229. mbedtls_raise_error(ret);
  230. }
  231. }
  232. STATIC mp_obj_t mod_ssl_getpeercert(mp_obj_t o_in, mp_obj_t binary_form) {
  233. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
  234. if (!mp_obj_is_true(binary_form)) {
  235. mp_raise_NotImplementedError(NULL);
  236. }
  237. const mbedtls_x509_crt *peer_cert = mbedtls_ssl_get_peer_cert(&o->ssl);
  238. if (peer_cert == NULL) {
  239. return mp_const_none;
  240. }
  241. return mp_obj_new_bytes(peer_cert->raw.p, peer_cert->raw.len);
  242. }
  243. STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_ssl_getpeercert_obj, mod_ssl_getpeercert);
  244. STATIC void socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  245. (void)kind;
  246. mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(self_in);
  247. mp_printf(print, "<_SSLSocket %p>", self);
  248. }
  249. STATIC mp_uint_t socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) {
  250. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
  251. int ret = mbedtls_ssl_read(&o->ssl, buf, size);
  252. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  253. // end of stream
  254. return 0;
  255. }
  256. if (ret >= 0) {
  257. return ret;
  258. }
  259. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  260. ret = MP_EWOULDBLOCK;
  261. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  262. // If handshake is not finished, read attempt may end up in protocol
  263. // wanting to write next handshake message. The same may happen with
  264. // renegotation.
  265. ret = MP_EWOULDBLOCK;
  266. }
  267. *errcode = ret;
  268. return MP_STREAM_ERROR;
  269. }
  270. STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) {
  271. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
  272. int ret = mbedtls_ssl_write(&o->ssl, buf, size);
  273. if (ret >= 0) {
  274. return ret;
  275. }
  276. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  277. ret = MP_EWOULDBLOCK;
  278. } else if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  279. // If handshake is not finished, write attempt may end up in protocol
  280. // wanting to read next handshake message. The same may happen with
  281. // renegotation.
  282. ret = MP_EWOULDBLOCK;
  283. }
  284. *errcode = ret;
  285. return MP_STREAM_ERROR;
  286. }
  287. STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) {
  288. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(self_in);
  289. mp_obj_t sock = o->sock;
  290. mp_obj_t dest[3];
  291. mp_load_method(sock, MP_QSTR_setblocking, dest);
  292. dest[2] = flag_in;
  293. return mp_call_method_n_kw(1, 0, dest);
  294. }
  295. STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking);
  296. STATIC mp_uint_t socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) {
  297. mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(o_in);
  298. if (request == MP_STREAM_CLOSE) {
  299. mbedtls_pk_free(&self->pkey);
  300. mbedtls_x509_crt_free(&self->cert);
  301. mbedtls_x509_crt_free(&self->cacert);
  302. mbedtls_ssl_free(&self->ssl);
  303. mbedtls_ssl_config_free(&self->conf);
  304. mbedtls_ctr_drbg_free(&self->ctr_drbg);
  305. mbedtls_entropy_free(&self->entropy);
  306. }
  307. // Pass all requests down to the underlying socket
  308. return mp_get_stream(self->sock)->ioctl(self->sock, request, arg, errcode);
  309. }
  310. STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = {
  311. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
  312. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
  313. { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
  314. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
  315. { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) },
  316. { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) },
  317. #if MICROPY_PY_USSL_FINALISER
  318. { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) },
  319. #endif
  320. { MP_ROM_QSTR(MP_QSTR_getpeercert), MP_ROM_PTR(&mod_ssl_getpeercert_obj) },
  321. };
  322. STATIC MP_DEFINE_CONST_DICT(ussl_socket_locals_dict, ussl_socket_locals_dict_table);
  323. STATIC const mp_stream_p_t ussl_socket_stream_p = {
  324. .read = socket_read,
  325. .write = socket_write,
  326. .ioctl = socket_ioctl,
  327. };
  328. STATIC const mp_obj_type_t ussl_socket_type = {
  329. { &mp_type_type },
  330. // Save on qstr's, reuse same as for module
  331. .name = MP_QSTR_ussl,
  332. .print = socket_print,
  333. .getiter = NULL,
  334. .iternext = NULL,
  335. .protocol = &ussl_socket_stream_p,
  336. .locals_dict = (void *)&ussl_socket_locals_dict,
  337. };
  338. STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  339. // TODO: Implement more args
  340. static const mp_arg_t allowed_args[] = {
  341. { MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
  342. { MP_QSTR_cert, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
  343. { MP_QSTR_server_side, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} },
  344. { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
  345. { MP_QSTR_do_handshake, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} },
  346. };
  347. // TODO: Check that sock implements stream protocol
  348. mp_obj_t sock = pos_args[0];
  349. struct ssl_args args;
  350. mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
  351. MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args);
  352. return MP_OBJ_FROM_PTR(socket_new(sock, &args));
  353. }
  354. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ssl_wrap_socket_obj, 1, mod_ssl_wrap_socket);
  355. STATIC const mp_rom_map_elem_t mp_module_ssl_globals_table[] = {
  356. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ussl) },
  357. { MP_ROM_QSTR(MP_QSTR_wrap_socket), MP_ROM_PTR(&mod_ssl_wrap_socket_obj) },
  358. };
  359. STATIC MP_DEFINE_CONST_DICT(mp_module_ssl_globals, mp_module_ssl_globals_table);
  360. const mp_obj_module_t mp_module_ussl = {
  361. .base = { &mp_type_module },
  362. .globals = (mp_obj_dict_t *)&mp_module_ssl_globals,
  363. };
  364. #endif // MICROPY_PY_USSL