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