• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "ssl_pm.h"
16 #include "ssl_port.h"
17 #include "ssl_dbg.h"
18 
19 /* mbedtls include */
20 #include "mbedtls/platform.h"
21 #if defined(LWS_HAVE_MBEDTLS_NET_SOCKETS)
22 #include "mbedtls/net_sockets.h"
23 #else
24 #include "mbedtls/net.h"
25 #endif
26 #include "mbedtls/debug.h"
27 #include "mbedtls/entropy.h"
28 #include "mbedtls/ctr_drbg.h"
29 #include "mbedtls/error.h"
30 #include "mbedtls/certs.h"
31 
32 #include "private-lib-core.h"
33 
34 #define X509_INFO_STRING_LENGTH 8192
35 
36 struct ssl_pm
37 {
38     /* local socket file description */
39     mbedtls_net_context fd;
40     /* remote client socket file description */
41     mbedtls_net_context cl_fd;
42 
43     mbedtls_ssl_config conf;
44 
45     mbedtls_ctr_drbg_context ctr_drbg;
46 
47     mbedtls_ssl_context ssl;
48 
49     mbedtls_entropy_context entropy;
50 
51     SSL *owner;
52 };
53 
54 struct x509_pm
55 {
56     mbedtls_x509_crt *x509_crt;
57 
58     mbedtls_x509_crt *ex_crt;
59 };
60 
61 struct pkey_pm
62 {
63     mbedtls_pk_context *pkey;
64 
65     mbedtls_pk_context *ex_pkey;
66 };
67 
68 unsigned int max_content_len;
69 
70 /*********************************************************************************************/
71 /************************************ SSL arch interface *************************************/
72 
73 //#ifdef CONFIG_OPENSSL_LOWLEVEL_DEBUG
74 
75 /* mbedtls debug level */
76 #define MBEDTLS_DEBUG_LEVEL 4
77 
78 /**
79  * @brief mbedtls debug function
80  */
ssl_platform_debug(void * ctx,int level,const char * file,int line,const char * str)81 static void ssl_platform_debug(void *ctx, int level,
82                      const char *file, int line,
83                      const char *str)
84 {
85     /* Shorten 'file' from the whole file path to just the filename
86 
87        This is a bit wasteful because the macros are compiled in with
88        the full _FILE_ path in each case.
89     */
90 //    char *file_sep = rindex(file, '/');
91   //  if(file_sep)
92     //    file = file_sep + 1;
93 
94     printf("%s:%d %s", file, line, str);
95 }
96 //#endif
97 
98 /**
99  * @brief create SSL low-level object
100  */
ssl_pm_new(SSL * ssl)101 int ssl_pm_new(SSL *ssl)
102 {
103     struct ssl_pm *ssl_pm;
104     int ret;
105 
106     const unsigned char pers[] = "OpenSSL PM";
107     size_t pers_len = sizeof(pers);
108 
109     int endpoint;
110     int version;
111 
112     const SSL_METHOD *method = ssl->method;
113 
114     ssl_pm = ssl_mem_zalloc(sizeof(struct ssl_pm));
115     if (!ssl_pm) {
116         SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "no enough memory > (ssl_pm)");
117         goto no_mem;
118     }
119 
120     ssl_pm->owner = ssl;
121 
122     if (!ssl->ctx->read_buffer_len)
123 	    ssl->ctx->read_buffer_len = 2048;
124 
125     max_content_len = ssl->ctx->read_buffer_len;
126     // printf("ssl->ctx->read_buffer_len = %d ++++++++++++++++++++\n", ssl->ctx->read_buffer_len);
127 
128     mbedtls_net_init(&ssl_pm->fd);
129     mbedtls_net_init(&ssl_pm->cl_fd);
130 
131     mbedtls_ssl_config_init(&ssl_pm->conf);
132     mbedtls_ctr_drbg_init(&ssl_pm->ctr_drbg);
133     mbedtls_entropy_init(&ssl_pm->entropy);
134     mbedtls_ssl_init(&ssl_pm->ssl);
135 
136     ret = mbedtls_ctr_drbg_seed(&ssl_pm->ctr_drbg, mbedtls_entropy_func, &ssl_pm->entropy, pers, pers_len);
137     if (ret) {
138         lwsl_notice("%s: mbedtls_ctr_drbg_seed() return -0x%x", __func__, -ret);
139         //goto mbedtls_err1;
140     }
141 
142     if (method->endpoint) {
143         endpoint = MBEDTLS_SSL_IS_SERVER;
144     } else {
145         endpoint = MBEDTLS_SSL_IS_CLIENT;
146     }
147     ret = mbedtls_ssl_config_defaults(&ssl_pm->conf, endpoint, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);
148     if (ret) {
149 	    lwsl_err("%s: mbedtls_ssl_config_defaults() return -0x%x", __func__, -ret);
150         SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "mbedtls_ssl_config_defaults() return -0x%x", -ret);
151         goto mbedtls_err2;
152     }
153 
154     if (TLS_ANY_VERSION != ssl->version) {
155         if (TLS1_2_VERSION == ssl->version)
156             version = MBEDTLS_SSL_MINOR_VERSION_3;
157         else if (TLS1_1_VERSION == ssl->version)
158             version = MBEDTLS_SSL_MINOR_VERSION_2;
159         else if (TLS1_VERSION == ssl->version)
160             version = MBEDTLS_SSL_MINOR_VERSION_1;
161         else
162             version = MBEDTLS_SSL_MINOR_VERSION_0;
163 
164         mbedtls_ssl_conf_max_version(&ssl_pm->conf, MBEDTLS_SSL_MAJOR_VERSION_3, version);
165         mbedtls_ssl_conf_min_version(&ssl_pm->conf, MBEDTLS_SSL_MAJOR_VERSION_3, version);
166     } else {
167         mbedtls_ssl_conf_max_version(&ssl_pm->conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
168         mbedtls_ssl_conf_min_version(&ssl_pm->conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0);
169     }
170 
171     mbedtls_ssl_conf_rng(&ssl_pm->conf, mbedtls_ctr_drbg_random, &ssl_pm->ctr_drbg);
172 
173 //#ifdef CONFIG_OPENSSL_LOWLEVEL_DEBUG
174  //   mbedtls_debug_set_threshold(MBEDTLS_DEBUG_LEVEL);
175 //    mbedtls_ssl_conf_dbg(&ssl_pm->conf, ssl_platform_debug, NULL);
176 //#else
177     mbedtls_ssl_conf_dbg(&ssl_pm->conf, ssl_platform_debug, NULL);
178 //#endif
179 
180     ret = mbedtls_ssl_setup(&ssl_pm->ssl, &ssl_pm->conf);
181     if (ret) {
182 	    lwsl_err("%s: mbedtls_ssl_setup() return -0x%x", __func__, -ret);
183 
184         SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "mbedtls_ssl_setup() return -0x%x", -ret);
185         goto mbedtls_err2;
186     }
187 
188     mbedtls_ssl_set_bio(&ssl_pm->ssl, &ssl_pm->fd, mbedtls_net_send, mbedtls_net_recv, NULL);
189 
190     ssl->ssl_pm = ssl_pm;
191 
192     return 0;
193 
194 mbedtls_err2:
195     mbedtls_ssl_config_free(&ssl_pm->conf);
196     mbedtls_ctr_drbg_free(&ssl_pm->ctr_drbg);
197 //mbedtls_err1:
198     mbedtls_entropy_free(&ssl_pm->entropy);
199     ssl_mem_free(ssl_pm);
200 no_mem:
201     return -1;
202 }
203 
204 /**
205  * @brief free SSL low-level object
206  */
ssl_pm_free(SSL * ssl)207 void ssl_pm_free(SSL *ssl)
208 {
209     struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;
210 
211     mbedtls_ctr_drbg_free(&ssl_pm->ctr_drbg);
212     mbedtls_entropy_free(&ssl_pm->entropy);
213     mbedtls_ssl_config_free(&ssl_pm->conf);
214     mbedtls_ssl_free(&ssl_pm->ssl);
215 
216     ssl_mem_free(ssl_pm);
217     ssl->ssl_pm = NULL;
218 }
219 
220 /**
221  * @brief reload SSL low-level certification object
222  */
ssl_pm_reload_crt(SSL * ssl)223 static int ssl_pm_reload_crt(SSL *ssl)
224 {
225     int ret;
226     int mode;
227     struct ssl_pm *ssl_pm = ssl->ssl_pm;
228     struct x509_pm *ca_pm = (struct x509_pm *)ssl->client_CA->x509_pm;
229 
230     struct pkey_pm *pkey_pm = (struct pkey_pm *)ssl->cert->pkey->pkey_pm;
231     struct x509_pm *crt_pm = (struct x509_pm *)ssl->cert->x509->x509_pm;
232 
233     if (ssl->verify_mode == SSL_VERIFY_PEER)
234         mode = MBEDTLS_SSL_VERIFY_OPTIONAL;
235     else if (ssl->verify_mode == SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
236         mode = MBEDTLS_SSL_VERIFY_OPTIONAL;
237     else if (ssl->verify_mode == SSL_VERIFY_CLIENT_ONCE)
238         mode = MBEDTLS_SSL_VERIFY_UNSET;
239     else
240         mode = MBEDTLS_SSL_VERIFY_NONE;
241 
242     mbedtls_ssl_conf_authmode(&ssl_pm->conf, mode);
243 
244     if (ca_pm->x509_crt) {
245         mbedtls_ssl_conf_ca_chain(&ssl_pm->conf, ca_pm->x509_crt, NULL);
246     } else if (ca_pm->ex_crt) {
247         mbedtls_ssl_conf_ca_chain(&ssl_pm->conf, ca_pm->ex_crt, NULL);
248     }
249 
250     if (crt_pm->x509_crt && pkey_pm->pkey) {
251         ret = mbedtls_ssl_conf_own_cert(&ssl_pm->conf, crt_pm->x509_crt, pkey_pm->pkey);
252     } else if (crt_pm->ex_crt && pkey_pm->ex_pkey) {
253         ret = mbedtls_ssl_conf_own_cert(&ssl_pm->conf, crt_pm->ex_crt, pkey_pm->ex_pkey);
254     } else {
255         ret = 0;
256     }
257 
258     if (ret) {
259         SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "mbedtls_ssl_conf_own_cert() return -0x%x", -ret);
260         ret = -1;
261     }
262 
263     return ret;
264 }
265 
266 /*
267  * Perform the mbedtls SSL handshake instead of mbedtls_ssl_handshake.
268  * We can add debug here.
269  */
mbedtls_handshake(mbedtls_ssl_context * ssl)270 static int mbedtls_handshake( mbedtls_ssl_context *ssl )
271 {
272     int ret = 0;
273 
274     while (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {
275         ret = mbedtls_ssl_handshake_step(ssl);
276 
277         lwsl_info("%s: ssl ret -%x state %d\n", __func__, -ret, ssl->state);
278 
279         if (ret != 0)
280             break;
281     }
282 
283     return ret;
284 }
285 
286 #if !defined(LWS_PLAT_OPTEE)
287 #include <errno.h>
288 #endif
289 
ssl_pm_handshake(SSL * ssl)290 int ssl_pm_handshake(SSL *ssl)
291 {
292     int ret;
293     struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;
294 
295     ssl->err = 0;
296     errno = 0;
297 
298     ret = ssl_pm_reload_crt(ssl);
299     if (ret) {
300 	    printf("%s: cert reload failed\n", __func__);
301         return 0;
302     }
303 
304     if (ssl_pm->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER) {
305 	    ssl_speed_up_enter();
306 
307 	   /* mbedtls return codes
308 	    * 0 = successful, or MBEDTLS_ERR_SSL_WANT_READ/WRITE
309 	    * anything else = death
310 	    */
311 	    ret = mbedtls_handshake(&ssl_pm->ssl);
312 	    ssl_speed_up_exit();
313     } else
314 	    ret = 0;
315 
316     /*
317      * OpenSSL return codes:
318      *   0 = did not complete, but may be retried
319      *   1 = successfully completed
320      *   <0 = death
321      */
322     if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
323 	    ssl->err = ret;
324         SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "mbedtls_ssl_handshake() return -0x%x", -ret);
325         return 0; /* OpenSSL: did not complete but may be retried */
326     }
327 
328     if (ret == 0) { /* successful */
329         struct x509_pm *x509_pm = (struct x509_pm *)ssl->session->peer->x509_pm;
330 
331         x509_pm->ex_crt = (mbedtls_x509_crt *)mbedtls_ssl_get_peer_cert(&ssl_pm->ssl);
332         return 1; /* openssl successful */
333     }
334 
335     if (errno == 11) {
336 	    ssl->err = ret == MBEDTLS_ERR_SSL_WANT_READ;
337 
338 	    return 0;
339     }
340 
341     lwsl_info("%s: mbedtls_ssl_handshake() returned -0x%x\n", __func__, -ret);
342 
343     /* it's had it */
344 
345     ssl->err = SSL_ERROR_SYSCALL;
346 
347     return -1; /* openssl death */
348 }
349 
350 mbedtls_x509_crt *
ssl_ctx_get_mbedtls_x509_crt(SSL_CTX * ssl_ctx)351 ssl_ctx_get_mbedtls_x509_crt(SSL_CTX *ssl_ctx)
352 {
353 	struct x509_pm *x509_pm = (struct x509_pm *)ssl_ctx->cert->x509->x509_pm;
354 
355 	if (!x509_pm)
356 		return NULL;
357 
358 	return x509_pm->x509_crt;
359 }
360 
361 mbedtls_x509_crt *
ssl_get_peer_mbedtls_x509_crt(SSL * ssl)362 ssl_get_peer_mbedtls_x509_crt(SSL *ssl)
363 {
364 	struct x509_pm *x509_pm = (struct x509_pm *)ssl->session->peer->x509_pm;
365 
366 	if (!x509_pm)
367 		return NULL;
368 
369 	return x509_pm->ex_crt;
370 }
371 
ssl_pm_shutdown(SSL * ssl)372 int ssl_pm_shutdown(SSL *ssl)
373 {
374     int ret;
375     struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;
376 
377     ret = mbedtls_ssl_close_notify(&ssl_pm->ssl);
378     if (ret) {
379         SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "mbedtls_ssl_close_notify() return -0x%x", -ret);
380         if (ret == MBEDTLS_ERR_NET_CONN_RESET)
381 		ssl->err = SSL_ERROR_SYSCALL;
382 	 ret = -1; /* OpenSSL: "Call SSL_get_error with the return value to find the reason */
383     } else {
384         struct x509_pm *x509_pm = (struct x509_pm *)ssl->session->peer->x509_pm;
385 
386         x509_pm->ex_crt = NULL;
387         ret = 1; /* OpenSSL: "The shutdown was successfully completed"
388 		     ...0 means retry */
389     }
390 
391     return ret;
392 }
393 
ssl_pm_clear(SSL * ssl)394 int ssl_pm_clear(SSL *ssl)
395 {
396     return ssl_pm_shutdown(ssl);
397 }
398 
399 
ssl_pm_read(SSL * ssl,void * buffer,int len)400 int ssl_pm_read(SSL *ssl, void *buffer, int len)
401 {
402     int ret;
403     struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;
404 
405     ret = mbedtls_ssl_read(&ssl_pm->ssl, buffer, len);
406     if (ret < 0) {
407 	 //   lwsl_notice("%s: mbedtls_ssl_read says -0x%x\n", __func__, -ret);
408         SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "mbedtls_ssl_read() return -0x%x", -ret);
409         if (ret == MBEDTLS_ERR_NET_CONN_RESET ||
410             ret <= MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE) /* fatal errors */
411 		ssl->err = SSL_ERROR_SYSCALL;
412         ret = -1;
413     }
414 
415     return ret;
416 }
417 
418 /*
419  * This returns -1, or the length sent.
420  * If -1, then you need to find out if the error was
421  * fatal or recoverable using SSL_get_error()
422  */
ssl_pm_send(SSL * ssl,const void * buffer,int len)423 int ssl_pm_send(SSL *ssl, const void *buffer, int len)
424 {
425     int ret;
426     struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;
427 
428     ret = mbedtls_ssl_write(&ssl_pm->ssl, buffer, len);
429     /*
430      * We can get a positive number, which may be less than len... that
431      * much was sent successfully and you can call again to send more.
432      *
433      * We can get a negative mbedtls error code... if WANT_WRITE or WANT_READ,
434      * it's nonfatal and means it should be retried as-is.  If something else,
435      * it's fatal actually.
436      *
437      * If this function returns something other than a positive value or
438      * MBEDTLS_ERR_SSL_WANT_READ/WRITE, the ssl context becomes unusable, and
439      * you should either free it or call mbedtls_ssl_session_reset() on it
440      * before re-using it for a new connection; the current connection must
441      * be closed.
442      *
443      * When this function returns MBEDTLS_ERR_SSL_WANT_WRITE/READ, it must be
444      * called later with the same arguments, until it returns a positive value.
445      */
446 
447     if (ret < 0) {
448 	    SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "mbedtls_ssl_write() return -0x%x", -ret);
449 	switch (ret) {
450 	case MBEDTLS_ERR_NET_SEND_FAILED:
451 	case MBEDTLS_ERR_NET_CONN_RESET:
452 		ssl->err = SSL_ERROR_SYSCALL;
453 		break;
454 	case MBEDTLS_ERR_SSL_WANT_WRITE:
455 		ssl->err = SSL_ERROR_WANT_WRITE;
456 		break;
457 	case MBEDTLS_ERR_SSL_WANT_READ:
458 		ssl->err = SSL_ERROR_WANT_READ;
459 		break;
460 	default:
461 		break;
462 	}
463 
464 	ret = -1;
465     }
466 
467     return ret;
468 }
469 
ssl_pm_pending(const SSL * ssl)470 int ssl_pm_pending(const SSL *ssl)
471 {
472     struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;
473 
474     return mbedtls_ssl_get_bytes_avail(&ssl_pm->ssl);
475 }
476 
ssl_pm_set_fd(SSL * ssl,int fd,int mode)477 void ssl_pm_set_fd(SSL *ssl, int fd, int mode)
478 {
479     struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;
480 
481     ssl_pm->fd.fd = fd;
482 }
483 
ssl_pm_get_fd(const SSL * ssl,int mode)484 int ssl_pm_get_fd(const SSL *ssl, int mode)
485 {
486     struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;
487 
488     return ssl_pm->fd.fd;
489 }
490 
ssl_pm_get_state(const SSL * ssl)491 OSSL_HANDSHAKE_STATE ssl_pm_get_state(const SSL *ssl)
492 {
493     OSSL_HANDSHAKE_STATE state;
494 
495     struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;
496 
497     switch (ssl_pm->ssl.state)
498     {
499         case MBEDTLS_SSL_CLIENT_HELLO:
500             state = TLS_ST_CW_CLNT_HELLO;
501             break;
502         case MBEDTLS_SSL_SERVER_HELLO:
503             state = TLS_ST_SW_SRVR_HELLO;
504             break;
505         case MBEDTLS_SSL_SERVER_CERTIFICATE:
506             state = TLS_ST_SW_CERT;
507             break;
508         case MBEDTLS_SSL_SERVER_HELLO_DONE:
509             state = TLS_ST_SW_SRVR_DONE;
510             break;
511         case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
512             state = TLS_ST_CW_KEY_EXCH;
513             break;
514         case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
515             state = TLS_ST_CW_CHANGE;
516             break;
517         case MBEDTLS_SSL_CLIENT_FINISHED:
518             state = TLS_ST_CW_FINISHED;
519             break;
520         case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
521             state = TLS_ST_SW_CHANGE;
522             break;
523         case MBEDTLS_SSL_SERVER_FINISHED:
524             state = TLS_ST_SW_FINISHED;
525             break;
526         case MBEDTLS_SSL_CLIENT_CERTIFICATE:
527             state = TLS_ST_CW_CERT;
528             break;
529         case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
530             state = TLS_ST_SR_KEY_EXCH;
531             break;
532         case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET:
533             state = TLS_ST_SW_SESSION_TICKET;
534             break;
535         case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT:
536             state = TLS_ST_SW_CERT_REQ;
537             break;
538         case MBEDTLS_SSL_HANDSHAKE_OVER:
539             state = TLS_ST_OK;
540             break;
541         default :
542             state = TLS_ST_BEFORE;
543             break;
544     }
545 
546     return state;
547 }
548 
x509_pm_show_info(X509 * x)549 int x509_pm_show_info(X509 *x)
550 {
551     int ret;
552     char *buf;
553     mbedtls_x509_crt *x509_crt;
554     struct x509_pm *x509_pm = x->x509_pm;
555 
556     if (x509_pm->x509_crt)
557         x509_crt = x509_pm->x509_crt;
558     else if (x509_pm->ex_crt)
559         x509_crt = x509_pm->ex_crt;
560     else
561         x509_crt = NULL;
562 
563     if (!x509_crt)
564         return -1;
565 
566     buf = ssl_mem_malloc(X509_INFO_STRING_LENGTH);
567     if (!buf) {
568         SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "no enough memory > (buf)");
569         goto no_mem;
570     }
571 
572     ret = mbedtls_x509_crt_info(buf, X509_INFO_STRING_LENGTH - 1, "", x509_crt);
573     if (ret <= 0) {
574         SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "mbedtls_x509_crt_info() return -0x%x", -ret);
575         goto mbedtls_err1;
576     }
577 
578     buf[ret] = 0;
579 
580     ssl_mem_free(buf);
581 
582     SSL_DEBUG(SSL_DEBUG_ON, "%s", buf);
583 
584     return 0;
585 
586 mbedtls_err1:
587     ssl_mem_free(buf);
588 no_mem:
589     return -1;
590 }
591 
x509_pm_new(X509 * x,X509 * m_x)592 int x509_pm_new(X509 *x, X509 *m_x)
593 {
594     struct x509_pm *x509_pm;
595 
596     x509_pm = ssl_mem_zalloc(sizeof(struct x509_pm));
597     if (!x509_pm) {
598         SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "no enough memory > (x509_pm)");
599         goto failed1;
600     }
601 
602     x->x509_pm = x509_pm;
603 
604     if (m_x) {
605         struct x509_pm *m_x509_pm = (struct x509_pm *)m_x->x509_pm;
606 
607         x509_pm->ex_crt = m_x509_pm->x509_crt;
608     }
609 
610     return 0;
611 
612 failed1:
613     return -1;
614 }
615 
x509_pm_free(X509 * x)616 void x509_pm_free(X509 *x)
617 {
618     struct x509_pm *x509_pm = (struct x509_pm *)x->x509_pm;
619 
620     if (x509_pm->x509_crt) {
621         mbedtls_x509_crt_free(x509_pm->x509_crt);
622 
623         ssl_mem_free(x509_pm->x509_crt);
624         x509_pm->x509_crt = NULL;
625     }
626 
627     ssl_mem_free(x->x509_pm);
628     x->x509_pm = NULL;
629 }
630 
x509_pm_load(X509 * x,const unsigned char * buffer,int len)631 int x509_pm_load(X509 *x, const unsigned char *buffer, int len)
632 {
633     int ret;
634     unsigned char *load_buf;
635     struct x509_pm *x509_pm = (struct x509_pm *)x->x509_pm;
636 
637 	if (x509_pm->x509_crt)
638         mbedtls_x509_crt_free(x509_pm->x509_crt);
639 
640     if (!x509_pm->x509_crt) {
641         x509_pm->x509_crt = ssl_mem_malloc(sizeof(mbedtls_x509_crt));
642         if (!x509_pm->x509_crt) {
643             SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "no enough memory > (x509_pm->x509_crt)");
644             goto no_mem;
645         }
646     }
647 
648     mbedtls_x509_crt_init(x509_pm->x509_crt);
649     if (buffer[0] != 0x30) {
650 	    load_buf = ssl_mem_malloc(len + 1);
651 	    if (!load_buf) {
652 		SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "no enough memory > (load_buf)");
653 		goto failed;
654 	    }
655 
656 	    ssl_memcpy(load_buf, buffer, len);
657 	    load_buf[len] = '\0';
658 
659 	    ret = mbedtls_x509_crt_parse(x509_pm->x509_crt, load_buf, len + 1);
660 	    ssl_mem_free(load_buf);
661     } else {
662 	    // printf("parsing as der\n");
663 
664 	    ret = mbedtls_x509_crt_parse_der(x509_pm->x509_crt, buffer, len);
665     }
666 
667     if (ret) {
668         printf("mbedtls_x509_crt_parse return -0x%x", -ret);
669         goto failed;
670     }
671 
672     return 0;
673 
674 failed:
675     mbedtls_x509_crt_free(x509_pm->x509_crt);
676     ssl_mem_free(x509_pm->x509_crt);
677     x509_pm->x509_crt = NULL;
678 no_mem:
679     return -1;
680 }
681 
pkey_pm_new(EVP_PKEY * pk,EVP_PKEY * m_pkey)682 int pkey_pm_new(EVP_PKEY *pk, EVP_PKEY *m_pkey)
683 {
684     struct pkey_pm *pkey_pm;
685 
686     pkey_pm = ssl_mem_zalloc(sizeof(struct pkey_pm));
687     if (!pkey_pm)
688         return -1;
689 
690     pk->pkey_pm = pkey_pm;
691 
692     if (m_pkey) {
693         struct pkey_pm *m_pkey_pm = (struct pkey_pm *)m_pkey->pkey_pm;
694 
695         pkey_pm->ex_pkey = m_pkey_pm->pkey;
696     }
697 
698     return 0;
699 }
700 
pkey_pm_free(EVP_PKEY * pk)701 void pkey_pm_free(EVP_PKEY *pk)
702 {
703     struct pkey_pm *pkey_pm = (struct pkey_pm *)pk->pkey_pm;
704 
705     if (pkey_pm->pkey) {
706         mbedtls_pk_free(pkey_pm->pkey);
707 
708         ssl_mem_free(pkey_pm->pkey);
709         pkey_pm->pkey = NULL;
710     }
711 
712     ssl_mem_free(pk->pkey_pm);
713     pk->pkey_pm = NULL;
714 }
715 
pkey_pm_load(EVP_PKEY * pk,const unsigned char * buffer,int len)716 int pkey_pm_load(EVP_PKEY *pk, const unsigned char *buffer, int len)
717 {
718     int ret;
719     unsigned char *load_buf;
720     struct pkey_pm *pkey_pm = (struct pkey_pm *)pk->pkey_pm;
721 
722     if (pkey_pm->pkey)
723         mbedtls_pk_free(pkey_pm->pkey);
724 
725     if (!pkey_pm->pkey) {
726         pkey_pm->pkey = ssl_mem_malloc(sizeof(mbedtls_pk_context));
727         if (!pkey_pm->pkey) {
728             SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "no enough memory > (pkey_pm->pkey)");
729             goto no_mem;
730         }
731     }
732 
733     load_buf = ssl_mem_malloc(len + 1);
734     if (!load_buf) {
735         SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "no enough memory > (load_buf)");
736         goto failed;
737     }
738 
739     ssl_memcpy(load_buf, buffer, len);
740     load_buf[len] = '\0';
741 
742     mbedtls_pk_init(pkey_pm->pkey);
743 
744     ret = mbedtls_pk_parse_key(pkey_pm->pkey, load_buf, len + 1, NULL, 0);
745     ssl_mem_free(load_buf);
746 
747     if (ret) {
748         SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "mbedtls_pk_parse_key return -0x%x", -ret);
749         goto failed;
750     }
751 
752     return 0;
753 
754 failed:
755     mbedtls_pk_free(pkey_pm->pkey);
756     ssl_mem_free(pkey_pm->pkey);
757     pkey_pm->pkey = NULL;
758 no_mem:
759     return -1;
760 }
761 
762 
763 
ssl_pm_set_bufflen(SSL * ssl,int len)764 void ssl_pm_set_bufflen(SSL *ssl, int len)
765 {
766     max_content_len = len;
767 }
768 
ssl_pm_get_verify_result(const SSL * ssl)769 long ssl_pm_get_verify_result(const SSL *ssl)
770 {
771 	uint32_t ret;
772 	long verify_result;
773 	struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;
774 
775 	ret = mbedtls_ssl_get_verify_result(&ssl_pm->ssl);
776 	if (!ret)
777 		return X509_V_OK;
778 
779 	if (ret & MBEDTLS_X509_BADCERT_NOT_TRUSTED ||
780 		(ret & MBEDTLS_X509_BADCRL_NOT_TRUSTED))
781 		verify_result = X509_V_ERR_INVALID_CA;
782 
783 	else if (ret & MBEDTLS_X509_BADCERT_CN_MISMATCH)
784 		verify_result = X509_V_ERR_HOSTNAME_MISMATCH;
785 
786 	else if ((ret & MBEDTLS_X509_BADCERT_BAD_KEY) ||
787 		(ret & MBEDTLS_X509_BADCRL_BAD_KEY))
788 		verify_result = X509_V_ERR_CA_KEY_TOO_SMALL;
789 
790 	else if ((ret & MBEDTLS_X509_BADCERT_BAD_MD) ||
791 		(ret & MBEDTLS_X509_BADCRL_BAD_MD))
792 		verify_result = X509_V_ERR_CA_MD_TOO_WEAK;
793 
794 	else if ((ret & MBEDTLS_X509_BADCERT_FUTURE) ||
795 		(ret & MBEDTLS_X509_BADCRL_FUTURE))
796 		verify_result = X509_V_ERR_CERT_NOT_YET_VALID;
797 
798 	else if ((ret & MBEDTLS_X509_BADCERT_EXPIRED) ||
799 		(ret & MBEDTLS_X509_BADCRL_EXPIRED))
800 		verify_result = X509_V_ERR_CERT_HAS_EXPIRED;
801 
802 	else
803 		verify_result = X509_V_ERR_UNSPECIFIED;
804 
805 	SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL,
806 		  "mbedtls_ssl_get_verify_result() return 0x%x", ret);
807 
808 	return verify_result;
809 }
810 
811 /**
812  * @brief set expected hostname on peer cert CN
813  */
814 
X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM * param,const char * name,size_t namelen)815 int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param,
816                                 const char *name, size_t namelen)
817 {
818 	SSL *ssl = (SSL *)((char *)param - offsetof(SSL, param));
819 	struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;
820 	char *name_cstr = NULL;
821 
822 	if (namelen) {
823 		name_cstr = malloc(namelen + 1);
824 		if (!name_cstr)
825 			return 0;
826 		memcpy(name_cstr, name, namelen);
827 		name_cstr[namelen] = '\0';
828 		name = name_cstr;
829 	}
830 
831 	mbedtls_ssl_set_hostname(&ssl_pm->ssl, name);
832 
833 	if (namelen)
834 		free(name_cstr);
835 
836 	return 1;
837 }
838 
_ssl_set_alpn_list(const SSL * ssl)839 void _ssl_set_alpn_list(const SSL *ssl)
840 {
841 #if defined(LWS_HAVE_mbedtls_ssl_conf_alpn_protocols)
842 	if (ssl->alpn_protos) {
843 		if (mbedtls_ssl_conf_alpn_protocols(&((struct ssl_pm *)(ssl->ssl_pm))->conf, ssl->alpn_protos))
844 			fprintf(stderr, "mbedtls_ssl_conf_alpn_protocols failed\n");
845 
846 		return;
847 	}
848 	if (!ssl->ctx->alpn_protos)
849 		return;
850 	if (mbedtls_ssl_conf_alpn_protocols(&((struct ssl_pm *)(ssl->ssl_pm))->conf, ssl->ctx->alpn_protos))
851 		fprintf(stderr, "mbedtls_ssl_conf_alpn_protocols failed\n");
852 #endif
853 }
854 
SSL_get0_alpn_selected(const SSL * ssl,const unsigned char ** data,unsigned int * len)855 void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
856                             unsigned int *len)
857 {
858 #if defined(LWS_HAVE_mbedtls_ssl_get_alpn_protocol)
859 	const char *alp = mbedtls_ssl_get_alpn_protocol(&((struct ssl_pm *)(ssl->ssl_pm))->ssl);
860 
861 	*data = (const unsigned char *)alp;
862 	if (alp)
863 		*len = strlen(alp);
864 	else
865 		*len = 0;
866 #endif
867 }
868 
SSL_set_sni_callback(SSL * ssl,int (* cb)(void *,mbedtls_ssl_context *,const unsigned char *,size_t),void * param)869 int SSL_set_sni_callback(SSL *ssl, int(*cb)(void *, mbedtls_ssl_context *,
870 			 const unsigned char *, size_t), void *param)
871 {
872 #if defined(LWS_HAVE_mbedtls_ssl_conf_sni)
873 	struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;
874 
875 	mbedtls_ssl_conf_sni(&ssl_pm->conf, cb, param);
876 #endif
877 	return 0;
878 }
879 
SSL_SSL_from_mbedtls_ssl_context(mbedtls_ssl_context * msc)880 SSL *SSL_SSL_from_mbedtls_ssl_context(mbedtls_ssl_context *msc)
881 {
882 	struct ssl_pm *ssl_pm = (struct ssl_pm *)((char *)msc - offsetof(struct ssl_pm, ssl));
883 
884 	return ssl_pm->owner;
885 }
886 
887 #include "ssl_cert.h"
888 
SSL_set_SSL_CTX(SSL * ssl,SSL_CTX * ctx)889 void SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx)
890 {
891 #if defined(LWS_HAVE_mbedtls_ssl_set_hs_authmode) || \
892     defined(LWS_HAVE_mbedtls_ssl_set_hs_ca_chain) || \
893     defined(LWS_HAVE_mbedtls_ssl_set_hs_own_cert)
894 	struct ssl_pm *ssl_pm = ssl->ssl_pm;
895 #endif
896 #if defined(LWS_HAVE_mbedtls_ssl_set_hs_own_cert)
897 	struct x509_pm *x509_pm;
898 #endif
899 #if defined(LWS_HAVE_mbedtls_ssl_set_hs_ca_chain)
900 	struct x509_pm *x509_pm_ca;
901 #endif
902 #if defined(LWS_HAVE_mbedtls_ssl_set_hs_own_cert)
903 	struct pkey_pm *pkey_pm;
904 #endif
905 #if defined(LWS_HAVE_mbedtls_ssl_set_hs_authmode)
906 	int mode;
907 #endif
908 
909 #if defined(LWS_HAVE_mbedtls_ssl_set_hs_own_cert)
910 	if (!ctx->cert || !ctx->cert->x509)
911 		return;
912 	x509_pm = (struct x509_pm *)ctx->cert->x509->x509_pm;
913 #endif
914 #if defined(LWS_HAVE_mbedtls_ssl_set_hs_ca_chain)
915 	if (!ctx->client_CA)
916 		return;
917 	x509_pm_ca = (struct x509_pm *)ctx->client_CA->x509_pm;
918 #endif
919 #if defined(LWS_HAVE_mbedtls_ssl_set_hs_own_cert)
920 	if (!ctx->cert || !ctx->cert->pkey)
921 		return;
922 	pkey_pm = (struct pkey_pm *)ctx->cert->pkey->pkey_pm;
923 #endif
924 
925 
926 	if (ssl->cert)
927 		ssl_cert_free(ssl->cert);
928 	ssl->ctx = ctx;
929 	ssl->cert = __ssl_cert_new(ctx->cert);
930 
931 #if defined(LWS_HAVE_mbedtls_ssl_set_hs_authmode)
932 	if (ctx->verify_mode == SSL_VERIFY_PEER)
933 		mode = MBEDTLS_SSL_VERIFY_OPTIONAL;
934 	else if (ctx->verify_mode == SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
935 		mode = MBEDTLS_SSL_VERIFY_OPTIONAL;
936 	else if (ctx->verify_mode == SSL_VERIFY_CLIENT_ONCE)
937 		mode = MBEDTLS_SSL_VERIFY_UNSET;
938 	else
939 	        mode = MBEDTLS_SSL_VERIFY_NONE;
940 #endif
941 
942 	/* apply new ctx cert to ssl */
943 
944 	ssl->verify_mode = ctx->verify_mode;
945 #if defined(LWS_HAVE_mbedtls_ssl_set_hs_ca_chain)
946 	mbedtls_ssl_set_hs_ca_chain(&ssl_pm->ssl, x509_pm_ca->x509_crt, NULL);
947 #endif
948 #if defined(LWS_HAVE_mbedtls_ssl_set_hs_own_cert)
949 	mbedtls_ssl_set_hs_own_cert(&ssl_pm->ssl, x509_pm->x509_crt, pkey_pm->pkey);
950 #endif
951 #if defined(LWS_HAVE_mbedtls_ssl_set_hs_authmode)
952 	mbedtls_ssl_set_hs_authmode(&ssl_pm->ssl, mode);
953 #endif
954 }
955