modussl_axtls.c 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2015-2017 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. } mp_obj_ssl_socket_t;
  40. struct ssl_args {
  41. mp_arg_val_t key;
  42. mp_arg_val_t cert;
  43. mp_arg_val_t server_side;
  44. mp_arg_val_t server_hostname;
  45. };
  46. STATIC const mp_obj_type_t ussl_socket_type;
  47. STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) {
  48. #if MICROPY_PY_USSL_FINALISER
  49. mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t);
  50. #else
  51. mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t);
  52. #endif
  53. o->base.type = &ussl_socket_type;
  54. o->buf = NULL;
  55. o->bytes_left = 0;
  56. o->sock = sock;
  57. uint32_t options = SSL_SERVER_VERIFY_LATER;
  58. if (args->key.u_obj != mp_const_none) {
  59. options |= SSL_NO_DEFAULT_KEY;
  60. }
  61. if ((o->ssl_ctx = ssl_ctx_new(options, SSL_DEFAULT_CLNT_SESS)) == NULL) {
  62. mp_raise_OSError(MP_EINVAL);
  63. }
  64. if (args->key.u_obj != mp_const_none) {
  65. size_t len;
  66. const byte *data = (const byte*)mp_obj_str_get_data(args->key.u_obj, &len);
  67. int res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_RSA_KEY, data, len, NULL);
  68. if (res != SSL_OK) {
  69. mp_raise_ValueError("invalid key");
  70. }
  71. data = (const byte*)mp_obj_str_get_data(args->cert.u_obj, &len);
  72. res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_X509_CERT, data, len, NULL);
  73. if (res != SSL_OK) {
  74. mp_raise_ValueError("invalid cert");
  75. }
  76. }
  77. if (args->server_side.u_bool) {
  78. o->ssl_sock = ssl_server_new(o->ssl_ctx, (long)sock);
  79. } else {
  80. SSL_EXTENSIONS *ext = ssl_ext_new();
  81. if (args->server_hostname.u_obj != mp_const_none) {
  82. ext->host_name = (char*)mp_obj_str_get_str(args->server_hostname.u_obj);
  83. }
  84. o->ssl_sock = ssl_client_new(o->ssl_ctx, (long)sock, NULL, 0, ext);
  85. int res = ssl_handshake_status(o->ssl_sock);
  86. // Pointer to SSL_EXTENSIONS as being passed to ssl_client_new()
  87. // is saved in ssl_sock->extensions.
  88. // As of axTLS 2.1.3, extensions aren't used beyond the initial
  89. // handshake, and that's pretty much how it's expected to be. So
  90. // we allocate them on stack and reset the pointer after handshake.
  91. if (res != SSL_OK) {
  92. printf("ssl_handshake_status: %d\n", res);
  93. ssl_display_error(res);
  94. mp_raise_OSError(MP_EIO);
  95. }
  96. }
  97. return o;
  98. }
  99. STATIC void socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  100. (void)kind;
  101. mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(self_in);
  102. mp_printf(print, "<_SSLSocket %p>", self->ssl_sock);
  103. }
  104. STATIC mp_uint_t socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) {
  105. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
  106. if (o->ssl_sock == NULL) {
  107. *errcode = EBADF;
  108. return MP_STREAM_ERROR;
  109. }
  110. while (o->bytes_left == 0) {
  111. mp_int_t r = ssl_read(o->ssl_sock, &o->buf);
  112. if (r == SSL_OK) {
  113. // SSL_OK from ssl_read() means "everything is ok, but there's
  114. // no user data yet". So, we just keep reading.
  115. continue;
  116. }
  117. if (r < 0) {
  118. if (r == SSL_CLOSE_NOTIFY || r == SSL_ERROR_CONN_LOST) {
  119. // EOF
  120. return 0;
  121. }
  122. if (r == SSL_EAGAIN) {
  123. r = MP_EAGAIN;
  124. }
  125. *errcode = r;
  126. return MP_STREAM_ERROR;
  127. }
  128. o->bytes_left = r;
  129. }
  130. if (size > o->bytes_left) {
  131. size = o->bytes_left;
  132. }
  133. memcpy(buf, o->buf, size);
  134. o->buf += size;
  135. o->bytes_left -= size;
  136. return size;
  137. }
  138. STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) {
  139. mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
  140. if (o->ssl_sock == NULL) {
  141. *errcode = EBADF;
  142. return MP_STREAM_ERROR;
  143. }
  144. mp_int_t r = ssl_write(o->ssl_sock, buf, size);
  145. if (r < 0) {
  146. *errcode = r;
  147. return MP_STREAM_ERROR;
  148. }
  149. return r;
  150. }
  151. STATIC mp_uint_t socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) {
  152. mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(o_in);
  153. if (request == MP_STREAM_CLOSE && self->ssl_sock != NULL) {
  154. ssl_free(self->ssl_sock);
  155. ssl_ctx_free(self->ssl_ctx);
  156. self->ssl_sock = NULL;
  157. }
  158. // Pass all requests down to the underlying socket
  159. return mp_get_stream(self->sock)->ioctl(self->sock, request, arg, errcode);
  160. }
  161. STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) {
  162. // Currently supports only blocking mode
  163. (void)self_in;
  164. if (!mp_obj_is_true(flag_in)) {
  165. mp_raise_NotImplementedError(NULL);
  166. }
  167. return mp_const_none;
  168. }
  169. STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking);
  170. STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = {
  171. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
  172. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
  173. { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
  174. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
  175. { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) },
  176. { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) },
  177. #if MICROPY_PY_USSL_FINALISER
  178. { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) },
  179. #endif
  180. };
  181. STATIC MP_DEFINE_CONST_DICT(ussl_socket_locals_dict, ussl_socket_locals_dict_table);
  182. STATIC const mp_stream_p_t ussl_socket_stream_p = {
  183. .read = socket_read,
  184. .write = socket_write,
  185. .ioctl = socket_ioctl,
  186. };
  187. STATIC const mp_obj_type_t ussl_socket_type = {
  188. { &mp_type_type },
  189. // Save on qstr's, reuse same as for module
  190. .name = MP_QSTR_ussl,
  191. .print = socket_print,
  192. .getiter = NULL,
  193. .iternext = NULL,
  194. .protocol = &ussl_socket_stream_p,
  195. .locals_dict = (void*)&ussl_socket_locals_dict,
  196. };
  197. STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  198. // TODO: Implement more args
  199. static const mp_arg_t allowed_args[] = {
  200. { MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
  201. { MP_QSTR_cert, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
  202. { MP_QSTR_server_side, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} },
  203. { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
  204. };
  205. // TODO: Check that sock implements stream protocol
  206. mp_obj_t sock = pos_args[0];
  207. struct ssl_args args;
  208. mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
  209. MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
  210. return MP_OBJ_FROM_PTR(socket_new(sock, &args));
  211. }
  212. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ssl_wrap_socket_obj, 1, mod_ssl_wrap_socket);
  213. STATIC const mp_rom_map_elem_t mp_module_ssl_globals_table[] = {
  214. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ussl) },
  215. { MP_ROM_QSTR(MP_QSTR_wrap_socket), MP_ROM_PTR(&mod_ssl_wrap_socket_obj) },
  216. };
  217. STATIC MP_DEFINE_CONST_DICT(mp_module_ssl_globals, mp_module_ssl_globals_table);
  218. const mp_obj_module_t mp_module_ussl = {
  219. .base = { &mp_type_module },
  220. .globals = (mp_obj_dict_t*)&mp_module_ssl_globals,
  221. };
  222. #endif // MICROPY_PY_USSL