modussl_axtls.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2015-2019 Paul Sokolovsky
  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 <stdio.h>
  27. #include <string.h>
  28. #include "py/runtime.h"
  29. #include "py/stream.h"
  30. #include "py/objstr.h"
  31. #if MICROPY_PY_USSL && MICROPY_SSL_AXTLS
  32. #include "ssl.h"
  33. typedef struct _mp_obj_ssl_socket_t {
  34. mp_obj_base_t base;
  35. mp_obj_t sock;
  36. SSL_CTX *ssl_ctx;
  37. SSL *ssl_sock;
  38. byte *buf;
  39. uint32_t bytes_left;
  40. bool blocking;
  41. } mp_obj_ssl_socket_t;
  42. struct ssl_args {
  43. mp_arg_val_t key;
  44. mp_arg_val_t cert;
  45. mp_arg_val_t server_side;
  46. mp_arg_val_t server_hostname;
  47. mp_arg_val_t do_handshake;
  48. };
  49. STATIC const mp_obj_type_t ussl_socket_type;
  50. // Table of error strings corresponding to SSL_xxx error codes.
  51. STATIC const char *const ssl_error_tab1[] = {
  52. "NOT_OK",
  53. "DEAD",
  54. "CLOSE_NOTIFY",
  55. "EAGAIN",
  56. };
  57. STATIC const char *const ssl_error_tab2[] = {
  58. "CONN_LOST",
  59. "RECORD_OVERFLOW",
  60. "SOCK_SETUP_FAILURE",
  61. NULL,
  62. "INVALID_HANDSHAKE",
  63. "INVALID_PROT_MSG",
  64. "INVALID_HMAC",
  65. "INVALID_VERSION",
  66. "UNSUPPORTED_EXTENSION",
  67. "INVALID_SESSION",
  68. "NO_CIPHER",
  69. "INVALID_CERT_HASH_ALG",
  70. "BAD_CERTIFICATE",
  71. "INVALID_KEY",
  72. NULL,
  73. "FINISHED_INVALID",
  74. "NO_CERT_DEFINED",
  75. "NO_CLIENT_RENOG",
  76. "NOT_SUPPORTED",
  77. };
  78. STATIC NORETURN void ussl_raise_error(int err) {
  79. MP_STATIC_ASSERT(SSL_NOT_OK - 3 == SSL_EAGAIN);
  80. MP_STATIC_ASSERT(SSL_ERROR_CONN_LOST - 18 == SSL_ERROR_NOT_SUPPORTED);
  81. // Check if err corresponds to something in one of the error string tables.
  82. const char *errstr = NULL;
  83. if (SSL_NOT_OK >= err && err >= SSL_EAGAIN) {
  84. errstr = ssl_error_tab1[SSL_NOT_OK - err];
  85. } else if (SSL_ERROR_CONN_LOST >= err && err >= SSL_ERROR_NOT_SUPPORTED) {
  86. errstr = ssl_error_tab2[SSL_ERROR_CONN_LOST - err];
  87. }
  88. // Unknown error, just raise the error code.
  89. if (errstr == NULL) {
  90. mp_raise_OSError(err);
  91. }
  92. // Construct string object.
  93. mp_obj_str_t *o_str = m_new_obj_maybe(mp_obj_str_t);
  94. if (o_str == NULL) {
  95. mp_raise_OSError(err);
  96. }
  97. o_str->base.type = &mp_type_str;
  98. o_str->data = (const byte *)errstr;
  99. o_str->len = strlen((char *)o_str->data);
  100. o_str->hash = qstr_compute_hash(o_str->data, o_str->len);
  101. // Raise OSError(err, str).
  102. mp_obj_t args[2] = { MP_OBJ_NEW_SMALL_INT(err), MP_OBJ_FROM_PTR(o_str)};
  103. nlr_raise(mp_obj_exception_make_new(&mp_type_OSError, 2, 0, args));
  104. }
  105. STATIC mp_obj_ssl_socket_t *ussl_socket_new(mp_obj_t sock, struct ssl_args *args) {
  106. #if MICROPY_PY_USSL_FINALISER
  107. mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t);
  108. #else
  109. mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t);
  110. #endif
  111. o->base.type = &ussl_socket_type;
  112. o->buf = NULL;
  113. o->bytes_left = 0;
  114. o->sock = sock;
  115. o->blocking = true;
  116. uint32_t options = SSL_SERVER_VERIFY_LATER;
  117. if (!args->do_handshake.u_bool) {
  118. options |= SSL_CONNECT_IN_PARTS;
  119. }
  120. if (args->key.u_obj != mp_const_none) {
  121. options |= SSL_NO_DEFAULT_KEY;
  122. }
  123. if ((o->ssl_ctx = ssl_ctx_new(options, SSL_DEFAULT_CLNT_SESS)) == NULL) {
  124. mp_raise_OSError(MP_EINVAL);
  125. }
  126. if (args->key.u_obj != mp_const_none) {
  127. size_t len;
  128. const byte *data = (const byte *)mp_obj_str_get_data(args->key.u_obj, &len);
  129. int res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_RSA_KEY, data, len, NULL);
  130. if (res != SSL_OK) {
  131. mp_raise_ValueError(MP_ERROR_TEXT("invalid key"));
  132. }
  133. data = (const byte *)mp_obj_str_get_data(args->cert.u_obj, &len);
  134. res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_X509_CERT, data, len, NULL);
  135. if (res != SSL_OK) {
  136. mp_raise_ValueError(MP_ERROR_TEXT("invalid cert"));
  137. }
  138. }
  139. if (args->server_side.u_bool) {
  140. o->ssl_sock = ssl_server_new(o->ssl_ctx, (long)sock);
  141. } else {
  142. SSL_EXTENSIONS *ext = ssl_ext_new();
  143. if (args->server_hostname.u_obj != mp_const_none) {
  144. ext->host_name = (char *)mp_obj_str_get_str(args->server_hostname.u_obj);
  145. }
  146. o->ssl_sock = ssl_client_new(o->ssl_ctx, (long)sock, NULL, 0, ext);
  147. if (args->do_handshake.u_bool) {
  148. int res = ssl_handshake_status(o->ssl_sock);
  149. if (res != SSL_OK) {
  150. ussl_raise_error(res);
  151. }
  152. }
  153. }
  154. return o;
  155. }
  156. STATIC void ussl_socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  157. (void)kind;
  158. mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(self_in);
  159. mp_printf(print, "<_SSLSocket %p>", self->ssl_sock);
  160. }
  161. STATIC mp_uint_t ussl_socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) {
  162. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
  163. if (o->ssl_sock == NULL) {
  164. *errcode = EBADF;
  165. return MP_STREAM_ERROR;
  166. }
  167. while (o->bytes_left == 0) {
  168. mp_int_t r = ssl_read(o->ssl_sock, &o->buf);
  169. if (r == SSL_OK) {
  170. // SSL_OK from ssl_read() means "everything is ok, but there's
  171. // no user data yet". It may happen e.g. if handshake is not
  172. // finished yet. The best way we can treat it is by returning
  173. // EAGAIN. This may be a bit unexpected in blocking mode, but
  174. // default is to perform complete handshake in constructor, so
  175. // this should not happen in blocking mode. On the other hand,
  176. // in nonblocking mode EAGAIN (comparing to the alternative of
  177. // looping) is really preferrable.
  178. if (o->blocking) {
  179. continue;
  180. } else {
  181. goto eagain;
  182. }
  183. }
  184. if (r < 0) {
  185. if (r == SSL_CLOSE_NOTIFY || r == SSL_ERROR_CONN_LOST) {
  186. // EOF
  187. return 0;
  188. }
  189. if (r == SSL_EAGAIN) {
  190. eagain:
  191. r = MP_EAGAIN;
  192. }
  193. *errcode = r;
  194. return MP_STREAM_ERROR;
  195. }
  196. o->bytes_left = r;
  197. }
  198. if (size > o->bytes_left) {
  199. size = o->bytes_left;
  200. }
  201. memcpy(buf, o->buf, size);
  202. o->buf += size;
  203. o->bytes_left -= size;
  204. return size;
  205. }
  206. STATIC mp_uint_t ussl_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. if (o->ssl_sock == NULL) {
  209. *errcode = EBADF;
  210. return MP_STREAM_ERROR;
  211. }
  212. mp_int_t r = ssl_write(o->ssl_sock, buf, size);
  213. if (r < 0) {
  214. *errcode = r;
  215. return MP_STREAM_ERROR;
  216. }
  217. return r;
  218. }
  219. STATIC mp_uint_t ussl_socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) {
  220. mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(o_in);
  221. if (request == MP_STREAM_CLOSE && self->ssl_sock != NULL) {
  222. ssl_free(self->ssl_sock);
  223. ssl_ctx_free(self->ssl_ctx);
  224. self->ssl_sock = NULL;
  225. }
  226. // Pass all requests down to the underlying socket
  227. return mp_get_stream(self->sock)->ioctl(self->sock, request, arg, errcode);
  228. }
  229. STATIC mp_obj_t ussl_socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) {
  230. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(self_in);
  231. mp_obj_t sock = o->sock;
  232. mp_obj_t dest[3];
  233. mp_load_method(sock, MP_QSTR_setblocking, dest);
  234. dest[2] = flag_in;
  235. mp_obj_t res = mp_call_method_n_kw(1, 0, dest);
  236. o->blocking = mp_obj_is_true(flag_in);
  237. return res;
  238. }
  239. STATIC MP_DEFINE_CONST_FUN_OBJ_2(ussl_socket_setblocking_obj, ussl_socket_setblocking);
  240. STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = {
  241. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
  242. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
  243. { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
  244. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
  245. { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&ussl_socket_setblocking_obj) },
  246. { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) },
  247. #if MICROPY_PY_USSL_FINALISER
  248. { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) },
  249. #endif
  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 = ussl_socket_read,
  254. .write = ussl_socket_write,
  255. .ioctl = ussl_socket_ioctl,
  256. };
  257. STATIC const mp_obj_type_t ussl_socket_type = {
  258. { &mp_type_type },
  259. // Save on qstr's, reuse same as for module
  260. .name = MP_QSTR_ussl,
  261. .print = ussl_socket_print,
  262. .getiter = NULL,
  263. .iternext = NULL,
  264. .protocol = &ussl_socket_stream_p,
  265. .locals_dict = (void *)&ussl_socket_locals_dict,
  266. };
  267. STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  268. // TODO: Implement more args
  269. static const mp_arg_t allowed_args[] = {
  270. { MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
  271. { MP_QSTR_cert, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
  272. { MP_QSTR_server_side, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} },
  273. { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
  274. { MP_QSTR_do_handshake, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} },
  275. };
  276. // TODO: Check that sock implements stream protocol
  277. mp_obj_t sock = pos_args[0];
  278. struct ssl_args args;
  279. mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
  280. MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args);
  281. return MP_OBJ_FROM_PTR(ussl_socket_new(sock, &args));
  282. }
  283. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ssl_wrap_socket_obj, 1, mod_ssl_wrap_socket);
  284. STATIC const mp_rom_map_elem_t mp_module_ssl_globals_table[] = {
  285. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ussl) },
  286. { MP_ROM_QSTR(MP_QSTR_wrap_socket), MP_ROM_PTR(&mod_ssl_wrap_socket_obj) },
  287. };
  288. STATIC MP_DEFINE_CONST_DICT(mp_module_ssl_globals, mp_module_ssl_globals_table);
  289. const mp_obj_module_t mp_module_ussl = {
  290. .base = { &mp_type_module },
  291. .globals = (mp_obj_dict_t *)&mp_module_ssl_globals,
  292. };
  293. #endif // MICROPY_PY_USSL