OpenVPN
ssl_mbedtls.c
Go to the documentation of this file.
1/*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
7 *
8 * Copyright (C) 2002-2026 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2010-2026 Sentyron B.V. <openvpn@sentyron.com>
10 * Copyright (C) 2006-2010, Brainspark B.V.
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License version 2
14 * as published by the Free Software Foundation.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, see <https://www.gnu.org/licenses/>.
23 */
24
30#ifdef HAVE_CONFIG_H
31#include "config.h"
32#endif
33
34#include "syshead.h"
35
36#if defined(ENABLE_CRYPTO_MBEDTLS)
37
38#include "errlevel.h"
39#include "ssl_backend.h"
40#include "base64.h"
41#include "buffer.h"
42#include "misc.h"
43#include "manage.h"
44#include "mbedtls_compat.h"
45#include "pkcs11_backend.h"
46#include "ssl_common.h"
47#include "ssl_util.h"
48
49#include "ssl_verify_mbedtls.h"
50#include <mbedtls/debug.h>
51#include <mbedtls/error.h>
52#include <mbedtls/net_sockets.h>
53#include <mbedtls/version.h>
54
55#include <mbedtls/oid.h>
56#include <mbedtls/pem.h>
57
58static const mbedtls_x509_crt_profile openvpn_x509_crt_profile_legacy = {
59 /* Hashes from SHA-1 and above */
60 MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA1) | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_RIPEMD160)
61 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA224) | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256)
62 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512),
63 0xFFFFFFF, /* Any PK alg */
64 0xFFFFFFF, /* Any curve */
65 1024, /* RSA-1024 and larger */
66};
67
68static const mbedtls_x509_crt_profile openvpn_x509_crt_profile_preferred = {
69 /* SHA-2 and above */
70 MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA224) | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256)
71 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512),
72 0xFFFFFFF, /* Any PK alg */
73 0xFFFFFFF, /* Any curve */
74 2048, /* RSA-2048 and larger */
75};
76
77#define openvpn_x509_crt_profile_suiteb mbedtls_x509_crt_profile_suiteb;
78
79void
80tls_init_lib(void)
81{
83}
84
85void
86tls_free_lib(void)
87{
88}
89
90void
91tls_ctx_new(struct tls_root_ctx *ctx)
92{
93 ASSERT(NULL != ctx);
94 CLEAR(*ctx);
95
96#if MBEDTLS_VERSION_NUMBER < 0x04000000
97 ALLOC_OBJ_CLEAR(ctx->dhm_ctx, mbedtls_dhm_context);
98#endif
99
100 ALLOC_OBJ_CLEAR(ctx->ca_chain, mbedtls_x509_crt);
101
102 ctx->initialised = true;
103}
104
105
106void
107tls_ctx_free(struct tls_root_ctx *ctx)
108{
109 if (ctx)
110 {
111 mbedtls_pk_free(ctx->priv_key);
112 free(ctx->priv_key);
113
114 mbedtls_x509_crt_free(ctx->ca_chain);
115 free(ctx->ca_chain);
116
117 mbedtls_x509_crt_free(ctx->crt_chain);
118 free(ctx->crt_chain);
119
120#if MBEDTLS_VERSION_NUMBER < 0x04000000
121 mbedtls_dhm_free(ctx->dhm_ctx);
122 free(ctx->dhm_ctx);
123#endif
124
125 mbedtls_x509_crl_free(ctx->crl);
126 free(ctx->crl);
127
128#if defined(ENABLE_PKCS11)
129 /* ...freeCertificate() can handle NULL ptrs, but if pkcs11 helper
130 * has not been initialized, it will ASSERT() - so, do not pass NULL
131 */
132 if (ctx->pkcs11_cert)
133 {
134 pkcs11h_certificate_freeCertificate(ctx->pkcs11_cert);
135 }
136#endif
137
138 free(ctx->allowed_ciphers);
139
140 free(ctx->groups);
141
142 CLEAR(*ctx);
143
144 ctx->initialised = false;
145 }
146}
147
148bool
150{
151 /* either this should be NULL or should be non-null and then have a
152 * valid TLS ctx inside as well */
153 ASSERT(NULL == ctx || ctx->initialised);
154 return ctx != NULL;
155}
156#if !defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT)
157/*
158 * If we don't have mbedtls_ssl_export_keying_material(), we use
159 * mbedtls_ssl_set_export_keys_cb() to obtain a copy of the TLS 1.2
160 * master secret and compute the TLS-Exporter function ourselves.
161 * Unfortunately, with TLS 1.3, there is no alternative to
162 * mbedtls_ssl_export_keying_material().
163 */
164void
165mbedtls_ssl_export_keys_cb(void *p_expkey, mbedtls_ssl_key_export_type type,
166 const unsigned char *secret, size_t secret_len,
167 const unsigned char client_random[32],
168 const unsigned char server_random[32],
169 mbedtls_tls_prf_types tls_prf_type)
170{
171 /* Since we can't get the TLS 1.3 exporter master secret, we ignore all key
172 * types except MBEDTLS_SSL_KEY_EXPORT_TLS12_MASTER_SECRET. */
173 if (type != MBEDTLS_SSL_KEY_EXPORT_TLS12_MASTER_SECRET)
174 {
175 return;
176 }
177
178 struct tls_session *session = p_expkey;
179 struct key_state_ssl *ks_ssl = &session->key[KS_PRIMARY].ks_ssl;
180 struct tls_key_cache *cache = &ks_ssl->tls_key_cache;
181
182 /* The TLS 1.2 master secret has a fixed size, so if secret_len has
183 * a different value, something is wrong with mbed TLS. */
184 if (secret_len != sizeof(cache->master_secret))
185 {
186 msg(M_FATAL, "ERROR: Incorrect TLS 1.2 master secret length: Got %zu, expected %zu",
187 secret_len, sizeof(cache->master_secret));
188 }
189
190 memcpy(cache->client_server_random, client_random, 32);
191 memcpy(cache->client_server_random + 32, server_random, 32);
192 memcpy(cache->master_secret, secret, sizeof(cache->master_secret));
193 cache->tls_prf_type = tls_prf_type;
194}
195#endif /* !defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT) */
196
197
198bool
199key_state_export_keying_material(struct tls_session *session, const char *label, size_t label_size,
200 void *ekm, size_t ekm_size)
201{
202 ASSERT(strlen(label) == label_size);
203
204#if defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT)
205 /* Our version of mbed TLS has a built-in TLS-Exporter. */
206
207 mbedtls_ssl_context *ctx = session->key[KS_PRIMARY].ks_ssl.ctx;
208 if (mbed_ok(
209 mbedtls_ssl_export_keying_material(ctx, ekm, ekm_size, label, label_size, NULL, 0, 0)))
210 {
211 return true;
212 }
213 else
214 {
215 return false;
216 }
217
218#else /* defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT) */
219 struct tls_key_cache *cache = &session->key[KS_PRIMARY].ks_ssl.tls_key_cache;
220
221 /* If the type is NONE, we either have no cached secrets or
222 * there is no PRF, in both cases we cannot generate key material */
223 if (cache->tls_prf_type == MBEDTLS_SSL_TLS_PRF_NONE)
224 {
225 return false;
226 }
227
228 int ret = mbedtls_ssl_tls_prf(cache->tls_prf_type, cache->master_secret,
229 sizeof(cache->master_secret), label, cache->client_server_random,
230 sizeof(cache->client_server_random), ekm, ekm_size);
231
232 if (mbed_ok(ret))
233 {
234 return true;
235 }
236 else
237 {
238 secure_memzero(ekm, session->opt->ekm_size);
239 return false;
240 }
241#endif /* defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT) */
242}
243
244bool
245tls_ctx_set_options(struct tls_root_ctx *ctx, unsigned int ssl_flags)
246{
247 return true;
248}
249
250static const char *
251tls_translate_cipher_name(const char *cipher_name)
252{
253 const tls_cipher_name_pair *pair = tls_get_cipher_name_pair(cipher_name, strlen(cipher_name));
254
255 if (NULL == pair)
256 {
257 /* No translation found, return original */
258 return cipher_name;
259 }
260
261 if (0 != strcmp(cipher_name, pair->iana_name))
262 {
263 /* Deprecated name found, notify user */
264 msg(M_WARN, "Deprecated cipher suite name '%s', please use IANA name '%s'",
265 pair->openssl_name, pair->iana_name);
266 }
267
268 return pair->iana_name;
269}
270
271void
272tls_ctx_restrict_ciphers_tls13(struct tls_root_ctx *ctx, const char *ciphers)
273{
274 if (ciphers == NULL)
275 {
276 /* Nothing to do, return without warning message */
277 return;
278 }
279
280 msg(M_WARN,
281 "mbed TLS does not support setting tls-ciphersuites. "
282 "Ignoring TLS 1.3 cipher list: %s",
283 ciphers);
284}
285
286void
287tls_ctx_restrict_ciphers(struct tls_root_ctx *ctx, const char *ciphers)
288{
289 char *tmp_ciphers, *tmp_ciphers_orig, *token;
290
291 if (NULL == ciphers)
292 {
293 return; /* Nothing to do */
294 }
295
296 ASSERT(NULL != ctx);
297
298 /* Get number of ciphers */
299 int cipher_count = get_num_elements(ciphers, ':');
300
301 /* Allocate an array for them */
302 ALLOC_ARRAY_CLEAR(ctx->allowed_ciphers, int, cipher_count + 1)
303
304 /* Parse allowed ciphers, getting IDs */
305 int i = 0;
306 char *lasts = NULL;
307 tmp_ciphers_orig = tmp_ciphers = string_alloc(ciphers, NULL);
308
309 token = strtok_r(tmp_ciphers, ":", &lasts);
310 while (token)
311 {
312 ctx->allowed_ciphers[i] = mbedtls_ssl_get_ciphersuite_id(tls_translate_cipher_name(token));
313 if (0 != ctx->allowed_ciphers[i])
314 {
315 i++;
316 }
317 token = strtok_r(NULL, ":", &lasts);
318 }
319 free(tmp_ciphers_orig);
320}
321
322void
323tls_ctx_set_cert_profile(struct tls_root_ctx *ctx, const char *profile)
324{
325 if (!profile || 0 == strcmp(profile, "legacy") || 0 == strcmp(profile, "insecure"))
326 {
327 ctx->cert_profile = openvpn_x509_crt_profile_legacy;
328 }
329 else if (0 == strcmp(profile, "preferred"))
330 {
331 ctx->cert_profile = openvpn_x509_crt_profile_preferred;
332 }
333 else if (0 == strcmp(profile, "suiteb"))
334 {
335 ctx->cert_profile = openvpn_x509_crt_profile_suiteb;
336 }
337 else
338 {
339 msg(M_FATAL, "ERROR: Invalid cert profile: %s", profile);
340 }
341}
342
343#if MBEDTLS_VERSION_NUMBER >= 0x04000000
344static const mbedtls_ecp_curve_info ecp_curve_info_table[] = {
345/* secp curves. */
346#if defined(PSA_WANT_ECC_SECP_R1_256)
347 { "secp256r1", MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1 },
348#endif
349#if defined(PSA_WANT_ECC_SECP_R1_384)
350 { "secp384r1", MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1 },
351#endif
352#if defined(PSA_WANT_ECC_SECP_R1_521)
353 { "secp521r1", MBEDTLS_SSL_IANA_TLS_GROUP_SECP521R1 },
354#endif
355
356/* Curve25519. */
357#if defined(PSA_WANT_ECC_MONTGOMERY_255)
358 { "X25519", MBEDTLS_SSL_IANA_TLS_GROUP_X25519 },
359#endif
360
361/* Curve448. */
362#if defined(PSA_WANT_ECC_MONTGOMERY_448)
363 { "X448", MBEDTLS_SSL_IANA_TLS_GROUP_X448 },
364#endif
365
366/* Brainpool curves. */
367#if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_256)
368 { "brainpoolP256r1", MBEDTLS_SSL_IANA_TLS_GROUP_BP256R1 },
369#endif
370#if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_384)
371 { "brainpoolP384r1", MBEDTLS_SSL_IANA_TLS_GROUP_BP384R1 },
372#endif
373#if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_512)
374 { "brainpoolP512r1", MBEDTLS_SSL_IANA_TLS_GROUP_BP512R1 },
375#endif
376
377/* Named Diffie-Hellman groups. */
378#if defined(PSA_WANT_DH_RFC7919_2048)
379 { "ffdhe2048", MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE2048 },
380#endif
381#if defined(PSA_WANT_DH_RFC7919_3072)
382 { "ffdhe3072", MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE3072 },
383#endif
384#if defined(PSA_WANT_DH_RFC7919_4096)
385 { "ffdhe4096", MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE4096 },
386#endif
387#if defined(PSA_WANT_DH_RFC7919_6144)
388 { "ffdhe6144", MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE6144 },
389#endif
390#if defined(PSA_WANT_DH_RFC7919_8192)
391 { "ffdhe8192", MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE8192 },
392#endif
393};
394static const size_t ecp_curve_info_table_items = sizeof(ecp_curve_info_table) / sizeof(mbedtls_ecp_curve_info);
395
396static const mbedtls_ecp_curve_info *
397mbedtls_ecp_curve_info_from_name(const char *name)
398{
399 for (size_t i = 0; i < ecp_curve_info_table_items; i++)
400 {
401 if (strcmp(name, ecp_curve_info_table[i].name) == 0)
402 {
403 return &ecp_curve_info_table[i];
404 }
405 }
406 return NULL;
407}
408#endif /* MBEDTLS_VERSION_NUMBER >= 0x04000000 */
409
410void
411tls_ctx_set_tls_groups(struct tls_root_ctx *ctx, const char *groups)
412{
413 ASSERT(ctx);
414 struct gc_arena gc = gc_new();
415
416 /* Get number of groups and allocate an array in ctx */
417 int groups_count = get_num_elements(groups, ':');
418 ALLOC_ARRAY_CLEAR(ctx->groups, uint16_t, groups_count + 1)
419
420 /* Parse allowed ciphers, getting IDs */
421 int i = 0;
422 char *tmp_groups = string_alloc(groups, &gc);
423
424 const char *token;
425 while ((token = strsep(&tmp_groups, ":")))
426 {
427 const mbedtls_ecp_curve_info *ci = mbedtls_ecp_curve_info_from_name(token);
428 if (!ci)
429 {
430 msg(M_WARN, "Warning unknown curve/group specified: %s", token);
431 }
432 else
433 {
434 ctx->groups[i] = ci->tls_id;
435 i++;
436 }
437 }
438
439 /* Check if any groups were valid. */
440 if (i == 0)
441 {
442 msg(M_FATAL, "Error: All groups in \"%s\" are invalid or unsupported.", groups);
443 }
444
445 /* Recent mbedtls versions state that the list of groups must be terminated
446 * with 0. Older versions state that it must be terminated with MBEDTLS_ECP_DP_NONE
447 * which is also 0, so this works either way. */
448 ctx->groups[i] = 0;
449
450 gc_free(&gc);
451}
452
453
454void
455tls_ctx_check_cert_time(const struct tls_root_ctx *ctx)
456{
457 ASSERT(ctx);
458 if (ctx->crt_chain == NULL)
459 {
460 return; /* Nothing to check if there is no certificate */
461 }
462
463 if (mbedtls_x509_time_is_future(&ctx->crt_chain->valid_from))
464 {
465 msg(M_WARN, "WARNING: Your certificate is not yet valid!");
466 }
467
468 if (mbedtls_x509_time_is_past(&ctx->crt_chain->valid_to))
469 {
470 msg(M_WARN, "WARNING: Your certificate has expired!");
471 }
472}
473
474void
475tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file, bool dh_inline)
476{
477#if MBEDTLS_VERSION_NUMBER < 0x04000000
478 if (dh_inline)
479 {
480 if (!mbed_ok(mbedtls_dhm_parse_dhm(ctx->dhm_ctx, (const unsigned char *)dh_file,
481 strlen(dh_file) + 1)))
482 {
483 msg(M_FATAL, "Cannot read inline DH parameters");
484 }
485 }
486 else
487 {
488 if (!mbed_ok(mbedtls_dhm_parse_dhmfile(ctx->dhm_ctx, dh_file)))
489 {
490 msg(M_FATAL, "Cannot read DH parameters from file %s", dh_file);
491 }
492 }
493
494 msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with " counter_format " bit key",
495 (counter_type)mbedtls_dhm_get_bitlen(ctx->dhm_ctx));
496#else
497 if (strcmp(dh_file, "none") != 0)
498 {
499 msg(M_FATAL, "Mbed TLS 4 only supports pre-defined Diffie-Hellman groups.");
500 }
501#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
502}
503
504void
505tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve_name)
506{
507 if (NULL != curve_name)
508 {
509 msg(M_WARN, "WARNING: mbed TLS builds do not support specifying an "
510 "ECDH curve with --ecdh-curve, using default curves. Use "
511 "--tls-groups to specify curves.");
512 }
513}
514
515int
516tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file, bool pkcs12_file_inline,
517 bool load_ca_file)
518{
519 msg(M_FATAL, "PKCS #12 files not yet supported for mbed TLS.");
520 return 0;
521}
522
523#ifdef ENABLE_CRYPTOAPI
524void
525tls_ctx_load_cryptoapi(struct tls_root_ctx *ctx, const char *cryptoapi_cert)
526{
527 msg(M_FATAL, "Windows CryptoAPI not yet supported for mbed TLS.");
528}
529#endif /* _WIN32 */
530
531void
532tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file, bool cert_inline)
533{
534 ASSERT(NULL != ctx);
535
536 if (!ctx->crt_chain)
537 {
538 ALLOC_OBJ_CLEAR(ctx->crt_chain, mbedtls_x509_crt);
539 }
540
541 if (cert_inline)
542 {
543 if (!cert_file)
544 {
545 msg(M_FATAL, "Cannot load inline certificate: NULL");
546 }
547 if (!mbed_ok(mbedtls_x509_crt_parse(ctx->crt_chain, (const unsigned char *)cert_file,
548 strlen(cert_file) + 1)))
549 {
550 msg(M_FATAL, "Cannot load inline certificate");
551 }
552 }
553 else
554 {
555 if (!mbed_ok(mbedtls_x509_crt_parse_file(ctx->crt_chain, cert_file)))
556 {
557 msg(M_FATAL, "Cannot load certificate file %s", cert_file);
558 }
559 }
560}
561
562int
563tls_ctx_load_priv_file(struct tls_root_ctx *ctx, const char *priv_key_file, bool priv_key_inline)
564{
565 int status;
566 ASSERT(NULL != ctx);
567
568 if (!ctx->priv_key)
569 {
570 ALLOC_OBJ_CLEAR(ctx->priv_key, mbedtls_pk_context);
571 }
572
573 if (priv_key_inline)
574 {
575 status = mbedtls_compat_pk_parse_key(ctx->priv_key, (const unsigned char *)priv_key_file,
576 strlen(priv_key_file) + 1, NULL, 0);
577
578 if (MBEDTLS_ERR_PK_PASSWORD_REQUIRED == status)
579 {
580 char passbuf[512] = { 0 };
581 pem_password_callback(passbuf, 512, 0, NULL);
583 ctx->priv_key, (const unsigned char *)priv_key_file, strlen(priv_key_file) + 1,
584 (unsigned char *)passbuf, strlen(passbuf));
585 }
586 }
587 else
588 {
589 status = mbedtls_compat_pk_parse_keyfile(ctx->priv_key, priv_key_file, NULL);
590 if (MBEDTLS_ERR_PK_PASSWORD_REQUIRED == status)
591 {
592 char passbuf[512] = { 0 };
593 pem_password_callback(passbuf, 512, 0, NULL);
595 }
596 }
597 if (!mbed_ok(status))
598 {
599#ifdef ENABLE_MANAGEMENT
600 if (management && (MBEDTLS_ERR_PK_PASSWORD_MISMATCH == status))
601 {
603 }
604#endif
605 msg(M_WARN, "Cannot load private key file %s",
606 print_key_filename(priv_key_file, priv_key_inline));
607 return 1;
608 }
609
611 {
612 msg(M_WARN, "Private key does not match the certificate");
613 return 1;
614 }
615
616 return 0;
617}
618
619#if MBEDTLS_VERSION_NUMBER < 0x04000000
638static inline int
639external_pkcs1_sign(void *ctx_voidptr, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
640 mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash,
641 unsigned char *sig)
642{
643 struct external_context *const ctx = ctx_voidptr;
644 int rv;
645 size_t asn_len = 0, oid_size = 0;
646 const char *oid = NULL;
647
648 if (NULL == ctx)
649 {
650 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
651 }
652
653 /*
654 * Support a wide range of hashes. TLSv1.1 and before only need SIG_RSA_RAW,
655 * but TLSv1.2 needs the full suite of hashes.
656 *
657 * This code has been taken from mbed TLS pkcs11_sign(), under the GPLv2.0+.
658 */
659 if (md_alg != MBEDTLS_MD_NONE)
660 {
661 const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_alg);
662 if (md_info == NULL)
663 {
664 return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA);
665 }
666
667 if (!mbed_ok(mbedtls_oid_get_oid_by_md(md_alg, &oid, &oid_size)))
668 {
669 return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA);
670 }
671
672 hashlen = mbedtls_md_get_size(md_info);
673 asn_len = 10 + oid_size;
674 }
675
676 if (ctx->signature_length < (asn_len + hashlen)
677 || (asn_len + hashlen) > UINT8_MAX)
678 {
679 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
680 }
681
682 uint8_t *to_sign = NULL;
683 ALLOC_ARRAY_CLEAR(to_sign, uint8_t, asn_len + hashlen);
684 uint8_t *p = to_sign;
685 if (md_alg != MBEDTLS_MD_NONE)
686 {
687 /*
688 * DigestInfo ::= SEQUENCE {
689 * digestAlgorithm DigestAlgorithmIdentifier,
690 * digest Digest }
691 *
692 * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
693 *
694 * Digest ::= OCTET STRING
695 */
696 *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
697 *p++ = (uint8_t)(0x08 + oid_size + hashlen);
698 *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
699 *p++ = (uint8_t)(0x04 + oid_size);
700 *p++ = MBEDTLS_ASN1_OID;
701 *p++ = (uint8_t)oid_size;
702 memcpy(p, oid, oid_size);
703 p += oid_size;
704 *p++ = MBEDTLS_ASN1_NULL;
705 *p++ = 0x00;
706 *p++ = MBEDTLS_ASN1_OCTET_STRING;
707 *p++ = (uint8_t)hashlen;
708
709 /* Double-check ASN length */
710 ASSERT(asn_len == (uintptr_t)(p - to_sign));
711 }
712
713 /* Copy the hash to be signed */
714 memcpy(p, hash, hashlen);
715
716 /* Call external signature function */
717 if (!ctx->sign(ctx->sign_ctx, to_sign, asn_len + hashlen, sig, ctx->signature_length))
718 {
719 rv = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
720 goto done;
721 }
722
723 rv = 0;
724
725done:
726 free(to_sign);
727 return rv;
728}
729
730static inline size_t
731external_key_len(void *vctx)
732{
733 struct external_context *const ctx = vctx;
734
735 return ctx->signature_length;
736}
737#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
738
739int
741 void *sign_ctx)
742{
743#if MBEDTLS_VERSION_NUMBER >= 0x04000000
744 msg(M_WARN, "tls_ctx_use_external_signing_func is not implemented for Mbed TLS 4.");
745 return 1;
746#else
747 ASSERT(NULL != ctx);
748
749 if (ctx->crt_chain == NULL)
750 {
751 msg(M_WARN, "ERROR: external key requires a certificate.");
752 return 1;
753 }
754
755 if (mbedtls_pk_get_type(&ctx->crt_chain->pk) != MBEDTLS_PK_RSA)
756 {
757 msg(M_WARN, "ERROR: external key with mbed TLS requires a "
758 "certificate with an RSA key.");
759 return 1;
760 }
761
762 ctx->external_key.signature_length = mbedtls_pk_get_len(&ctx->crt_chain->pk);
763 ctx->external_key.sign = sign_func;
765
766 ALLOC_OBJ_CLEAR(ctx->priv_key, mbedtls_pk_context);
767 if (!mbed_ok(mbedtls_pk_setup_rsa_alt(ctx->priv_key, &ctx->external_key, NULL,
768 external_pkcs1_sign, external_key_len)))
769 {
770 return 1;
771 }
772
773 return 0;
774#endif /* MBEDTLS_VERSION_NUMBER >= 0x04000000 */
775}
776
777#ifdef ENABLE_MANAGEMENT
779static bool
780management_sign_func(void *sign_ctx, const void *src, size_t src_len, void *dst, size_t dst_len)
781{
782 bool ret = false;
783 char *src_b64 = NULL;
784 char *dst_b64 = NULL;
785
786 if (!management || (openvpn_base64_encode(src, (int)src_len, &src_b64) <= 0))
787 {
788 goto cleanup;
789 }
790
791 /*
792 * We only support RSA external keys and PKCS1 signatures at the moment
793 * in mbed TLS, so the signature parameter is hardcoded to this encoding
794 */
795 if (!(dst_b64 = management_query_pk_sig(management, src_b64, "RSA_PKCS1_PADDING")))
796 {
797 goto cleanup;
798 }
799
800 if (openvpn_base64_decode(dst_b64, dst, (int)dst_len) != (int)dst_len)
801 {
802 goto cleanup;
803 }
804
805 ret = true;
806cleanup:
807 free(src_b64);
808 free(dst_b64);
809
810 return ret;
811}
812
813int
815{
816 return tls_ctx_use_external_signing_func(ctx, management_sign_func, NULL);
817}
818
819#endif /* ifdef ENABLE_MANAGEMENT */
820
821void
822tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file, bool ca_inline, const char *ca_path,
823 bool tls_server)
824{
825 if (ca_path)
826 {
827 msg(M_FATAL, "ERROR: mbed TLS cannot handle the capath directive");
828 }
829
830 if (ca_file && ca_inline)
831 {
832 if (!mbed_ok(mbedtls_x509_crt_parse(ctx->ca_chain, (const unsigned char *)ca_file,
833 strlen(ca_file) + 1)))
834 {
835 msg(M_FATAL, "Cannot load inline CA certificates");
836 }
837 }
838 else
839 {
840 /* Load CA file for verifying peer supplied certificate */
841 if (!mbed_ok(mbedtls_x509_crt_parse_file(ctx->ca_chain, ca_file)))
842 {
843 msg(M_FATAL, "Cannot load CA certificate file %s", ca_file);
844 }
845 }
846}
847
848void
849tls_ctx_load_extra_certs(struct tls_root_ctx *ctx, const char *extra_certs_file,
850 bool extra_certs_inline)
851{
852 ASSERT(NULL != ctx);
853
854 if (!ctx->crt_chain)
855 {
856 ALLOC_OBJ_CLEAR(ctx->crt_chain, mbedtls_x509_crt);
857 }
858
859 if (extra_certs_inline)
860 {
861 if (!mbed_ok(mbedtls_x509_crt_parse(ctx->crt_chain, (const unsigned char *)extra_certs_file,
862 strlen(extra_certs_file) + 1)))
863 {
864 msg(M_FATAL, "Cannot load inline extra-certs file");
865 }
866 }
867 else
868 {
869 if (!mbed_ok(mbedtls_x509_crt_parse_file(ctx->crt_chain, extra_certs_file)))
870 {
871 msg(M_FATAL, "Cannot load extra-certs file: %s", extra_certs_file);
872 }
873 }
874}
875
876/* **************************************
877 *
878 * Key-state specific functions
879 *
880 ***************************************/
881
882/*
883 * "Endless buffer"
884 */
885
886static inline void
887buf_free_entry(buffer_entry *entry)
888{
889 if (NULL != entry)
890 {
891 free(entry->data);
892 free(entry);
893 }
894}
895
896static void
897buf_free_entries(endless_buffer *buf)
898{
899 while (buf->first_block)
900 {
901 buffer_entry *cur_block = buf->first_block;
902 buf->first_block = cur_block->next_block;
903 buf_free_entry(cur_block);
904 }
905 buf->last_block = NULL;
906}
907
908static int
909endless_buf_read(endless_buffer *in, unsigned char *out, size_t out_len)
910{
911 size_t read_len = 0;
912
913 ASSERT(out_len <= INT_MAX);
914
915 if (in->first_block == NULL)
916 {
917 return MBEDTLS_ERR_SSL_WANT_READ;
918 }
919
920 while (in->first_block != NULL && read_len < out_len)
921 {
922 size_t block_len = in->first_block->length - in->data_start;
923 if (block_len <= out_len - read_len)
924 {
925 buffer_entry *cur_entry = in->first_block;
926 memcpy(out + read_len, cur_entry->data + in->data_start, block_len);
927
928 read_len += block_len;
929
930 in->first_block = cur_entry->next_block;
931 in->data_start = 0;
932
933 if (in->first_block == NULL)
934 {
935 in->last_block = NULL;
936 }
937
938 buf_free_entry(cur_entry);
939 }
940 else
941 {
942 memcpy(out + read_len, in->first_block->data + in->data_start, out_len - read_len);
943 in->data_start += out_len - read_len;
944 read_len = out_len;
945 }
946 }
947
948 return (int)read_len;
949}
950
951static int
952endless_buf_write(endless_buffer *out, const unsigned char *in, size_t len)
953{
954 buffer_entry *new_block = malloc(sizeof(buffer_entry));
955 if (NULL == new_block)
956 {
957 return MBEDTLS_ERR_NET_SEND_FAILED;
958 }
959
960 new_block->data = malloc(len);
961 if (NULL == new_block->data)
962 {
963 free(new_block);
964 return MBEDTLS_ERR_NET_SEND_FAILED;
965 }
966
967 ASSERT(len <= INT_MAX);
968
969 new_block->length = len;
970 new_block->next_block = NULL;
971
972 memcpy(new_block->data, in, len);
973
974 if (NULL == out->first_block)
975 {
976 out->first_block = new_block;
977 }
978
979 if (NULL != out->last_block)
980 {
981 out->last_block->next_block = new_block;
982 }
983
984 out->last_block = new_block;
985
986 return (int)len;
987}
988
989static int
990ssl_bio_read(void *ctx, unsigned char *out, size_t out_len)
991{
992 bio_ctx *my_ctx = (bio_ctx *)ctx;
993 return endless_buf_read(&my_ctx->in, out, out_len);
994}
995
996static int
997ssl_bio_write(void *ctx, const unsigned char *in, size_t in_len)
998{
999 bio_ctx *my_ctx = (bio_ctx *)ctx;
1000 return endless_buf_write(&my_ctx->out, in, in_len);
1001}
1002
1003static void
1004my_debug(void *ctx, int level, const char *file, int line, const char *str)
1005{
1006 msglvl_t my_loglevel = (level < 3) ? D_TLS_DEBUG_MED : D_TLS_DEBUG;
1007 msg(my_loglevel, "mbed TLS msg (%s:%d): %s", file, line, str);
1008}
1009
1010/*
1011 * Further personalise the RNG using a hash of the public key
1012 */
1013void
1014tls_ctx_personalise_random(struct tls_root_ctx *ctx)
1015{
1016#if MBEDTLS_VERSION_NUMBER < 0x04000000
1017 static char old_sha256_hash[32] = { 0 };
1018 unsigned char sha256_hash[32] = { 0 };
1019 mbedtls_ctr_drbg_context *cd_ctx = rand_ctx_get();
1020
1021 if (NULL != ctx->crt_chain)
1022 {
1023 mbedtls_x509_crt *cert = ctx->crt_chain;
1024 const mbedtls_md_info_t *kt = md_get("SHA256");
1025
1026 if (0 != mbedtls_md(kt, cert->tbs.p, cert->tbs.len, sha256_hash))
1027 {
1028 msg(M_WARN, "WARNING: failed to personalise random");
1029 }
1030
1031 if (0 != memcmp(old_sha256_hash, sha256_hash, sizeof(sha256_hash)))
1032 {
1033 if (!mbed_ok(mbedtls_ctr_drbg_update(cd_ctx, sha256_hash, 32)))
1034 {
1035 msg(M_WARN, "WARNING: failed to personalise random, could not update CTR_DRBG");
1036 }
1037 memcpy(old_sha256_hash, sha256_hash, sizeof(old_sha256_hash));
1038 }
1039 }
1040#endif /* MBEDTLS_VERSION_NUMBER < 0x040000 */
1041}
1042
1043int
1044tls_version_max(void)
1045{
1046 /* We need mbedtls_ssl_export_keying_material() to support TLS 1.3. */
1047#if defined(MBEDTLS_SSL_PROTO_TLS1_3) && defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT)
1048 return TLS_VER_1_3;
1049#elif defined(MBEDTLS_SSL_PROTO_TLS1_2)
1050 return TLS_VER_1_2;
1051#else
1052#error mbedtls is compiled without support for TLS 1.2 or 1.3
1053#endif
1054}
1055
1063mbedtls_ssl_protocol_version
1064tls_version_to_ssl_version(int tls_ver)
1065{
1066 switch (tls_ver)
1067 {
1068#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1069 case TLS_VER_1_2:
1070 return MBEDTLS_SSL_VERSION_TLS1_2;
1071#endif
1072
1073#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1074 case TLS_VER_1_3:
1075 return MBEDTLS_SSL_VERSION_TLS1_3;
1076#endif
1077
1078 default:
1079 msg(M_FATAL, "%s: invalid or unsupported TLS version %d", __func__, tls_ver);
1080 return MBEDTLS_SSL_VERSION_UNKNOWN;
1081 }
1082}
1083
1084void
1085backend_tls_ctx_reload_crl(struct tls_root_ctx *ctx, const char *crl_file, bool crl_inline)
1086{
1087 ASSERT(crl_file);
1088
1089 if (ctx->crl == NULL)
1090 {
1091 ALLOC_OBJ_CLEAR(ctx->crl, mbedtls_x509_crl);
1092 }
1093 mbedtls_x509_crl_free(ctx->crl);
1094
1095 if (crl_inline)
1096 {
1097 if (!mbed_ok(mbedtls_x509_crl_parse(ctx->crl, (const unsigned char *)crl_file,
1098 strlen(crl_file) + 1)))
1099 {
1100 msg(M_WARN, "CRL: cannot parse inline CRL");
1101 goto err;
1102 }
1103 }
1104 else
1105 {
1106 if (!mbed_ok(mbedtls_x509_crl_parse_file(ctx->crl, crl_file)))
1107 {
1108 msg(M_WARN, "CRL: cannot read CRL from file %s", crl_file);
1109 goto err;
1110 }
1111 }
1112 return;
1113
1114err:
1115 mbedtls_x509_crl_free(ctx->crl);
1116}
1117
1118void
1119key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_ctx *ssl_ctx, bool is_server,
1120 struct tls_session *session)
1121{
1122 ASSERT(NULL != ssl_ctx);
1123 ASSERT(ks_ssl);
1124 CLEAR(*ks_ssl);
1125
1126 /* Initialise SSL config */
1127 ALLOC_OBJ_CLEAR(ks_ssl->ssl_config, mbedtls_ssl_config);
1128 mbedtls_ssl_config_init(ks_ssl->ssl_config);
1129 int endpoint = is_server ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT;
1130 mbedtls_ssl_config_defaults(ks_ssl->ssl_config, endpoint, MBEDTLS_SSL_TRANSPORT_STREAM,
1131 MBEDTLS_SSL_PRESET_DEFAULT);
1132#ifdef MBEDTLS_DEBUG_C
1133 /* We only want to have mbed TLS generate debug level logging when we would
1134 * also display it.
1135 * In fact mbed TLS 2.25.0 crashes generating debug log if Curve25591 is
1136 * selected for DH (https://github.com/ARMmbed/mbedtls/issues/4208) */
1137 if (session->opt->ssl_flags & SSLF_TLS_DEBUG_ENABLED)
1138 {
1139 mbedtls_debug_set_threshold(3);
1140 }
1141 else
1142 {
1143 mbedtls_debug_set_threshold(2);
1144 }
1145#endif
1146 mbedtls_ssl_conf_dbg(ks_ssl->ssl_config, my_debug, NULL);
1147#if MBEDTLS_VERSION_NUMBER < 0x04000000
1148 mbedtls_ssl_conf_rng(ks_ssl->ssl_config, mbedtls_ctr_drbg_random, rand_ctx_get());
1149#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
1150
1151 mbedtls_ssl_conf_cert_profile(ks_ssl->ssl_config, &ssl_ctx->cert_profile);
1152
1153 if (ssl_ctx->allowed_ciphers)
1154 {
1155 mbedtls_ssl_conf_ciphersuites(ks_ssl->ssl_config, ssl_ctx->allowed_ciphers);
1156 }
1157
1158 if (ssl_ctx->groups)
1159 {
1160 mbedtls_ssl_conf_groups(ks_ssl->ssl_config, ssl_ctx->groups);
1161 }
1162
1163 /* Disable TLS renegotiations if the mbedtls library supports that feature.
1164 * OpenVPN's renegotiation creates new SSL sessions and does not depend on
1165 * this feature and TLS renegotiations have been problematic in the past. */
1166#if defined(MBEDTLS_SSL_RENEGOTIATION)
1167 mbedtls_ssl_conf_renegotiation(ks_ssl->ssl_config, MBEDTLS_SSL_RENEGOTIATION_DISABLED);
1168#endif /* MBEDTLS_SSL_RENEGOTIATION */
1169
1170 /* Disable record splitting (for now). OpenVPN assumes records are sent
1171 * unfragmented, and changing that will require thorough review and
1172 * testing. Since OpenVPN is not susceptible to BEAST, we can just
1173 * disable record splitting as a quick fix. */
1174#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
1175 mbedtls_ssl_conf_cbc_record_splitting(ks_ssl->ssl_config,
1176 MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED);
1177#endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
1178
1179 /* Initialise authentication information */
1180#if MBEDTLS_VERSION_NUMBER < 0x04000000
1181 if (is_server)
1182 {
1183 mbed_ok(mbedtls_ssl_conf_dh_param_ctx(ks_ssl->ssl_config, ssl_ctx->dhm_ctx));
1184 }
1185#endif
1186
1187 (void)mbed_ok(mbedtls_ssl_conf_own_cert(ks_ssl->ssl_config, ssl_ctx->crt_chain, ssl_ctx->priv_key));
1188
1189 /* Initialise SSL verification */
1190 if (session->opt->ssl_flags & SSLF_CLIENT_CERT_OPTIONAL)
1191 {
1192 mbedtls_ssl_conf_authmode(ks_ssl->ssl_config, MBEDTLS_SSL_VERIFY_OPTIONAL);
1193 }
1194 else if (!(session->opt->ssl_flags & SSLF_CLIENT_CERT_NOT_REQUIRED))
1195 {
1196 mbedtls_ssl_conf_authmode(ks_ssl->ssl_config, MBEDTLS_SSL_VERIFY_REQUIRED);
1197 }
1198 mbedtls_ssl_conf_verify(ks_ssl->ssl_config, verify_callback, session);
1199
1200 /* TODO: mbed TLS does not currently support sending the CA chain to the client */
1201 mbedtls_ssl_conf_ca_chain(ks_ssl->ssl_config, ssl_ctx->ca_chain, ssl_ctx->crl);
1202
1203 /* Initialize minimum TLS version */
1204 {
1205 const int configured_tls_version_min =
1207
1208 /* default to TLS 1.2 */
1209 mbedtls_ssl_protocol_version version = MBEDTLS_SSL_VERSION_TLS1_2;
1210
1211 if (configured_tls_version_min > TLS_VER_UNSPEC)
1212 {
1213 version = tls_version_to_ssl_version(configured_tls_version_min);
1214 }
1215
1216 mbedtls_ssl_conf_min_tls_version(ks_ssl->ssl_config, version);
1217 }
1218
1219 /* Initialize maximum TLS version */
1220 {
1221 const int configured_tls_version_max =
1223
1224 mbedtls_ssl_protocol_version version = MBEDTLS_SSL_VERSION_UNKNOWN;
1225
1226 if (configured_tls_version_max > TLS_VER_UNSPEC)
1227 {
1228 version = tls_version_to_ssl_version(configured_tls_version_max);
1229 }
1230 else
1231 {
1232 /* Default to tls_version_max(). */
1233 version = tls_version_to_ssl_version(tls_version_max());
1234 }
1235
1236 mbedtls_ssl_conf_max_tls_version(ks_ssl->ssl_config, version);
1237 }
1238
1239 /* Initialise SSL context */
1240 ALLOC_OBJ_CLEAR(ks_ssl->ctx, mbedtls_ssl_context);
1241 mbedtls_ssl_init(ks_ssl->ctx);
1242 (void)mbed_ok(mbedtls_ssl_setup(ks_ssl->ctx, ks_ssl->ssl_config));
1243 /* We do verification in our own callback depending on the
1244 * exact configuration. We do not rely on the default hostname
1245 * verification. */
1246 ASSERT(mbed_ok(mbedtls_ssl_set_hostname(ks_ssl->ctx, NULL)));
1247
1248#if !defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT)
1249 /* Initialize the keying material exporter callback. */
1250 mbedtls_ssl_set_export_keys_cb(ks_ssl->ctx, mbedtls_ssl_export_keys_cb, session);
1251#endif
1252
1253 /* Initialise BIOs */
1255 mbedtls_ssl_set_bio(ks_ssl->ctx, ks_ssl->bio_ctx, ssl_bio_write, ssl_bio_read, NULL);
1256}
1257
1258
1259void
1261{
1262 mbedtls_ssl_send_alert_message(ks_ssl->ctx, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1263 MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY);
1264}
1265
1266void
1267key_state_ssl_free(struct key_state_ssl *ks_ssl)
1268{
1269 if (ks_ssl)
1270 {
1271 CLEAR(ks_ssl->tls_key_cache);
1272
1273 if (ks_ssl->ctx)
1274 {
1275 mbedtls_ssl_free(ks_ssl->ctx);
1276 free(ks_ssl->ctx);
1277 }
1278 if (ks_ssl->ssl_config)
1279 {
1280 mbedtls_ssl_config_free(ks_ssl->ssl_config);
1281 free(ks_ssl->ssl_config);
1282 }
1283 if (ks_ssl->bio_ctx)
1284 {
1285 buf_free_entries(&ks_ssl->bio_ctx->in);
1286 buf_free_entries(&ks_ssl->bio_ctx->out);
1287 free(ks_ssl->bio_ctx);
1288 }
1289 CLEAR(*ks_ssl);
1290 }
1291}
1292
1293int
1294key_state_write_plaintext(struct key_state_ssl *ks, struct buffer *buf)
1295{
1296 int retval = 0;
1297
1298 ASSERT(buf);
1299
1300 retval = key_state_write_plaintext_const(ks, BPTR(buf), BLEN(buf));
1301
1302 if (1 == retval)
1303 {
1304 memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */
1305 buf->len = 0;
1306 }
1307
1308 return retval;
1309}
1310
1311int
1312key_state_write_plaintext_const(struct key_state_ssl *ks, const uint8_t *data, int len)
1313{
1314 int retval = 0;
1315
1316 ASSERT(NULL != ks);
1317 ASSERT(len >= 0);
1318
1319 if (0 == len)
1320 {
1321 return 0;
1322 }
1323
1324 ASSERT(data);
1325
1326 retval = mbedtls_ssl_write(ks->ctx, data, len);
1327
1328 if (retval < 0)
1329 {
1330 if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval)
1331 {
1332 return 0;
1333 }
1334 mbed_log_err(D_TLS_ERRORS, retval, "TLS ERROR: write tls_write_plaintext_const error");
1335 return -1;
1336 }
1337
1338 if (retval != len)
1339 {
1340 msg(D_TLS_ERRORS, "TLS ERROR: write tls_write_plaintext_const incomplete %d/%d", retval,
1341 len);
1342 return -1;
1343 }
1344
1345 /* successful write */
1346 dmsg(D_HANDSHAKE_VERBOSE, "write tls_write_plaintext_const %d bytes", retval);
1347
1348 return 1;
1349}
1350
1351int
1352key_state_read_ciphertext(struct key_state_ssl *ks, struct buffer *buf)
1353{
1354 int retval = 0;
1355 int len = 0;
1356
1357 ASSERT(NULL != ks);
1358 ASSERT(buf);
1359 ASSERT(buf->len >= 0);
1360
1361 if (buf->len)
1362 {
1363 return 0;
1364 }
1365
1366 len = buf_forward_capacity(buf);
1367
1368 retval = endless_buf_read(&ks->bio_ctx->out, BPTR(buf), len);
1369
1370 /* Error during read, check for retry error */
1371 if (retval < 0)
1372 {
1373 if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval)
1374 {
1375 return 0;
1376 }
1377 mbed_log_err(D_TLS_ERRORS, retval, "TLS_ERROR: read tls_read_ciphertext error");
1378 buf->len = 0;
1379 return -1;
1380 }
1381 /* Nothing read, try again */
1382 if (0 == retval)
1383 {
1384 buf->len = 0;
1385 return 0;
1386 }
1387
1388 /* successful read */
1389 dmsg(D_HANDSHAKE_VERBOSE, "read tls_read_ciphertext %d bytes", retval);
1390 buf->len = retval;
1391 return 1;
1392}
1393
1394int
1395key_state_write_ciphertext(struct key_state_ssl *ks, struct buffer *buf)
1396{
1397 int retval = 0;
1398
1399 ASSERT(NULL != ks);
1400 ASSERT(buf);
1401 ASSERT(buf->len >= 0);
1402
1403 if (0 == buf->len)
1404 {
1405 return 0;
1406 }
1407
1408 retval = endless_buf_write(&ks->bio_ctx->in, BPTR(buf), buf->len);
1409
1410 if (retval < 0)
1411 {
1412 if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval)
1413 {
1414 return 0;
1415 }
1416 mbed_log_err(D_TLS_ERRORS, retval, "TLS ERROR: write tls_write_ciphertext error");
1417 return -1;
1418 }
1419
1420 if (retval != buf->len)
1421 {
1422 msg(D_TLS_ERRORS, "TLS ERROR: write tls_write_ciphertext incomplete %d/%d", retval,
1423 buf->len);
1424 return -1;
1425 }
1426
1427 /* successful write */
1428 dmsg(D_HANDSHAKE_VERBOSE, "write tls_write_ciphertext %d bytes", retval);
1429
1430 memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */
1431 buf->len = 0;
1432
1433 return 1;
1434}
1435
1436int
1437key_state_read_plaintext(struct key_state_ssl *ks, struct buffer *buf)
1438{
1439 int retval = 0;
1440 int len = 0;
1441
1442 ASSERT(NULL != ks);
1443 ASSERT(buf);
1444 ASSERT(buf->len >= 0);
1445
1446 if (buf->len)
1447 {
1448 return 0;
1449 }
1450
1451 len = buf_forward_capacity(buf);
1452
1453 retval = mbedtls_ssl_read(ks->ctx, BPTR(buf), len);
1454
1455 /* Error during read, check for retry error */
1456 if (retval < 0)
1457 {
1458 if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval
1459 || MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET == retval)
1460 {
1461 return 0;
1462 }
1463 mbed_log_err(D_TLS_ERRORS, retval, "TLS_ERROR: read tls_read_plaintext error");
1464 buf->len = 0;
1465 return -1;
1466 }
1467 /* Nothing read, try again */
1468 if (0 == retval)
1469 {
1470 buf->len = 0;
1471 return 0;
1472 }
1473
1474 /* successful read */
1475 dmsg(D_HANDSHAKE_VERBOSE, "read tls_read_plaintext %d bytes", retval);
1476 buf->len = retval;
1477
1478 return 1;
1479}
1480
1481/* **************************************
1482 *
1483 * Information functions
1484 *
1485 * Print information for the end user.
1486 *
1487 ***************************************/
1488void
1489print_details(struct key_state_ssl *ks_ssl, const char *prefix)
1490{
1491 const mbedtls_x509_crt *cert;
1492 char s1[256];
1493 char s2[256];
1494
1495 s1[0] = s2[0] = 0;
1496 snprintf(s1, sizeof(s1), "%s %s, cipher %s", prefix, mbedtls_ssl_get_version(ks_ssl->ctx),
1497 mbedtls_ssl_get_ciphersuite(ks_ssl->ctx));
1498
1499 cert = mbedtls_ssl_get_peer_cert(ks_ssl->ctx);
1500 if (cert != NULL)
1501 {
1502 snprintf(s2, sizeof(s2), ", %u bit key", (unsigned int)mbedtls_pk_get_bitlen(&cert->pk));
1503 }
1504
1505 msg(D_HANDSHAKE, "%s%s", s1, s2);
1506}
1507
1508void
1509show_available_tls_ciphers_list(const char *cipher_list, const char *tls_cert_profile, bool tls13)
1510{
1511 if (tls13)
1512 {
1513 /* mbed TLS has no TLS 1.3 support currently */
1514 return;
1515 }
1516 struct tls_root_ctx tls_ctx;
1517 const int *ciphers = mbedtls_ssl_list_ciphersuites();
1518
1519 tls_ctx_new(&tls_ctx);
1520 tls_ctx_set_cert_profile(&tls_ctx, tls_cert_profile);
1521 tls_ctx_restrict_ciphers(&tls_ctx, cipher_list);
1522
1523 if (tls_ctx.allowed_ciphers)
1524 {
1525 ciphers = tls_ctx.allowed_ciphers;
1526 }
1527
1528 while (*ciphers != 0)
1529 {
1530 printf("%s\n", mbedtls_ssl_get_ciphersuite_name(*ciphers));
1531 ciphers++;
1532 }
1533 tls_ctx_free(&tls_ctx);
1534}
1535
1536void
1538{
1539#if MBEDTLS_VERSION_NUMBER < 0x04000000
1540 const mbedtls_ecp_curve_info *pcurve = mbedtls_ecp_curve_list();
1541
1542 if (NULL == pcurve)
1543 {
1544 msg(M_FATAL, "Cannot retrieve curve list from mbed TLS");
1545 }
1546
1547 /* Print curve list */
1548 printf("Available Elliptic curves, listed in order of preference:\n\n");
1549 while (MBEDTLS_ECP_DP_NONE != pcurve->grp_id)
1550 {
1551 printf("%s\n", pcurve->name);
1552 pcurve++;
1553 }
1554#else
1555 printf("Available elliptic curves:\n\n");
1556 for (size_t i = 0; i < ecp_curve_info_table_items; i++)
1557 {
1558 printf("%s\n", ecp_curve_info_table[i].name);
1559 }
1560#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
1561}
1562
1563const char *
1565{
1566 static char mbedtls_version[30];
1567 unsigned int pv = mbedtls_version_get_number();
1568 snprintf(mbedtls_version, sizeof(mbedtls_version), "mbed TLS %u.%u.%u", (pv >> 24) & 0xff,
1569 (pv >> 16) & 0xff, (pv >> 8) & 0xff);
1570 return mbedtls_version;
1571}
1572
1573void
1575{
1576 return; /* no external key provider in mbedTLS build */
1577}
1578
1579#endif /* defined(ENABLE_CRYPTO_MBEDTLS) */
char * string_alloc(const char *str, struct gc_arena *gc)
Duplicate a string, allocating memory under garbage collection.
Definition buffer.c:616
Buffer management functions and garbage collection.
#define BPTR(buf)
Return a pointer to the start of the buffer content.
Definition buffer.h:139
#define ALLOC_ARRAY_CLEAR(dptr, type, n)
Allocate and zero-initialise an array of n elements of the given type.
Definition buffer.h:2012
static int buf_forward_capacity(const struct buffer *buf)
Return the number of bytes that can still be appended to the buffer.
Definition buffer.h:997
static void secure_memzero(void *data, size_t len)
Securely zeroise memory.
Definition buffer.h:705
#define BLEN(buf)
Return the length of the buffer content in bytes.
Definition buffer.h:145
static void gc_free(struct gc_arena *a)
Free all allocations in a garbage collection arena.
Definition buffer.h:1909
#define ALLOC_OBJ_CLEAR(dptr, type)
Allocate and zero-initialise memory for a single object of the given type.
Definition buffer.h:1971
static struct gc_arena gc_new(void)
Allocate and return a new, empty garbage collection arena.
Definition buffer.h:1893
uint64_t counter_type
Definition common.h:31
#define counter_format
Definition common.h:32
char * strsep(char **stringp, const char *delim)
char * strtok_r(char *s, const char *delim, char **last)
const char * print_key_filename(const char *str, bool is_inline)
To be used when printing a string that may contain inline data.
Definition crypto.c:1279
#define mbed_ok(errval)
Check errval and log on error.
bool mbed_log_err(unsigned int flags, int errval, const char *prefix)
Log the supplied mbed TLS error, prefixed by supplied prefix.
mbedtls_ctr_drbg_context * rand_ctx_get(void)
Returns a singleton instance of the mbed TLS random number generator.
const mbedtls_md_info_t * md_get(const char *digest)
#define D_TLS_DEBUG_LOW
Definition errlevel.h:76
#define D_TLS_DEBUG_MED
Definition errlevel.h:156
#define D_HANDSHAKE_VERBOSE
Definition errlevel.h:155
#define D_HANDSHAKE
Definition errlevel.h:71
#define D_TLS_ERRORS
Definition errlevel.h:58
#define D_TLS_DEBUG
Definition errlevel.h:164
#define KS_PRIMARY
Primary key state index.
Definition ssl_common.h:464
int key_state_read_plaintext(struct key_state_ssl *ks_ssl, struct buffer *buf)
Extract plaintext data from the TLS module.
int key_state_write_ciphertext(struct key_state_ssl *ks_ssl, struct buffer *buf)
Insert a ciphertext buffer into the TLS module.
int key_state_read_ciphertext(struct key_state_ssl *ks_ssl, struct buffer *buf)
Extract ciphertext data from the TLS module.
int key_state_write_plaintext_const(struct key_state_ssl *ks_ssl, const uint8_t *data, int len)
Insert plaintext data into the TLS module.
int key_state_write_plaintext(struct key_state_ssl *ks_ssl, struct buffer *buf)
Insert a plaintext buffer into the TLS module.
int verify_callback(void *session_obj, mbedtls_x509_crt *cert, int cert_depth, uint32_t *flags)
Verify that the remote OpenVPN peer's certificate allows setting up a VPN tunnel.
static SERVICE_STATUS status
Definition interactive.c:52
void management_auth_failure(struct management *man, const char *type, const char *reason)
Definition manage.c:3212
char * management_query_pk_sig(struct management *man, const char *b64_data, const char *algorithm)
Definition manage.c:3879
mbedtls compatibility stub.
static int mbedtls_compat_pk_parse_key(mbedtls_pk_context *ctx, const unsigned char *key, size_t keylen, const unsigned char *pwd, size_t pwdlen)
static void mbedtls_compat_psa_crypto_init(void)
static int mbedtls_compat_pk_check_pair(const mbedtls_pk_context *pub, const mbedtls_pk_context *prv)
static int mbedtls_compat_pk_parse_keyfile(mbedtls_pk_context *ctx, const char *path, const char *password)
#define CLEAR(x)
Definition basic.h:32
#define M_FATAL
Definition error.h:90
#define dmsg(flags,...)
Definition error.h:172
#define msg(flags,...)
Definition error.h:152
unsigned int msglvl_t
Definition error.h:77
#define ASSERT(x)
Definition error.h:219
#define M_WARN
Definition error.h:92
PKCS #11 SSL library-specific backend.
int openvpn_base64_decode(const char *str, void *data, int size)
Definition base64.c:160
int openvpn_base64_encode(const void *data, int size, char **str)
Definition base64.c:51
static struct user_pass passbuf
Definition ssl.c:245
int pem_password_callback(char *buf, int size, int rwflag, void *u)
Callback to retrieve the user's password.
Definition ssl.c:259
void load_xkey_provider(void)
Load ovpn.xkey provider used for external key signing.
Control Channel SSL library backend module.
void tls_ctx_set_tls_groups(struct tls_root_ctx *ctx, const char *groups)
Set the (elliptic curve) group allowed for signatures and key exchange.
void tls_ctx_free(struct tls_root_ctx *ctx)
Frees the library-specific TLSv1 context.
const char * get_ssl_library_version(void)
return a pointer to a static memory area containing the name and version number of the SSL library in...
bool key_state_export_keying_material(struct tls_session *session, const char *label, size_t label_size, void *ekm, size_t ekm_size)
Keying Material Exporters [RFC 5705] allows additional keying material to be derived from existing TL...
void show_available_tls_ciphers_list(const char *cipher_list, const char *tls_cert_profile, bool tls13)
Show the TLS ciphers that are available for us to use in the library depending on the TLS version.
void show_available_curves(void)
Show the available elliptic curves in the crypto library.
void key_state_ssl_free(struct key_state_ssl *ks_ssl)
Free the SSL channel part of the given key state.
#define TLS_VER_1_2
int tls_ctx_load_priv_file(struct tls_root_ctx *ctx, const char *priv_key_file, bool priv_key_file_inline)
Load private key file into the given TLS context.
void key_state_ssl_shutdown(struct key_state_ssl *ks_ssl)
Sets a TLS session to be shutdown state, so the TLS library will generate a shutdown alert.
void tls_ctx_load_extra_certs(struct tls_root_ctx *ctx, const char *extra_certs_file, bool extra_certs_file_inline)
Load extra certificate authority certificates from the given file or path.
void tls_ctx_check_cert_time(const struct tls_root_ctx *ctx)
Check our certificate notBefore and notAfter fields, and warn if the cert is either not yet valid or ...
void tls_ctx_restrict_ciphers_tls13(struct tls_root_ctx *ctx, const char *ciphers)
Restrict the list of ciphers that can be used within the TLS context for TLS 1.3 and higher.
int tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file, bool pkcs12_file_inline, bool load_ca_file)
Load PKCS #12 file for key, cert and (optionally) CA certs, and add to library-specific TLS context.
bool tls_ctx_initialised(struct tls_root_ctx *ctx)
Checks whether the given TLS context is initialised.
void key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_ctx *ssl_ctx, bool is_server, struct tls_session *session)
Initialise the SSL channel part of the given key state.
void tls_free_lib(void)
Free any global SSL library-specific data structures.
Definition ssl_openssl.c:98
void tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve_name)
Load Elliptic Curve Parameters, and load them into the library-specific TLS context.
#define TLS_VER_1_3
#define TLS_VER_UNSPEC
void tls_init_lib(void)
Perform any static initialisation necessary by the library.
Definition ssl_openssl.c:91
void print_details(struct key_state_ssl *ks_ssl, const char *prefix)
Print a one line summary of SSL/TLS session handshake.
int tls_version_max(void)
Return the maximum TLS version (as a TLS_VER_x constant) supported by current SSL implementation.
void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file, bool crl_inline)
Reload the Certificate Revocation List for the SSL channel.
void tls_ctx_restrict_ciphers(struct tls_root_ctx *ctx, const char *ciphers)
Restrict the list of ciphers that can be used within the TLS context for TLS 1.2 and below.
void tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file, bool ca_file_inline, const char *ca_path, bool tls_server)
Load certificate authority certificates from the given file or path.
void tls_ctx_set_cert_profile(struct tls_root_ctx *ctx, const char *profile)
Set the TLS certificate profile.
int tls_ctx_use_management_external_key(struct tls_root_ctx *ctx)
Tell the management interface to load the given certificate and the external private key matching the...
void tls_ctx_load_cryptoapi(struct tls_root_ctx *ctx, const char *cryptoapi_cert)
Use Windows cryptoapi for key and cert, and add to library-specific TLS context.
bool tls_ctx_set_options(struct tls_root_ctx *ctx, unsigned int ssl_flags)
Set any library specific options.
void tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file, bool dh_file_inline)
Load Diffie Hellman Parameters, and load them into the library-specific TLS context.
void tls_ctx_new(struct tls_root_ctx *ctx)
Initialise a library-specific TLS context.
void tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file, bool cert_file_inline)
Load certificate file into the given TLS context.
Control Channel Common Data Structures.
#define SSLF_TLS_VERSION_MAX_SHIFT
Definition ssl_common.h:431
#define UP_TYPE_PRIVATE_KEY
Definition ssl_common.h:42
#define SSLF_CLIENT_CERT_OPTIONAL
Definition ssl_common.h:424
#define SSLF_CLIENT_CERT_NOT_REQUIRED
Definition ssl_common.h:423
#define SSLF_TLS_DEBUG_ENABLED
Definition ssl_common.h:433
#define SSLF_TLS_VERSION_MAX_MASK
Definition ssl_common.h:432
#define SSLF_TLS_VERSION_MIN_SHIFT
Definition ssl_common.h:429
#define SSLF_TLS_VERSION_MIN_MASK
Definition ssl_common.h:430
int tls_ctx_use_external_signing_func(struct tls_root_ctx *ctx, external_sign_func sign_func, void *sign_ctx)
Call the supplied signing function to create a TLS signature during the TLS handshake.
bool(* external_sign_func)(void *sign_ctx, const void *src, size_t src_size, void *dst, size_t dst_size)
External signing function prototype.
Definition ssl_mbedtls.h:77
int get_num_elements(const char *string, char delimiter)
Returns the occurrences of 'delimiter' in a string +1 This is typically used to find out the number e...
Definition ssl_util.c:355
const tls_cipher_name_pair * tls_get_cipher_name_pair(const char *cipher_name, size_t len)
Definition ssl_util.c:336
SSL utility functions.
Control Channel Verification Module mbed TLS backend.
size_t length
Definition ssl_mbedtls.h:46
uint8_t * data
Definition ssl_mbedtls.h:47
buffer_entry * next_block
Definition ssl_mbedtls.h:48
endless_buffer out
Definition ssl_mbedtls.h:61
endless_buffer in
Definition ssl_mbedtls.h:60
One node in a buffer_list linked list.
Definition buffer.h:2096
Wrapper structure for dynamically allocated memory.
Definition buffer.h:71
int len
Length in bytes of the actual content within the allocated memory.
Definition buffer.h:76
size_t data_start
Definition ssl_mbedtls.h:53
buffer_entry * first_block
Definition ssl_mbedtls.h:54
buffer_entry * last_block
Definition ssl_mbedtls.h:55
Context used by external_pkcs1_sign()
Definition ssl_mbedtls.h:82
external_sign_func sign
Definition ssl_mbedtls.h:84
size_t signature_length
Definition ssl_mbedtls.h:83
Garbage collection arena used to keep track of dynamically allocated memory.
Definition buffer.h:127
Definition list.h:56
bio_ctx * bio_ctx
mbedtls_ssl_config * ssl_config
mbedTLS global ssl config
mbedtls_ssl_context * ctx
mbedTLS connection context
struct tls_key_cache tls_key_cache
Get a tls_cipher_name_pair containing OpenSSL and IANA names for supplied TLS cipher name.
Definition ssl_util.h:111
const char * iana_name
Definition ssl_util.h:113
const char * openssl_name
Definition ssl_util.h:112
struct to cache TLS secrets for keying material exporter (RFC 5705).
Definition ssl_mbedtls.h:96
unsigned char master_secret[48]
Definition ssl_mbedtls.h:99
mbedtls_tls_prf_types tls_prf_type
Definition ssl_mbedtls.h:98
unsigned char client_server_random[64]
Definition ssl_mbedtls.h:97
Structure that wraps the TLS context.
mbedtls_x509_crl * crl
Certificate Revocation List.
mbedtls_x509_crt * crt_chain
Local Certificate chain.
uint16_t * groups
List of allowed groups for this connection.
mbedtls_x509_crt * ca_chain
CA chain for remote verification.
int * allowed_ciphers
List of allowed ciphers for this connection.
mbedtls_dhm_context * dhm_ctx
Diffie-Helmann-Merkle context.
mbedtls_x509_crt_profile cert_profile
Allowed certificate types.
bool initialised
True if the context has been initialised.
struct external_context external_key
External key context.
mbedtls_pk_context * priv_key
Local private key.
Security parameter state of a single session within a VPN tunnel.
Definition ssl_common.h:489
static int cleanup(void **state)
struct gc_arena gc
Definition test_ssl.c:122