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