modussl_axtls.c 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. #if MICROPY_PY_USSL && MICROPY_SSL_AXTLS
  31. #include "ssl.h"
  32. typedef struct _mp_obj_ssl_socket_t {
  33. mp_obj_base_t base;
  34. mp_obj_t sock;
  35. SSL_CTX *ssl_ctx;
  36. SSL *ssl_sock;
  37. byte *buf;
  38. uint32_t bytes_left;
  39. bool blocking;
  40. } mp_obj_ssl_socket_t;
  41. struct ssl_args {
  42. mp_arg_val_t key;
  43. mp_arg_val_t cert;
  44. mp_arg_val_t server_side;
  45. mp_arg_val_t server_hostname;
  46. mp_arg_val_t do_handshake;
  47. };
  48. STATIC const mp_obj_type_t ussl_socket_type;
  49. STATIC mp_obj_ssl_socket_t *ussl_socket_new(mp_obj_t sock, struct ssl_args *args) {
  50. #if MICROPY_PY_USSL_FINALISER
  51. mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t);
  52. #else
  53. mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t);
  54. #endif
  55. o->base.type = &ussl_socket_type;
  56. o->buf = NULL;
  57. o->bytes_left = 0;
  58. o->sock = sock;
  59. o->blocking = true;
  60. uint32_t options = SSL_SERVER_VERIFY_LATER;
  61. if (!args->do_handshake.u_bool) {
  62. options |= SSL_CONNECT_IN_PARTS;
  63. }
  64. if (args->key.u_obj != mp_const_none) {
  65. options |= SSL_NO_DEFAULT_KEY;
  66. }
  67. if ((o->ssl_ctx = ssl_ctx_new(options, SSL_DEFAULT_CLNT_SESS)) == NULL) {
  68. mp_raise_OSError(MP_EINVAL);
  69. }
  70. if (args->key.u_obj != mp_const_none) {
  71. size_t len;
  72. const byte *data = (const byte*)mp_obj_str_get_data(args->key.u_obj, &len);
  73. int res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_RSA_KEY, data, len, NULL);
  74. if (res != SSL_OK) {
  75. mp_raise_ValueError("invalid key");
  76. }
  77. data = (const byte*)mp_obj_str_get_data(args->cert.u_obj, &len);
  78. res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_X509_CERT, data, len, NULL);
  79. if (res != SSL_OK) {
  80. mp_raise_ValueError("invalid cert");
  81. }
  82. }
  83. if (args->server_side.u_bool) {
  84. o->ssl_sock = ssl_server_new(o->ssl_ctx, (long)sock);
  85. } else {
  86. SSL_EXTENSIONS *ext = ssl_ext_new();
  87. if (args->server_hostname.u_obj != mp_const_none) {
  88. ext->host_name = (char*)mp_obj_str_get_str(args->server_hostname.u_obj);
  89. }
  90. o->ssl_sock = ssl_client_new(o->ssl_ctx, (long)sock, NULL, 0, ext);
  91. if (args->do_handshake.u_bool) {
  92. int res = ssl_handshake_status(o->ssl_sock);
  93. if (res != SSL_OK) {
  94. printf("ssl_handshake_status: %d\n", res);
  95. ssl_display_error(res);
  96. mp_raise_OSError(MP_EIO);
  97. }
  98. }
  99. }
  100. return o;
  101. }
  102. STATIC void ussl_socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  103. (void)kind;
  104. mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(self_in);
  105. mp_printf(print, "<_SSLSocket %p>", self->ssl_sock);
  106. }
  107. STATIC mp_uint_t ussl_socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) {
  108. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
  109. if (o->ssl_sock == NULL) {
  110. *errcode = EBADF;
  111. return MP_STREAM_ERROR;
  112. }
  113. while (o->bytes_left == 0) {
  114. mp_int_t r = ssl_read(o->ssl_sock, &o->buf);
  115. if (r == SSL_OK) {
  116. // SSL_OK from ssl_read() means "everything is ok, but there's
  117. // no user data yet". It may happen e.g. if handshake is not
  118. // finished yet. The best way we can treat it is by returning
  119. // EAGAIN. This may be a bit unexpected in blocking mode, but
  120. // default is to perform complete handshake in constructor, so
  121. // this should not happen in blocking mode. On the other hand,
  122. // in nonblocking mode EAGAIN (comparing to the alternative of
  123. // looping) is really preferrable.
  124. if (o->blocking) {
  125. continue;
  126. } else {
  127. goto eagain;
  128. }
  129. }
  130. if (r < 0) {
  131. if (r == SSL_CLOSE_NOTIFY || r == SSL_ERROR_CONN_LOST) {
  132. // EOF
  133. return 0;
  134. }
  135. if (r == SSL_EAGAIN) {
  136. eagain:
  137. r = MP_EAGAIN;
  138. }
  139. *errcode = r;
  140. return MP_STREAM_ERROR;
  141. }
  142. o->bytes_left = r;
  143. }
  144. if (size > o->bytes_left) {
  145. size = o->bytes_left;
  146. }
  147. memcpy(buf, o->buf, size);
  148. o->buf += size;
  149. o->bytes_left -= size;
  150. return size;
  151. }
  152. STATIC mp_uint_t ussl_socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) {
  153. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
  154. if (o->ssl_sock == NULL) {
  155. *errcode = EBADF;
  156. return MP_STREAM_ERROR;
  157. }
  158. mp_int_t r = ssl_write(o->ssl_sock, buf, size);
  159. if (r < 0) {
  160. *errcode = r;
  161. return MP_STREAM_ERROR;
  162. }
  163. return r;
  164. }
  165. STATIC mp_uint_t ussl_socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) {
  166. mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(o_in);
  167. if (request == MP_STREAM_CLOSE && self->ssl_sock != NULL) {
  168. ssl_free(self->ssl_sock);
  169. ssl_ctx_free(self->ssl_ctx);
  170. self->ssl_sock = NULL;
  171. }
  172. // Pass all requests down to the underlying socket
  173. return mp_get_stream(self->sock)->ioctl(self->sock, request, arg, errcode);
  174. }
  175. STATIC mp_obj_t ussl_socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) {
  176. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(self_in);
  177. mp_obj_t sock = o->sock;
  178. mp_obj_t dest[3];
  179. mp_load_method(sock, MP_QSTR_setblocking, dest);
  180. dest[2] = flag_in;
  181. mp_obj_t res = mp_call_method_n_kw(1, 0, dest);
  182. o->blocking = mp_obj_is_true(flag_in);
  183. return res;
  184. }
  185. STATIC MP_DEFINE_CONST_FUN_OBJ_2(ussl_socket_setblocking_obj, ussl_socket_setblocking);
  186. STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = {
  187. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
  188. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
  189. { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
  190. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
  191. { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&ussl_socket_setblocking_obj) },
  192. { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) },
  193. #if MICROPY_PY_USSL_FINALISER
  194. { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) },
  195. #endif
  196. };
  197. STATIC MP_DEFINE_CONST_DICT(ussl_socket_locals_dict, ussl_socket_locals_dict_table);
  198. STATIC const mp_stream_p_t ussl_socket_stream_p = {
  199. .read = ussl_socket_read,
  200. .write = ussl_socket_write,
  201. .ioctl = ussl_socket_ioctl,
  202. };
  203. STATIC const mp_obj_type_t ussl_socket_type = {
  204. { &mp_type_type },
  205. // Save on qstr's, reuse same as for module
  206. .name = MP_QSTR_ussl,
  207. .print = ussl_socket_print,
  208. .getiter = NULL,
  209. .iternext = NULL,
  210. .protocol = &ussl_socket_stream_p,
  211. .locals_dict = (void*)&ussl_socket_locals_dict,
  212. };
  213. STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  214. // TODO: Implement more args
  215. static const mp_arg_t allowed_args[] = {
  216. { MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  217. { MP_QSTR_cert, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  218. { MP_QSTR_server_side, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} },
  219. { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} },
  220. { MP_QSTR_do_handshake, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} },
  221. };
  222. // TODO: Check that sock implements stream protocol
  223. mp_obj_t sock = pos_args[0];
  224. struct ssl_args args;
  225. mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
  226. MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
  227. return MP_OBJ_FROM_PTR(ussl_socket_new(sock, &args));
  228. }
  229. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ssl_wrap_socket_obj, 1, mod_ssl_wrap_socket);
  230. STATIC const mp_rom_map_elem_t mp_module_ssl_globals_table[] = {
  231. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ussl) },
  232. { MP_ROM_QSTR(MP_QSTR_wrap_socket), MP_ROM_PTR(&mod_ssl_wrap_socket_obj) },
  233. };
  234. STATIC MP_DEFINE_CONST_DICT(mp_module_ssl_globals, mp_module_ssl_globals_table);
  235. const mp_obj_module_t mp_module_ussl = {
  236. .base = { &mp_type_module },
  237. .globals = (mp_obj_dict_t*)&mp_module_ssl_globals,
  238. };
  239. #endif // MICROPY_PY_USSL