Debian Codegraph @

Xpjproject/pjlib/src/pj/ssl_sock_mbedtls.c

raw symbols SCIP
1 /*
2 * Copyright (C) 2025 Teluu Inc. (http://www.teluu.com)
3 * Copyright (c) 2025 Arlo Technologies, Inc. (https://www.arlo.com)
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19
20 #include <pj/activesock.h>
21 #include <pj/assert.h>
22 #include <pj/compat/socket.h>
23 #include <pj/errno.h>
24 #include <pj/file_io.h>
25 #include <pj/list.h>
26 #include <pj/lock.h>
27 #include <pj/log.h>
28 #include <pj/math.h>
29 #include <pj/os.h>
30 #include <pj/pool.h>
31 #include <pj/ssl_sock.h>
32 #include <pj/string.h>
33 #include <pj/timer.h>
34
35 /* Only build when PJ_HAS_SSL_SOCK is enabled and when the backend is
36 * MbedTLS.
37 */
38 #if defined(PJ_HAS_SSL_SOCK) && PJ_HAS_SSL_SOCK != 0 && \
39 (PJ_SSL_SOCK_IMP == PJ_SSL_SOCK_IMP_MBEDTLS)
40
41 #include "mbedtls/ctr_drbg.h"
42 #include "mbedtls/debug.h"
43 #include "mbedtls/entropy.h"
44 #include "mbedtls/error.h"
45 #include "mbedtls/net_sockets.h"
46 #include "mbedtls/oid.h"
47 #include "mbedtls/platform.h"
48 #include "mbedtls/pk.h"
49 #include "mbedtls/ssl.h"
50 #include "mbedtls/version.h"
51
52 #ifdef MBEDTLS_DEBUG_C
53 #define MBEDTLS_DEBUG_VERBOSE 1
54 #endif
55
56 #define SSL_SOCK_IMP_USE_CIRC_BUF
57
58 #include "ssl_sock_imp_common.h"
59
60 #define THIS_FILE "ssl_sock_mbedtls.c"
61
62 /*
63 * Secure socket structure definition.
64 */
65 typedef struct mbedtls_sock_t {
66 pj_ssl_sock_t base;
67
68 mbedtls_ssl_context ssl_ctx;
69 mbedtls_ssl_config ssl_config;
70 mbedtls_entropy_context entropy;
71 mbedtls_ctr_drbg_context ctr_drbg;
72 mbedtls_x509_crt cacert;
73 mbedtls_x509_crt cert;
74 mbedtls_pk_context pk_ctx;
75 } mbedtls_sock_t;
76
77 #include "ssl_sock_imp_common.c"
78
79 /*
80 *******************************************************************
81 * Static/internal functions.
82 *******************************************************************
83 */
84
85 /* MbedTLS way of reporting internal operations. */
86 static void mbedtls_print_logs(void *ctx, int level, const char *file,
87 int line, const char *str)
88 {
89 const char* last_slash;
90 const char* file_name;
91
92 PJ_UNUSED_ARG(ctx);
93 PJ_UNUSED_ARG(level);
94
95 last_slash = strrchr(file, '/');
96 file_name = last_slash ? last_slash + 1 : file;
97
98 PJ_LOG(3, (THIS_FILE, "%s:%d: %s", file_name, line, str));
99 }
100
101 /* Convert from MbedTLS error to pj_status_t. */
102 static pj_status_t ssl_status_from_err(pj_ssl_sock_t *ssock, int err)
103 {
104 pj_status_t status;
105
106 PJ_UNUSED_ARG(ssock);
107
108 switch (err) {
109 case 0:
110 status = PJ_SUCCESS;
111 break;
112 case MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL:
113 case MBEDTLS_ERR_SSL_ALLOC_FAILED:
114 status = PJ_ENOMEM;
115 break;
116 case MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE:
117 status = PJ_ETOOBIG;
118 break;
119 case MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE:
120 status = PJ_ENOTFOUND;
121 break;
122 case MBEDTLS_ERR_SSL_TIMEOUT:
123 status = PJ_ETIMEDOUT;
124 break;
125 case MBEDTLS_ERR_SSL_INTERNAL_ERROR:
126 case MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY:
127 status = PJ_EBUG;
128 break;
129 case MBEDTLS_ERR_SSL_WANT_READ:
130 case MBEDTLS_ERR_SSL_WANT_WRITE:
131 case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
132 case MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS:
133 case MBEDTLS_ERR_SSL_RECEIVED_EARLY_DATA:
134 case MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET:
135 status = PJ_EPENDING;
136 break;
137
138 case MBEDTLS_ERR_SSL_UNEXPECTED_RECORD:
139 case MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER:
140 case MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION:
141 case MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE:
142 status = PJ_EINVAL;
143 break;
144 default:
145 status = PJ_EUNKNOWN;
146 break;
147 }
148
149 return status;
150 }
151
152 static int ssl_data_push(void *ctx, const unsigned char *buf, size_t len)
153 {
154 pj_ssl_sock_t *ssock = (pj_ssl_sock_t *)ctx;
155
156 pj_lock_acquire(ssock->ssl_write_buf_mutex);
157 if (circ_write(&ssock->ssl_write_buf, buf, len) != PJ_SUCCESS) {
158 pj_lock_release(ssock->ssl_write_buf_mutex);
159
160 return MBEDTLS_ERR_SSL_WANT_WRITE;
161 }
162
163 pj_lock_release(ssock->ssl_write_buf_mutex);
164
165 return len;
166 }
167
168 static int ssl_data_pull(void *ctx, unsigned char *buf, size_t len)
169 {
170 pj_ssl_sock_t *ssock = (pj_ssl_sock_t *)ctx;
171 pj_size_t circ_buf_size;
172 pj_size_t read_size;
173
174 pj_lock_acquire(ssock->ssl_read_buf_mutex);
175
176 if (circ_empty(&ssock->ssl_read_buf)) {
177 pj_lock_release(ssock->ssl_read_buf_mutex);
178
179 return MBEDTLS_ERR_SSL_WANT_READ;
180 }
181
182 circ_buf_size = circ_size(&ssock->ssl_read_buf);
183 read_size = PJ_MIN(circ_buf_size, len);
184
185 circ_read(&ssock->ssl_read_buf, buf, read_size);
186 pj_lock_release(ssock->ssl_read_buf_mutex);
187
188 return read_size;
189 }
190
191 /* Get Common Name field string from a general name string */
192 static void cert_get_cn(const pj_str_t *gen_name, pj_str_t *cn)
193 {
194 pj_str_t CN_sign = {"CN=", 3};
195 char *p, *q;
196
197 pj_bzero(cn, sizeof(cn));
198
199 p = pj_strstr(gen_name, &CN_sign);
200 if (!p)
201 return;
202
203 p += 3; /* shift pointer to value part */
204 pj_strset(cn, p, gen_name->slen - (p - gen_name->ptr));
205 q = pj_strchr(cn, ',');
206 if (q)
207 cn->slen = q - p;
208 }
209
210 static void cert_get_time(pj_time_val *tv,
211 const mbedtls_x509_time *time,
212 pj_bool_t *gmt)
213 {
214 pj_parsed_time pt;
215
216 pt.day = time->day;
217 pt.mon = time->mon - 1;
218 pt.year = time->year;
219
220 pt.sec = time->sec;
221 pt.min = time->min;
222 pt.hour = time->hour;
223
224 pt.msec = 0;
225
226 // Assume MbedTLS always use GMT
227 *gmt = PJ_TRUE;
228
229 pj_time_encode(&pt, tv);
230 }
231
232 static void cert_get_alt_name(const mbedtls_x509_crt *crt,
233 pj_pool_t *pool,
234 pj_ssl_cert_info *ci)
235 {
236 const mbedtls_x509_sequence *cur;
237 size_t cnt_alt_name;
238 int ret;
239
240 int is_alt_name = mbedtls_x509_crt_has_ext_type(
241 crt, MBEDTLS_X509_EXT_SUBJECT_ALT_NAME);
242 if (!is_alt_name)
243 return;
244
245 cnt_alt_name = 0;
246 cur = &crt->subject_alt_names;
247 while (cur != NULL) {
248 cur = cur->next;
249 cnt_alt_name++;
250 }
251
252 ci->subj_alt_name.entry = pj_pool_calloc(pool, cnt_alt_name,
253 sizeof(*ci->subj_alt_name.entry));
254 if (!ci->subj_alt_name.entry) {
255 PJ_LOG(2, (THIS_FILE, "Failed to allocate memory for SubjectAltName"));
256 return;
257 }
258
259 ci->subj_alt_name.cnt = 0;
260 cur = &crt->subject_alt_names;
261
262 while (cur != NULL) {
263 mbedtls_x509_subject_alternative_name san;
264 pj_ssl_cert_name_type type;
265 size_t len;
266
267 memset(&san, 0, sizeof(san));
268 ret = mbedtls_x509_parse_subject_alt_name(&cur->buf, &san);
269 if (ret != 0) {
270 cur = cur->next;
271 continue;
272 }
273
274 len = san.san.unstructured_name.len;
275 switch (san.type) {
276 case MBEDTLS_X509_SAN_RFC822_NAME:
277 type = PJ_SSL_CERT_NAME_RFC822;
278 break;
279 case MBEDTLS_X509_SAN_DNS_NAME:
280 type = PJ_SSL_CERT_NAME_DNS;
281 break;
282 case MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER:
283 type = PJ_SSL_CERT_NAME_URI;
284 break;
285 case MBEDTLS_X509_SAN_IP_ADDRESS:
286 type = PJ_SSL_CERT_NAME_IP;
287 break;
288 default:
289 type = PJ_SSL_CERT_NAME_UNKNOWN;
290 break;
291 }
292
293 if (len && type != PJ_SSL_CERT_NAME_UNKNOWN) {
294 ci->subj_alt_name.entry[ci->subj_alt_name.cnt].type = type;
295 if (type == PJ_SSL_CERT_NAME_IP) {
296 char ip_buf[PJ_INET6_ADDRSTRLEN];
297 int af = pj_AF_INET();
298 if (len == sizeof(pj_in6_addr))
299 af = pj_AF_INET6();
300 pj_inet_ntop2(af, san.san.unstructured_name.p,
301 ip_buf, sizeof(ip_buf));
302 pj_strdup2(pool,
303 &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name,
304 ip_buf);
305 } else {
306 const pj_str_t str = {(char *)san.san.unstructured_name.p, len};
307 pj_strdup(pool,
308 &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name,
309 &str);
310 }
311 ci->subj_alt_name.cnt++;
312 }
313
314 /* So far memory is freed only in the case of directoryName
315 * parsing succeeding, as mbedtls_x509_get_name allocates memory.
316 */
317 mbedtls_x509_free_subject_alt_name(&san);
318 cur = cur->next;
319 }
320 }
321
322 static void update_cert_info(const mbedtls_x509_crt *crt,
323 pj_pool_t *pool, pj_ssl_cert_info *ci)
324 {
325 int ret;
326 char buf[1024];
327 size_t bufsize = sizeof(buf);
328
329 pj_bzero(ci, sizeof(pj_ssl_cert_info));
330
331 ci->version = crt->version;
332
333 /* Serial number */
334 pj_memcpy(ci->serial_no, crt->serial.p, sizeof(ci->serial_no));
335
336 /* Issuer */
337 ret = mbedtls_x509_dn_gets(buf, bufsize, &crt->issuer);
338 if (ret < 0) {
339 PJ_LOG(2, (THIS_FILE, "Error parsing cert issuer"));
340 return;
341 }
342 pj_strdup2(pool, &ci->issuer.info, buf);
343 cert_get_cn(&ci->issuer.info, &ci->issuer.cn);
344
345 /* Subject */
346 ret = mbedtls_x509_dn_gets(buf, bufsize, &crt->subject);
347 if (ret < 0) {
348 PJ_LOG(2, (THIS_FILE, "Error parsing cert subject"));
349 return;
350 }
351 pj_strdup2(pool, &ci->subject.info, buf);
352 cert_get_cn(&ci->subject.info, &ci->subject.cn);
353
354 /* Validity period */
355 cert_get_time(&ci->validity.start, &crt->valid_from, &ci->validity.gmt);
356 cert_get_time(&ci->validity.end, &crt->valid_to, &ci->validity.gmt);
357
358 /* Subject Alternative Name extension */
359 cert_get_alt_name(crt, pool, ci);
360 }
361
362 static pj_status_t set_ssl_protocol(pj_ssl_sock_t *ssock)
363 {
364 mbedtls_sock_t *mssock = (mbedtls_sock_t *)ssock;
365 mbedtls_ssl_protocol_version max_proto;
366 mbedtls_ssl_protocol_version min_proto;
367
368 if (ssock->param.proto == PJ_SSL_SOCK_PROTO_DEFAULT) {
369 ssock->param.proto = PJ_SSL_SOCK_PROTO_TLS1_2 |
370 PJ_SSL_SOCK_PROTO_TLS1_3;
371 }
372
373 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_3) {
374 max_proto = MBEDTLS_SSL_VERSION_TLS1_3;
375 } else if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_2) {
376 max_proto = MBEDTLS_SSL_VERSION_TLS1_2;
377 } else {
378 PJ_LOG(1, (THIS_FILE, "Unsupported TLS protocol"));
379 return PJ_EINVAL;
380 }
381
382 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_2) {
383 min_proto = MBEDTLS_SSL_VERSION_TLS1_2;
384 } else {
385 min_proto = MBEDTLS_SSL_VERSION_TLS1_3;
386 }
387
388 mbedtls_ssl_conf_min_tls_version(&mssock->ssl_config, min_proto);
389 mbedtls_ssl_conf_max_tls_version(&mssock->ssl_config, max_proto);
390
391 return PJ_SUCCESS;
392 }
393
394 static int cert_verify_cb(void *data, mbedtls_x509_crt *crt,
395 int depth, uint32_t *flags)
396 {
397 pj_ssl_sock_t *ssock = (pj_ssl_sock_t *)data;
398 const int cert_dump_log_level = 5;
399
400 if (pj_log_get_level() >= cert_dump_log_level) {
401 char buf[1024];
402 PJ_LOG(5, (THIS_FILE, "Certificate index in chain "
403 "- %d", depth));
404 mbedtls_x509_crt_info(buf, sizeof(buf) - 1, "", crt);
405 PJ_LOG(5, (THIS_FILE, "Certificate info:\n%s", buf));
406 }
407
408 /* Peer cert depth = 0 */
409 if (depth > 0)
410 return 0;
411
412 if (((*flags) & MBEDTLS_X509_BADCERT_EXPIRED) != 0) {
413 PJ_LOG(3, (THIS_FILE, "Server certificate has expired!"));
414 ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD;
415 }
416
417 if (((*flags) & MBEDTLS_X509_BADCERT_REVOKED) != 0) {
418 PJ_LOG(3, (THIS_FILE, "Server certificate has been revoked!"));
419 ssock->verify_status |= PJ_SSL_CERT_EREVOKED;
420 }
421
422 if (((*flags) & MBEDTLS_X509_BADCERT_CN_MISMATCH) != 0) {
423 PJ_LOG(3, (THIS_FILE, "CN mismatch!"));
424 ssock->verify_status |= PJ_SSL_CERT_EISSUER_MISMATCH;
425 }
426
427 if (((*flags) & MBEDTLS_X509_BADCERT_NOT_TRUSTED) != 0) {
428 PJ_LOG(3, (THIS_FILE, "Self-signed or not signed by a trusted CA!"));
429 ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED;
430 }
431
432 if (((*flags) & MBEDTLS_X509_BADCRL_NOT_TRUSTED) != 0) {
433 PJ_LOG(3, (THIS_FILE, "CRL not trusted!"));
434 ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED;
435 }
436
437 if (((*flags) & MBEDTLS_X509_BADCRL_EXPIRED) != 0) {
438 PJ_LOG(3, (THIS_FILE, "CRL expired!"));
439 ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD;
440 }
441
442 if (((*flags) & MBEDTLS_X509_BADCERT_OTHER) != 0) {
443 PJ_LOG(3, (THIS_FILE, "other (unknown) flags!"));
444 ssock->verify_status |= PJ_SSL_CERT_EUNKNOWN;
445 }
446
447 if ((*flags) == 0) {
448 PJ_LOG(5, (THIS_FILE, "Certificate verified without error flags"));
449 } else {
450 update_cert_info(crt, ssock->pool, &ssock->remote_cert_info);
451 }
452
453 return 0;
454 }
455
456 static pj_status_t set_cert(pj_ssl_sock_t *ssock)
457 {
458 mbedtls_sock_t *mssock = (mbedtls_sock_t *)ssock;
459 mbedtls_x509_crt *cacert_ = NULL;
460 int authmode = MBEDTLS_SSL_VERIFY_NONE;
461 int ret = 0;
462 pj_ssl_cert_t *cert = ssock->cert;
463
464 if (cert == NULL)
465 goto on_config;
466
467 if (cert->CA_buf.slen) {
468 ret = mbedtls_x509_crt_parse(&mssock->cacert,
469 (const unsigned char *)cert->CA_buf.ptr,
470 cert->CA_buf.slen);
471 if (ret != 0) {
472 PJ_LOG(1, (THIS_FILE, "Failed to CA mbedtls_x509_crt_parse, "
473 "ret = -0x%04X", -ret));
474 goto on_error;
475 }
476 cacert_ = &mssock->cacert;
477 }
478
479 if (cert->cert_buf.slen && cert->privkey_buf.slen) {
480 ret = mbedtls_x509_crt_parse(&mssock->cert,
481 (const unsigned char *)cert->cert_buf.ptr,
482 cert->cert_buf.slen);
483 if (ret != 0) {
484 PJ_LOG(1, (THIS_FILE, "Failed to mbedtls_x509_crt_parse, "
485 "ret = -0x%04X", -ret));
486 goto on_error;
487 }
488
489 ret = mbedtls_pk_parse_key(&mssock->pk_ctx,
490 (const unsigned char *)cert->privkey_buf.ptr,
491 cert->privkey_buf.slen,
492 (const unsigned char *)cert->privkey_pass.ptr,
493 cert->privkey_pass.slen,
494 mbedtls_ctr_drbg_random, &mssock->ctr_drbg);
495 if (ret != 0) {
496 PJ_LOG(1, (THIS_FILE, "Failed to mbedtls_pk_parse, "
497 "ret = -0x%04X", -ret));
498 goto on_error;
499 }
500
501 mbedtls_ssl_conf_own_cert(&mssock->ssl_config,
502 &mssock->cert,
503 &mssock->pk_ctx);
504 }
505
506 #if defined(MBEDTLS_FS_IO)
507 if (cert->CA_file.slen) {
508 ret = mbedtls_x509_crt_parse_file(&mssock->cacert, cert->CA_file.ptr);
509 if (ret != 0) {
510 PJ_LOG(1, (THIS_FILE, "Failed to CA mbedtls_x509_crt_parse_file, "
511 "ret = -0x%04X", -ret));
512 goto on_error;
513 }
514 cacert_ = &mssock->cacert;
515 }
516
517 if (cert->CA_path.slen) {
518 ret = mbedtls_x509_crt_parse_path(&mssock->cacert, cert->CA_path.ptr);
519 if (ret != 0) {
520 PJ_LOG(1, (THIS_FILE, "Failed to CA mbedtls_x509_crt_parse_path, "
521 "ret = -0x%04X", -ret));
522 goto on_error;
523 }
524 cacert_ = &mssock->cacert;
525 }
526
527 if (cert->cert_file.slen && cert->privkey_file.slen) {
528 ret = mbedtls_x509_crt_parse_file(&mssock->cert, cert->cert_file.ptr);
529 if (ret != 0) {
530 PJ_LOG(1, (THIS_FILE, "Failed to mbedtls_x509_crt_parse_file, "
531 "ret = -0x%04X", -ret));
532 goto on_error;
533 }
534
535 ret = mbedtls_pk_parse_keyfile(&mssock->pk_ctx,
536 cert->privkey_file.ptr,
537 cert->privkey_pass.ptr,
538 mbedtls_ctr_drbg_random,
539 &mssock->ctr_drbg);
540 if (ret != 0) {
541 PJ_LOG(1, (THIS_FILE, "Failed to mbedtls_pk_parse_keyfile, "
542 "ret = -0x%04X", -ret));
543 goto on_error;
544 }
545
546 mbedtls_ssl_conf_own_cert(&mssock->ssl_config,
547 &mssock->cert,
548 &mssock->pk_ctx);
549 }
550 #endif
551
552 on_config:
553 if (ssock->is_server) {
554 if (ssock->param.require_client_cert) {
555 authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
556 } else {
557 authmode = MBEDTLS_SSL_VERIFY_OPTIONAL;
558 }
559 } else {
560 if (cacert_)
561 authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
562 else
563 PJ_LOG(2, (THIS_FILE, "Peer validation is disabled"));
564 }
565
566 mbedtls_ssl_conf_verify(&mssock->ssl_config, cert_verify_cb, ssock);
567 mbedtls_ssl_conf_ca_chain(&mssock->ssl_config, cacert_, NULL);
568 mbedtls_ssl_conf_authmode(&mssock->ssl_config, authmode);
569
570 on_error:
571 return ssl_status_from_err(ssock, ret);
572 }
573
574 static pj_status_t set_cipher_list(pj_ssl_sock_t *ssock)
575 {
576 mbedtls_sock_t *mssock = (mbedtls_sock_t *)ssock;
577
578 /* mbedtls_ssl_conf_ciphersuites requires a 0-terminated
579 * list of supported ciphers
580 */
581 if (ssock->param.ciphers_num > 0) {
582 unsigned i;
583 int *ciphers;
584 ciphers = (int*)
585 pj_pool_calloc(ssock->pool, ssock->param.ciphers_num + 1,
586 sizeof(int));
587 if (!ciphers)
588 return PJ_ENOMEM;
589
590 for (i = 0; i < ssock->param.ciphers_num; ++i)
591 ciphers[i] = (int)ssock->param.ciphers[i];
592
593 mbedtls_ssl_conf_ciphersuites(&mssock->ssl_config, ciphers);
594 }
595
596 return PJ_SUCCESS;
597 }
598
599 /* === SSL socket implementations === */
600
601 /* Allocate SSL backend struct */
602 static pj_ssl_sock_t *ssl_alloc(pj_pool_t *pool)
603 {
604 return (pj_ssl_sock_t *)PJ_POOL_ZALLOC_T(pool, mbedtls_sock_t);
605 }
606
607 /* Create and initialize new SSL context and instance */
608 static pj_status_t ssl_create(pj_ssl_sock_t *ssock)
609 {
610 mbedtls_sock_t *mssock = (mbedtls_sock_t *)ssock;
611 const char *pers = "ssl_client";
612 pj_status_t status;
613 int ret;
614 int endpoint;
615 /* This version string is 18 bytes long, as advised by version.h. */
616 char version[18];
617
618 /* Suppress warnings */
619 PJ_UNUSED_ARG(circ_reset);
620 PJ_UNUSED_ARG(circ_read_cancel);
621 PJ_UNUSED_ARG(get_ip_addr_ver);
622
623 pj_assert(ssock);
624
625 /* Initialize input circular buffer */
626 status = circ_init(ssock->pool->factory, &ssock->ssl_read_buf, 512);
627 if (status != PJ_SUCCESS)
628 return status;
629
630 /* Initialize output circular buffer */
631 status = circ_init(ssock->pool->factory, &ssock->ssl_write_buf, 512);
632 if (status != PJ_SUCCESS) {
633 return status;
634 }
635
636 mbedtls_version_get_string_full(version);
637 PJ_LOG(4, (THIS_FILE, "Mbed TLS version : %s", version));
638
639 #ifdef MBEDTLS_PSA_CRYPTO_C
640 ret = psa_crypto_init();
641 if (ret != PSA_SUCCESS) {
642 PJ_LOG(1, (THIS_FILE, "Failed to initialize PSA Crypto, "
643 "ret = -0x%04X", ret));
644 return PJ_EUNKNOWN;
645 }
646 #endif
647
648 mbedtls_ssl_init(&mssock->ssl_ctx);
649 mbedtls_ssl_config_init(&mssock->ssl_config);
650 mbedtls_ctr_drbg_init(&mssock->ctr_drbg);
651 mbedtls_entropy_init(&mssock->entropy);
652 mbedtls_x509_crt_init(&mssock->cacert);
653 mbedtls_x509_crt_init(&mssock->cert);
654 mbedtls_pk_init(&mssock->pk_ctx);
655
656 endpoint = ssock->is_server ? MBEDTLS_SSL_IS_SERVER
657 : MBEDTLS_SSL_IS_CLIENT;
658 ret = mbedtls_ssl_config_defaults(&mssock->ssl_config, endpoint,
659 MBEDTLS_SSL_TRANSPORT_STREAM,
660 MBEDTLS_SSL_PRESET_DEFAULT);
661 if (ret != 0) {
662 PJ_LOG(1, (THIS_FILE, "Failed to mbedtls_ssl_config_defaults, "
663 "ret = -0x%04X", -ret));
664 goto out;
665 }
666
667 ret = mbedtls_ctr_drbg_seed(&mssock->ctr_drbg, mbedtls_entropy_func,
668 &mssock->entropy,
669 (const unsigned char *)pers, strlen(pers));
670 if (ret != 0) {
671 PJ_LOG(1, (THIS_FILE, "Failed to mbedtls_ctr_drbg_seed, "
672 "ret = -0x%04X", -ret));
673 goto out;
674 }
675
676 mbedtls_ssl_conf_rng(&mssock->ssl_config,
677 mbedtls_ctr_drbg_random,
678 &mssock->ctr_drbg);
679
680 status = set_ssl_protocol(ssock);
681 if (status != PJ_SUCCESS)
682 return status;
683
684 status = set_cert(ssock);
685 if (status != PJ_SUCCESS)
686 return status;
687
688 status = set_cipher_list(ssock);
689 if (status != PJ_SUCCESS)
690 return status;
691
692 #if defined(MBEDTLS_DEBUG_C)
693 mbedtls_ssl_conf_dbg(&mssock->ssl_config, mbedtls_print_logs, NULL);
694 mbedtls_debug_set_threshold(MBEDTLS_DEBUG_VERBOSE);
695 #endif
696
697 ret = mbedtls_ssl_setup(&mssock->ssl_ctx, &mssock->ssl_config);
698 if (ret != 0) {
699 PJ_LOG(1, (THIS_FILE, "Failed to mbedtls_ssl_setup, "
700 "ret = -0x%04X", -ret));
701 goto out;
702 }
703
704 if (!ssock->is_server && ssock->param.server_name.slen) {
705 ret = mbedtls_ssl_set_hostname(&mssock->ssl_ctx,
706 ssock->param.server_name.ptr);
707 if (ret != 0) {
708 PJ_LOG(1, (THIS_FILE, "Failed to mbedtls_ssl_set_hostname, "
709 "ret = -0x%04X", -ret));
710 goto out;
711 }
712 }
713
714 mbedtls_ssl_set_bio(&mssock->ssl_ctx, (void *)ssock,
715 (mbedtls_ssl_send_t *)ssl_data_push,
716 (mbedtls_ssl_recv_t *)ssl_data_pull,
717 NULL);
718
719 ssl_ciphers_populate();
720
721 ret = 0;
722
723 out:
724 return ssl_status_from_err(ssock, ret);
725 }
726
727 /* Destroy MbedTLS credentials and session. */
728 static void ssl_destroy(pj_ssl_sock_t *ssock)
729 {
730 mbedtls_sock_t *mssock = (mbedtls_sock_t *)ssock;
731
732 mbedtls_ssl_free(&mssock->ssl_ctx);
733 mbedtls_ssl_config_free(&mssock->ssl_config);
734 mbedtls_x509_crt_free(&mssock->cacert);
735 mbedtls_ctr_drbg_free(&mssock->ctr_drbg);
736 mbedtls_entropy_free(&mssock->entropy);
737 mbedtls_x509_crt_free(&mssock->cert);
738 mbedtls_pk_free(&mssock->pk_ctx);
739
740 #ifdef MBEDTLS_PSA_CRYPTO_C
741 mbedtls_psa_crypto_free();
742 #endif
743
744 /* Destroy circular buffers */
745 circ_deinit(&ssock->ssl_read_buf);
746 circ_deinit(&ssock->ssl_write_buf);
747 }
748
749 /* Reset socket state. */
750 static void ssl_reset_sock_state(pj_ssl_sock_t *ssock)
751 {
752 pj_lock_acquire(ssock->ssl_write_buf_mutex);
753 ssock->ssl_state = SSL_STATE_NULL;
754 pj_lock_release(ssock->ssl_write_buf_mutex);
755
756 ssl_close_sockets(ssock);
757 }
758
759 static void ssl_ciphers_populate()
760 {
761 const int *list;
762
763 /* Populate once only */
764 if (ssl_cipher_num) {
765 return;
766 }
767
768 list = mbedtls_ssl_list_ciphersuites();
769
770 for (unsigned num = 0;
771 ssl_cipher_num < PJ_ARRAY_SIZE(ssl_ciphers) && list[num]; num++) {
772 const mbedtls_ssl_ciphersuite_t * const ciphersuite =
773 mbedtls_ssl_ciphersuite_from_id(list[num]);
774 if (!ciphersuite)
775 continue;
776 ssl_ciphers[ssl_cipher_num].name =
777 mbedtls_ssl_ciphersuite_get_name(ciphersuite);
778 ssl_ciphers[ssl_cipher_num].id =
779 mbedtls_ssl_ciphersuite_get_id(ciphersuite);
780 ssl_cipher_num++;
781 }
782 }
783
784 static pj_ssl_cipher ssl_get_cipher(pj_ssl_sock_t *ssock)
785 {
786 mbedtls_sock_t *mssock = (mbedtls_sock_t *)ssock;
787
788 int id = mbedtls_ssl_get_ciphersuite_id_from_ssl(&mssock->ssl_ctx);
789 if (id != 0) {
790 return id;
791 } else {
792 return PJ_TLS_UNKNOWN_CIPHER;
793 }
794 }
795
796 static void ssl_update_certs_info(pj_ssl_sock_t *ssock)
797 {
798 mbedtls_sock_t *mssock = (mbedtls_sock_t *)ssock;
799 const mbedtls_x509_crt *crt;
800
801 pj_assert(ssock->ssl_state == SSL_STATE_ESTABLISHED);
802
803 /* Get active remote certificate */
804 crt = mbedtls_ssl_get_peer_cert(&mssock->ssl_ctx);
805 if (crt) {
806 update_cert_info(crt, ssock->pool, &ssock->remote_cert_info);
807 }
808 }
809
810 static void ssl_set_state(pj_ssl_sock_t *ssock, pj_bool_t is_server)
811 {
812 PJ_UNUSED_ARG(ssock);
813 PJ_UNUSED_ARG(is_server);
814 }
815
816 static void ssl_set_peer_name(pj_ssl_sock_t *ssock)
817 {
818 /* Setting server name is done in ssl_create because ssl_create can handle
819 * errors returned from Mbed TLS APIs properly.
820 */
821 PJ_UNUSED_ARG(ssock);
822 }
823
824 /* Try to perform an asynchronous handshake */
825 static pj_status_t ssl_do_handshake(pj_ssl_sock_t *ssock)
826 {
827 mbedtls_sock_t *mssock = (mbedtls_sock_t *)ssock;
828 pj_status_t handshake_status;
829 int ret;
830
831 /* Hold write_mutex to prevent concurrent session access from
832 * read and write callbacks (ioqueue may fire them in parallel).
833 */
834 pj_lock_acquire(ssock->write_mutex);
835 ret = mbedtls_ssl_handshake(&mssock->ssl_ctx);
836 pj_lock_release(ssock->write_mutex);
837 handshake_status = ssl_status_from_err(ssock, ret);
838
839 if (handshake_status == PJ_EPENDING)
840 return PJ_EPENDING;
841
842
843 if (handshake_status != PJ_SUCCESS) {
844 PJ_LOG(2, (THIS_FILE, "Failed to mbedtls_ssl_handshake, "
845 "ret -0x%04X", -ret));
846 return handshake_status;
847 }
848
849 ssock->ssl_state = SSL_STATE_ESTABLISHED;
850
851 return PJ_SUCCESS;
852 }
853
854 static pj_status_t ssl_renegotiate(pj_ssl_sock_t *ssock)
855 {
856 PJ_UNUSED_ARG(ssock);
857
858 return PJ_SUCCESS;
859 }
860
861 static pj_status_t ssl_read(pj_ssl_sock_t *ssock, void *data, int *size)
862 {
863 mbedtls_sock_t *mssock = (mbedtls_sock_t *)ssock;
864 int ret;
865
866 /* Hold write_mutex because mbedtls_ssl_read() may produce
867 * handshake data during renegotiation (same as OpenSSL's
868 * SSL_read approach).
869 */
870 pj_lock_acquire(ssock->write_mutex);
871 ret = mbedtls_ssl_read(&mssock->ssl_ctx, data, *size);
872 pj_lock_release(ssock->write_mutex);
873 if (ret >= 0) {
874 *size = ret;
875 return PJ_SUCCESS;
876 } else if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
877 *size = 0;
878 return PJ_SUCCESS;
879 } else {
880 return PJ_EUNKNOWN;
881 }
882 }
883
884 /* Caller must hold ssock->write_mutex. */
885 static pj_status_t ssl_write(pj_ssl_sock_t *ssock, const void *data,
886 pj_ssize_t size, int *nwritten)
887 {
888 mbedtls_sock_t *mssock = (mbedtls_sock_t *)ssock;
889 pj_status_t status;
890 pj_ssize_t nwritten_ = 0;
891 int ret;
892
893 while (nwritten_ < size) {
894 ret = mbedtls_ssl_write(&mssock->ssl_ctx,
895 ((const unsigned char *)data) + nwritten_,
896 size - nwritten_);
897 if (ret < 0) {
898 status = ssl_status_from_err(ssock, ret);
899
900 if (status == PJ_EPENDING)
901 continue;
902
903 *nwritten = nwritten_;
904 PJ_LOG(2, (THIS_FILE, "Failed to mbedtls_ssl_write, "
905 "ret -0x%04X", -ret));
906 return status;
907 }
908
909 nwritten_ += ret;
910 }
911
912 *nwritten = nwritten_;
913 return PJ_SUCCESS;
914 }
915
916 #endif /* PJ_HAS_SSL_SOCK */