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