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-2025 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2010-2021 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
92{
93 ASSERT(NULL != ctx);
94 CLEAR(*ctx);
95
96 ALLOC_OBJ_CLEAR(ctx->dhm_ctx, mbedtls_dhm_context);
97
98 ALLOC_OBJ_CLEAR(ctx->ca_chain, mbedtls_x509_crt);
99
100 ctx->endpoint = MBEDTLS_SSL_IS_SERVER;
101 ctx->initialised = true;
102}
103
104void
106{
107 ASSERT(NULL != ctx);
108 CLEAR(*ctx);
109
110 ALLOC_OBJ_CLEAR(ctx->dhm_ctx, mbedtls_dhm_context);
111 ALLOC_OBJ_CLEAR(ctx->ca_chain, mbedtls_x509_crt);
112
113 ctx->endpoint = MBEDTLS_SSL_IS_CLIENT;
114 ctx->initialised = true;
115}
116
117void
118tls_ctx_free(struct tls_root_ctx *ctx)
119{
120 if (ctx)
121 {
122 mbedtls_pk_free(ctx->priv_key);
123 free(ctx->priv_key);
124
125 mbedtls_x509_crt_free(ctx->ca_chain);
126 free(ctx->ca_chain);
127
128 mbedtls_x509_crt_free(ctx->crt_chain);
129 free(ctx->crt_chain);
130
131 mbedtls_dhm_free(ctx->dhm_ctx);
132 free(ctx->dhm_ctx);
133
134 mbedtls_x509_crl_free(ctx->crl);
135 free(ctx->crl);
136
137#if defined(ENABLE_PKCS11)
138 /* ...freeCertificate() can handle NULL ptrs, but if pkcs11 helper
139 * has not been initialized, it will ASSERT() - so, do not pass NULL
140 */
141 if (ctx->pkcs11_cert)
142 {
143 pkcs11h_certificate_freeCertificate(ctx->pkcs11_cert);
144 }
145#endif
146
147 free(ctx->allowed_ciphers);
148
149 free(ctx->groups);
150
151 CLEAR(*ctx);
152
153 ctx->initialised = false;
154 }
155}
156
157bool
159{
160 /* either this should be NULL or should be non-null and then have a
161 * valid TLS ctx inside as well */
162 ASSERT(NULL == ctx || ctx->initialised);
163 return ctx != NULL;
164}
165#if !defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT)
166/*
167 * If we don't have mbedtls_ssl_export_keying_material(), we use
168 * mbedtls_ssl_set_export_keys_cb() to obtain a copy of the TLS 1.2
169 * master secret and compute the TLS-Exporter function ourselves.
170 * Unfortunately, with TLS 1.3, there is no alternative to
171 * mbedtls_ssl_export_keying_material().
172 */
173void
174mbedtls_ssl_export_keys_cb(void *p_expkey, mbedtls_ssl_key_export_type type,
175 const unsigned char *secret, size_t secret_len,
176 const unsigned char client_random[32],
177 const unsigned char server_random[32],
178 mbedtls_tls_prf_types tls_prf_type)
179{
180 /* Since we can't get the TLS 1.3 exporter master secret, we ignore all key
181 * types except MBEDTLS_SSL_KEY_EXPORT_TLS12_MASTER_SECRET. */
182 if (type != MBEDTLS_SSL_KEY_EXPORT_TLS12_MASTER_SECRET)
183 {
184 return;
185 }
186
187 struct tls_session *session = p_expkey;
188 struct key_state_ssl *ks_ssl = &session->key[KS_PRIMARY].ks_ssl;
189 struct tls_key_cache *cache = &ks_ssl->tls_key_cache;
190
191 /* The TLS 1.2 master secret has a fixed size, so if secret_len has
192 * a different value, something is wrong with mbed TLS. */
193 if (secret_len != sizeof(cache->master_secret))
194 {
195 msg(M_FATAL, "ERROR: Incorrect TLS 1.2 master secret length: Got %zu, expected %zu",
196 secret_len, sizeof(cache->master_secret));
197 }
198
199 memcpy(cache->client_server_random, client_random, 32);
200 memcpy(cache->client_server_random + 32, server_random, 32);
201 memcpy(cache->master_secret, secret, sizeof(cache->master_secret));
202 cache->tls_prf_type = tls_prf_type;
203}
204#endif /* !defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT) */
205
206
207bool
208key_state_export_keying_material(struct tls_session *session, const char *label, size_t label_size,
209 void *ekm, size_t ekm_size)
210{
211 ASSERT(strlen(label) == label_size);
212
213#if defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT)
214 /* Our version of mbed TLS has a built-in TLS-Exporter. */
215
216 mbedtls_ssl_context *ctx = session->key[KS_PRIMARY].ks_ssl.ctx;
217 if (mbed_ok(
218 mbedtls_ssl_export_keying_material(ctx, ekm, ekm_size, label, label_size, NULL, 0, 0)))
219 {
220 return true;
221 }
222 else
223 {
224 return false;
225 }
226
227#else /* defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT) */
228 struct tls_key_cache *cache = &session->key[KS_PRIMARY].ks_ssl.tls_key_cache;
229
230 /* If the type is NONE, we either have no cached secrets or
231 * there is no PRF, in both cases we cannot generate key material */
232 if (cache->tls_prf_type == MBEDTLS_SSL_TLS_PRF_NONE)
233 {
234 return false;
235 }
236
237 int ret = mbedtls_ssl_tls_prf(cache->tls_prf_type, cache->master_secret,
238 sizeof(cache->master_secret), label, cache->client_server_random,
239 sizeof(cache->client_server_random), ekm, ekm_size);
240
241 if (mbed_ok(ret))
242 {
243 return true;
244 }
245 else
246 {
247 secure_memzero(ekm, session->opt->ekm_size);
248 return false;
249 }
250#endif /* defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT) */
251}
252
253bool
254tls_ctx_set_options(struct tls_root_ctx *ctx, unsigned int ssl_flags)
255{
256 return true;
257}
258
259static const char *
260tls_translate_cipher_name(const char *cipher_name)
261{
262 const tls_cipher_name_pair *pair = tls_get_cipher_name_pair(cipher_name, strlen(cipher_name));
263
264 if (NULL == pair)
265 {
266 /* No translation found, return original */
267 return cipher_name;
268 }
269
270 if (0 != strcmp(cipher_name, pair->iana_name))
271 {
272 /* Deprecated name found, notify user */
273 msg(M_WARN, "Deprecated cipher suite name '%s', please use IANA name '%s'",
274 pair->openssl_name, pair->iana_name);
275 }
276
277 return pair->iana_name;
278}
279
280void
281tls_ctx_restrict_ciphers_tls13(struct tls_root_ctx *ctx, const char *ciphers)
282{
283 if (ciphers == NULL)
284 {
285 /* Nothing to do, return without warning message */
286 return;
287 }
288
289 msg(M_WARN,
290 "mbed TLS does not support setting tls-ciphersuites. "
291 "Ignoring TLS 1.3 cipher list: %s",
292 ciphers);
293}
294
295void
296tls_ctx_restrict_ciphers(struct tls_root_ctx *ctx, const char *ciphers)
297{
298 char *tmp_ciphers, *tmp_ciphers_orig, *token;
299
300 if (NULL == ciphers)
301 {
302 return; /* Nothing to do */
303 }
304
305 ASSERT(NULL != ctx);
306
307 /* Get number of ciphers */
308 int cipher_count = get_num_elements(ciphers, ':');
309
310 /* Allocate an array for them */
311 ALLOC_ARRAY_CLEAR(ctx->allowed_ciphers, int, cipher_count + 1)
312
313 /* Parse allowed ciphers, getting IDs */
314 int i = 0;
315 tmp_ciphers_orig = tmp_ciphers = string_alloc(ciphers, NULL);
316
317 token = strtok(tmp_ciphers, ":");
318 while (token)
319 {
320 ctx->allowed_ciphers[i] = mbedtls_ssl_get_ciphersuite_id(tls_translate_cipher_name(token));
321 if (0 != ctx->allowed_ciphers[i])
322 {
323 i++;
324 }
325 token = strtok(NULL, ":");
326 }
327 free(tmp_ciphers_orig);
328}
329
330void
331tls_ctx_set_cert_profile(struct tls_root_ctx *ctx, const char *profile)
332{
333 if (!profile || 0 == strcmp(profile, "legacy") || 0 == strcmp(profile, "insecure"))
334 {
335 ctx->cert_profile = openvpn_x509_crt_profile_legacy;
336 }
337 else if (0 == strcmp(profile, "preferred"))
338 {
339 ctx->cert_profile = openvpn_x509_crt_profile_preferred;
340 }
341 else if (0 == strcmp(profile, "suiteb"))
342 {
343 ctx->cert_profile = openvpn_x509_crt_profile_suiteb;
344 }
345 else
346 {
347 msg(M_FATAL, "ERROR: Invalid cert profile: %s", profile);
348 }
349}
350
351void
352tls_ctx_set_tls_groups(struct tls_root_ctx *ctx, const char *groups)
353{
354 ASSERT(ctx);
355 struct gc_arena gc = gc_new();
356
357 /* Get number of groups and allocate an array in ctx */
358 int groups_count = get_num_elements(groups, ':');
359 ALLOC_ARRAY_CLEAR(ctx->groups, uint16_t, groups_count + 1)
360
361 /* Parse allowed ciphers, getting IDs */
362 int i = 0;
363 char *tmp_groups = string_alloc(groups, &gc);
364
365 const char *token;
366 while ((token = strsep(&tmp_groups, ":")))
367 {
368 const mbedtls_ecp_curve_info *ci = mbedtls_ecp_curve_info_from_name(token);
369 if (!ci)
370 {
371 msg(M_WARN, "Warning unknown curve/group specified: %s", token);
372 }
373 else
374 {
375 ctx->groups[i] = ci->tls_id;
376 i++;
377 }
378 }
379
380 /* Recent mbedtls versions state that the list of groups must be terminated
381 * with 0. Older versions state that it must be terminated with MBEDTLS_ECP_DP_NONE
382 * which is also 0, so this works either way. */
383 ctx->groups[i] = 0;
384
385 gc_free(&gc);
386}
387
388
389void
390tls_ctx_check_cert_time(const struct tls_root_ctx *ctx)
391{
392 ASSERT(ctx);
393 if (ctx->crt_chain == NULL)
394 {
395 return; /* Nothing to check if there is no certificate */
396 }
397
398 if (mbedtls_x509_time_is_future(&ctx->crt_chain->valid_from))
399 {
400 msg(M_WARN, "WARNING: Your certificate is not yet valid!");
401 }
402
403 if (mbedtls_x509_time_is_past(&ctx->crt_chain->valid_to))
404 {
405 msg(M_WARN, "WARNING: Your certificate has expired!");
406 }
407}
408
409void
410tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file, bool dh_inline)
411{
412 if (dh_inline)
413 {
414 if (!mbed_ok(mbedtls_dhm_parse_dhm(ctx->dhm_ctx, (const unsigned char *)dh_file,
415 strlen(dh_file) + 1)))
416 {
417 msg(M_FATAL, "Cannot read inline DH parameters");
418 }
419 }
420 else
421 {
422 if (!mbed_ok(mbedtls_dhm_parse_dhmfile(ctx->dhm_ctx, dh_file)))
423 {
424 msg(M_FATAL, "Cannot read DH parameters from file %s", dh_file);
425 }
426 }
427
428 msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with " counter_format " bit key",
429 (counter_type)mbedtls_dhm_get_bitlen(ctx->dhm_ctx));
430}
431
432void
433tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve_name)
434{
435 if (NULL != curve_name)
436 {
437 msg(M_WARN, "WARNING: mbed TLS builds do not support specifying an "
438 "ECDH curve with --ecdh-curve, using default curves. Use "
439 "--tls-groups to specify curves.");
440 }
441}
442
443int
444tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file, bool pkcs12_file_inline,
445 bool load_ca_file)
446{
447 msg(M_FATAL, "PKCS #12 files not yet supported for mbed TLS.");
448 return 0;
449}
450
451#ifdef ENABLE_CRYPTOAPI
452void
453tls_ctx_load_cryptoapi(struct tls_root_ctx *ctx, const char *cryptoapi_cert)
454{
455 msg(M_FATAL, "Windows CryptoAPI not yet supported for mbed TLS.");
456}
457#endif /* _WIN32 */
458
459void
460tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file, bool cert_inline)
461{
462 ASSERT(NULL != ctx);
463
464 if (!ctx->crt_chain)
465 {
466 ALLOC_OBJ_CLEAR(ctx->crt_chain, mbedtls_x509_crt);
467 }
468
469 if (cert_inline)
470 {
471 if (!cert_file)
472 {
473 msg(M_FATAL, "Cannot load inline certificate: NULL");
474 }
475 if (!mbed_ok(mbedtls_x509_crt_parse(ctx->crt_chain, (const unsigned char *)cert_file,
476 strlen(cert_file) + 1)))
477 {
478 msg(M_FATAL, "Cannot load inline certificate");
479 }
480 }
481 else
482 {
483 if (!mbed_ok(mbedtls_x509_crt_parse_file(ctx->crt_chain, cert_file)))
484 {
485 msg(M_FATAL, "Cannot load certificate file %s", cert_file);
486 }
487 }
488}
489
490int
491tls_ctx_load_priv_file(struct tls_root_ctx *ctx, const char *priv_key_file, bool priv_key_inline)
492{
493 int status;
494 ASSERT(NULL != ctx);
495
496 if (!ctx->priv_key)
497 {
498 ALLOC_OBJ_CLEAR(ctx->priv_key, mbedtls_pk_context);
499 }
500
501 if (priv_key_inline)
502 {
503 status = mbedtls_pk_parse_key(ctx->priv_key, (const unsigned char *)priv_key_file,
504 strlen(priv_key_file) + 1, NULL, 0,
505 mbedtls_ctr_drbg_random, rand_ctx_get());
506
507 if (MBEDTLS_ERR_PK_PASSWORD_REQUIRED == status)
508 {
509 char passbuf[512] = { 0 };
510 pem_password_callback(passbuf, 512, 0, NULL);
511 status = mbedtls_pk_parse_key(
512 ctx->priv_key, (const unsigned char *)priv_key_file, strlen(priv_key_file) + 1,
513 (unsigned char *)passbuf, strlen(passbuf), mbedtls_ctr_drbg_random, rand_ctx_get());
514 }
515 }
516 else
517 {
518 status = mbedtls_pk_parse_keyfile(ctx->priv_key, priv_key_file, NULL,
519 mbedtls_ctr_drbg_random, rand_ctx_get());
520 if (MBEDTLS_ERR_PK_PASSWORD_REQUIRED == status)
521 {
522 char passbuf[512] = { 0 };
523 pem_password_callback(passbuf, 512, 0, NULL);
524 status = mbedtls_pk_parse_keyfile(ctx->priv_key, priv_key_file, passbuf,
525 mbedtls_ctr_drbg_random, rand_ctx_get());
526 }
527 }
528 if (!mbed_ok(status))
529 {
530#ifdef ENABLE_MANAGEMENT
531 if (management && (MBEDTLS_ERR_PK_PASSWORD_MISMATCH == status))
532 {
534 }
535#endif
536 msg(M_WARN, "Cannot load private key file %s",
537 print_key_filename(priv_key_file, priv_key_inline));
538 return 1;
539 }
540
541 if (!mbed_ok(mbedtls_pk_check_pair(&ctx->crt_chain->pk, ctx->priv_key,
542 mbedtls_ctr_drbg_random, rand_ctx_get())))
543 {
544 msg(M_WARN, "Private key does not match the certificate");
545 return 1;
546 }
547
548 return 0;
549}
550
551#if defined(__GNUC__) || defined(__clang__)
552#pragma GCC diagnostic push
553#pragma GCC diagnostic ignored "-Wconversion"
554#endif
555
574static inline int
575external_pkcs1_sign(void *ctx_voidptr, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
576 mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash,
577 unsigned char *sig)
578{
579 struct external_context *const ctx = ctx_voidptr;
580 int rv;
581 uint8_t *to_sign = NULL;
582 size_t asn_len = 0, oid_size = 0;
583 const char *oid = NULL;
584
585 if (NULL == ctx)
586 {
587 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
588 }
589
590 /*
591 * Support a wide range of hashes. TLSv1.1 and before only need SIG_RSA_RAW,
592 * but TLSv1.2 needs the full suite of hashes.
593 *
594 * This code has been taken from mbed TLS pkcs11_sign(), under the GPLv2.0+.
595 */
596 if (md_alg != MBEDTLS_MD_NONE)
597 {
598 const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_alg);
599 if (md_info == NULL)
600 {
601 return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA);
602 }
603
604 if (!mbed_ok(mbedtls_oid_get_oid_by_md(md_alg, &oid, &oid_size)))
605 {
606 return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA);
607 }
608
609 hashlen = mbedtls_md_get_size(md_info);
610 asn_len = 10 + oid_size;
611 }
612
613 if ((SIZE_MAX - hashlen) < asn_len || ctx->signature_length < (asn_len + hashlen))
614 {
615 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
616 }
617
618 ALLOC_ARRAY_CLEAR(to_sign, uint8_t, asn_len + hashlen);
619 uint8_t *p = to_sign;
620 if (md_alg != MBEDTLS_MD_NONE)
621 {
622 /*
623 * DigestInfo ::= SEQUENCE {
624 * digestAlgorithm DigestAlgorithmIdentifier,
625 * digest Digest }
626 *
627 * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
628 *
629 * Digest ::= OCTET STRING
630 */
631 *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
632 *p++ = (unsigned char)(0x08 + oid_size + hashlen);
633 *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
634 *p++ = (unsigned char)(0x04 + oid_size);
635 *p++ = MBEDTLS_ASN1_OID;
636 *p++ = oid_size & 0xFF;
637 memcpy(p, oid, oid_size);
638 p += oid_size;
639 *p++ = MBEDTLS_ASN1_NULL;
640 *p++ = 0x00;
641 *p++ = MBEDTLS_ASN1_OCTET_STRING;
642 *p++ = hashlen;
643
644 /* Double-check ASN length */
645 ASSERT(asn_len == p - to_sign);
646 }
647
648 /* Copy the hash to be signed */
649 memcpy(p, hash, hashlen);
650
651 /* Call external signature function */
652 if (!ctx->sign(ctx->sign_ctx, to_sign, asn_len + hashlen, sig, ctx->signature_length))
653 {
654 rv = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
655 goto done;
656 }
657
658 rv = 0;
659
660done:
661 free(to_sign);
662 return rv;
663}
664
665static inline size_t
666external_key_len(void *vctx)
667{
668 struct external_context *const ctx = vctx;
669
670 return ctx->signature_length;
671}
672
673int
675 void *sign_ctx)
676{
677 ASSERT(NULL != ctx);
678
679 if (ctx->crt_chain == NULL)
680 {
681 msg(M_WARN, "ERROR: external key requires a certificate.");
682 return 1;
683 }
684
685 if (mbedtls_pk_get_type(&ctx->crt_chain->pk) != MBEDTLS_PK_RSA)
686 {
687 msg(M_WARN, "ERROR: external key with mbed TLS requires a "
688 "certificate with an RSA key.");
689 return 1;
690 }
691
692 ctx->external_key.signature_length = mbedtls_pk_get_len(&ctx->crt_chain->pk);
693 ctx->external_key.sign = sign_func;
695
696 ALLOC_OBJ_CLEAR(ctx->priv_key, mbedtls_pk_context);
697 if (!mbed_ok(mbedtls_pk_setup_rsa_alt(ctx->priv_key, &ctx->external_key, NULL,
698 external_pkcs1_sign, external_key_len)))
699 {
700 return 1;
701 }
702
703 return 0;
704}
705
706#ifdef ENABLE_MANAGEMENT
708static bool
709management_sign_func(void *sign_ctx, const void *src, size_t src_len, void *dst, size_t dst_len)
710{
711 bool ret = false;
712 char *src_b64 = NULL;
713 char *dst_b64 = NULL;
714
715 if (!management || (openvpn_base64_encode(src, (int)src_len, &src_b64) <= 0))
716 {
717 goto cleanup;
718 }
719
720 /*
721 * We only support RSA external keys and PKCS1 signatures at the moment
722 * in mbed TLS, so the signature parameter is hardcoded to this encoding
723 */
724 if (!(dst_b64 = management_query_pk_sig(management, src_b64, "RSA_PKCS1_PADDING")))
725 {
726 goto cleanup;
727 }
728
729 if (openvpn_base64_decode(dst_b64, dst, (int)dst_len) != dst_len)
730 {
731 goto cleanup;
732 }
733
734 ret = true;
735cleanup:
736 free(src_b64);
737 free(dst_b64);
738
739 return ret;
740}
741
742int
744{
745 return tls_ctx_use_external_signing_func(ctx, management_sign_func, NULL);
746}
747
748#endif /* ifdef ENABLE_MANAGEMENT */
749
750void
751tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file, bool ca_inline, const char *ca_path,
752 bool tls_server)
753{
754 if (ca_path)
755 {
756 msg(M_FATAL, "ERROR: mbed TLS cannot handle the capath directive");
757 }
758
759 if (ca_file && ca_inline)
760 {
761 if (!mbed_ok(mbedtls_x509_crt_parse(ctx->ca_chain, (const unsigned char *)ca_file,
762 strlen(ca_file) + 1)))
763 {
764 msg(M_FATAL, "Cannot load inline CA certificates");
765 }
766 }
767 else
768 {
769 /* Load CA file for verifying peer supplied certificate */
770 if (!mbed_ok(mbedtls_x509_crt_parse_file(ctx->ca_chain, ca_file)))
771 {
772 msg(M_FATAL, "Cannot load CA certificate file %s", ca_file);
773 }
774 }
775}
776
777void
778tls_ctx_load_extra_certs(struct tls_root_ctx *ctx, const char *extra_certs_file,
779 bool extra_certs_inline)
780{
781 ASSERT(NULL != ctx);
782
783 if (!ctx->crt_chain)
784 {
785 ALLOC_OBJ_CLEAR(ctx->crt_chain, mbedtls_x509_crt);
786 }
787
788 if (extra_certs_inline)
789 {
790 if (!mbed_ok(mbedtls_x509_crt_parse(ctx->crt_chain, (const unsigned char *)extra_certs_file,
791 strlen(extra_certs_file) + 1)))
792 {
793 msg(M_FATAL, "Cannot load inline extra-certs file");
794 }
795 }
796 else
797 {
798 if (!mbed_ok(mbedtls_x509_crt_parse_file(ctx->crt_chain, extra_certs_file)))
799 {
800 msg(M_FATAL, "Cannot load extra-certs file: %s", extra_certs_file);
801 }
802 }
803}
804
805/* **************************************
806 *
807 * Key-state specific functions
808 *
809 ***************************************/
810
811/*
812 * "Endless buffer"
813 */
814
815static inline void
816buf_free_entry(buffer_entry *entry)
817{
818 if (NULL != entry)
819 {
820 free(entry->data);
821 free(entry);
822 }
823}
824
825static void
826buf_free_entries(endless_buffer *buf)
827{
828 while (buf->first_block)
829 {
830 buffer_entry *cur_block = buf->first_block;
831 buf->first_block = cur_block->next_block;
832 buf_free_entry(cur_block);
833 }
834 buf->last_block = NULL;
835}
836
837static int
838endless_buf_read(endless_buffer *in, unsigned char *out, size_t out_len)
839{
840 size_t read_len = 0;
841
842 if (in->first_block == NULL)
843 {
844 return MBEDTLS_ERR_SSL_WANT_READ;
845 }
846
847 while (in->first_block != NULL && read_len < out_len)
848 {
849 int block_len = in->first_block->length - in->data_start;
850 if (block_len <= out_len - read_len)
851 {
852 buffer_entry *cur_entry = in->first_block;
853 memcpy(out + read_len, cur_entry->data + in->data_start, block_len);
854
855 read_len += block_len;
856
857 in->first_block = cur_entry->next_block;
858 in->data_start = 0;
859
860 if (in->first_block == NULL)
861 {
862 in->last_block = NULL;
863 }
864
865 buf_free_entry(cur_entry);
866 }
867 else
868 {
869 memcpy(out + read_len, in->first_block->data + in->data_start, out_len - read_len);
870 in->data_start += out_len - read_len;
871 read_len = out_len;
872 }
873 }
874
875 return read_len;
876}
877
878static int
879endless_buf_write(endless_buffer *out, const unsigned char *in, size_t len)
880{
881 buffer_entry *new_block = malloc(sizeof(buffer_entry));
882 if (NULL == new_block)
883 {
884 return MBEDTLS_ERR_NET_SEND_FAILED;
885 }
886
887 new_block->data = malloc(len);
888 if (NULL == new_block->data)
889 {
890 free(new_block);
891 return MBEDTLS_ERR_NET_SEND_FAILED;
892 }
893
894 new_block->length = len;
895 new_block->next_block = NULL;
896
897 memcpy(new_block->data, in, len);
898
899 if (NULL == out->first_block)
900 {
901 out->first_block = new_block;
902 }
903
904 if (NULL != out->last_block)
905 {
906 out->last_block->next_block = new_block;
907 }
908
909 out->last_block = new_block;
910
911 return len;
912}
913
914static int
915ssl_bio_read(void *ctx, unsigned char *out, size_t out_len)
916{
917 bio_ctx *my_ctx = (bio_ctx *)ctx;
918 return endless_buf_read(&my_ctx->in, out, out_len);
919}
920
921static int
922ssl_bio_write(void *ctx, const unsigned char *in, size_t in_len)
923{
924 bio_ctx *my_ctx = (bio_ctx *)ctx;
925 return endless_buf_write(&my_ctx->out, in, in_len);
926}
927
928static void
929my_debug(void *ctx, int level, const char *file, int line, const char *str)
930{
931 int my_loglevel = (level < 3) ? D_TLS_DEBUG_MED : D_TLS_DEBUG;
932 msg(my_loglevel, "mbed TLS msg (%s:%d): %s", file, line, str);
933}
934
935/*
936 * Further personalise the RNG using a hash of the public key
937 */
938void
939tls_ctx_personalise_random(struct tls_root_ctx *ctx)
940{
941 static char old_sha256_hash[32] = { 0 };
942 unsigned char sha256_hash[32] = { 0 };
943 mbedtls_ctr_drbg_context *cd_ctx = rand_ctx_get();
944
945 if (NULL != ctx->crt_chain)
946 {
947 mbedtls_x509_crt *cert = ctx->crt_chain;
948
949 if (!md_full("SHA256", cert->tbs.p, cert->tbs.len, sha256_hash))
950 {
951 msg(M_WARN, "WARNING: failed to personalise random");
952 }
953
954 if (0 != memcmp(old_sha256_hash, sha256_hash, sizeof(sha256_hash)))
955 {
956 if (!mbed_ok(mbedtls_ctr_drbg_update(cd_ctx, sha256_hash, 32)))
957 {
958 msg(M_WARN, "WARNING: failed to personalise random, could not update CTR_DRBG");
959 }
960 memcpy(old_sha256_hash, sha256_hash, sizeof(old_sha256_hash));
961 }
962 }
963}
964
965#if defined(__GNUC__) || defined(__clang__)
966#pragma GCC diagnostic pop
967#endif
968
969int
970tls_version_max(void)
971{
972 /* We need mbedtls_ssl_export_keying_material() to support TLS 1.3. */
973#if defined(MBEDTLS_SSL_PROTO_TLS1_3) && defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT)
974 return TLS_VER_1_3;
975#elif defined(MBEDTLS_SSL_PROTO_TLS1_2)
976 return TLS_VER_1_2;
977#else
978#error mbedtls is compiled without support for TLS 1.2 or 1.3
979#endif
980}
981
989mbedtls_ssl_protocol_version
990tls_version_to_ssl_version(int tls_ver)
991{
992 switch (tls_ver)
993 {
994#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
995 case TLS_VER_1_2:
996 return MBEDTLS_SSL_VERSION_TLS1_2;
997#endif
998
999#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1000 case TLS_VER_1_3:
1001 return MBEDTLS_SSL_VERSION_TLS1_3;
1002#endif
1003
1004 default:
1005 msg(M_FATAL, "%s: invalid or unsupported TLS version %d", __func__, tls_ver);
1006 return MBEDTLS_SSL_VERSION_UNKNOWN;
1007 }
1008}
1009
1010void
1011backend_tls_ctx_reload_crl(struct tls_root_ctx *ctx, const char *crl_file, bool crl_inline)
1012{
1013 ASSERT(crl_file);
1014
1015 if (ctx->crl == NULL)
1016 {
1017 ALLOC_OBJ_CLEAR(ctx->crl, mbedtls_x509_crl);
1018 }
1019 mbedtls_x509_crl_free(ctx->crl);
1020
1021 if (crl_inline)
1022 {
1023 if (!mbed_ok(mbedtls_x509_crl_parse(ctx->crl, (const unsigned char *)crl_file,
1024 strlen(crl_file) + 1)))
1025 {
1026 msg(M_WARN, "CRL: cannot parse inline CRL");
1027 goto err;
1028 }
1029 }
1030 else
1031 {
1032 if (!mbed_ok(mbedtls_x509_crl_parse_file(ctx->crl, crl_file)))
1033 {
1034 msg(M_WARN, "CRL: cannot read CRL from file %s", crl_file);
1035 goto err;
1036 }
1037 }
1038 return;
1039
1040err:
1041 mbedtls_x509_crl_free(ctx->crl);
1042}
1043
1044void
1045key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_ctx *ssl_ctx, bool is_server,
1046 struct tls_session *session)
1047{
1048 ASSERT(NULL != ssl_ctx);
1049 ASSERT(ks_ssl);
1050 CLEAR(*ks_ssl);
1051
1052 /* Initialise SSL config */
1053 ALLOC_OBJ_CLEAR(ks_ssl->ssl_config, mbedtls_ssl_config);
1054 mbedtls_ssl_config_init(ks_ssl->ssl_config);
1055 mbedtls_ssl_config_defaults(ks_ssl->ssl_config, ssl_ctx->endpoint, MBEDTLS_SSL_TRANSPORT_STREAM,
1056 MBEDTLS_SSL_PRESET_DEFAULT);
1057#ifdef MBEDTLS_DEBUG_C
1058 /* We only want to have mbed TLS generate debug level logging when we would
1059 * also display it.
1060 * In fact mbed TLS 2.25.0 crashes generating debug log if Curve25591 is
1061 * selected for DH (https://github.com/ARMmbed/mbedtls/issues/4208) */
1062 if (session->opt->ssl_flags & SSLF_TLS_DEBUG_ENABLED)
1063 {
1064 mbedtls_debug_set_threshold(3);
1065 }
1066 else
1067 {
1068 mbedtls_debug_set_threshold(2);
1069 }
1070#endif
1071 mbedtls_ssl_conf_dbg(ks_ssl->ssl_config, my_debug, NULL);
1072 mbedtls_ssl_conf_rng(ks_ssl->ssl_config, mbedtls_ctr_drbg_random, rand_ctx_get());
1073
1074 mbedtls_ssl_conf_cert_profile(ks_ssl->ssl_config, &ssl_ctx->cert_profile);
1075
1076 if (ssl_ctx->allowed_ciphers)
1077 {
1078 mbedtls_ssl_conf_ciphersuites(ks_ssl->ssl_config, ssl_ctx->allowed_ciphers);
1079 }
1080
1081 if (ssl_ctx->groups)
1082 {
1083 mbedtls_ssl_conf_groups(ks_ssl->ssl_config, ssl_ctx->groups);
1084 }
1085
1086 /* Disable TLS renegotiations if the mbedtls library supports that feature.
1087 * OpenVPN's renegotiation creates new SSL sessions and does not depend on
1088 * this feature and TLS renegotiations have been problematic in the past. */
1089#if defined(MBEDTLS_SSL_RENEGOTIATION)
1090 mbedtls_ssl_conf_renegotiation(ks_ssl->ssl_config, MBEDTLS_SSL_RENEGOTIATION_DISABLED);
1091#endif /* MBEDTLS_SSL_RENEGOTIATION */
1092
1093 /* Disable record splitting (for now). OpenVPN assumes records are sent
1094 * unfragmented, and changing that will require thorough review and
1095 * testing. Since OpenVPN is not susceptible to BEAST, we can just
1096 * disable record splitting as a quick fix. */
1097#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
1098 mbedtls_ssl_conf_cbc_record_splitting(ks_ssl->ssl_config,
1099 MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED);
1100#endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
1101
1102 /* Initialise authentication information */
1103 if (is_server)
1104 {
1105 mbed_ok(mbedtls_ssl_conf_dh_param_ctx(ks_ssl->ssl_config, ssl_ctx->dhm_ctx));
1106 }
1107
1108 mbed_ok(mbedtls_ssl_conf_own_cert(ks_ssl->ssl_config, ssl_ctx->crt_chain, ssl_ctx->priv_key));
1109
1110 /* Initialise SSL verification */
1111 if (session->opt->ssl_flags & SSLF_CLIENT_CERT_OPTIONAL)
1112 {
1113 mbedtls_ssl_conf_authmode(ks_ssl->ssl_config, MBEDTLS_SSL_VERIFY_OPTIONAL);
1114 }
1115 else if (!(session->opt->ssl_flags & SSLF_CLIENT_CERT_NOT_REQUIRED))
1116 {
1117 mbedtls_ssl_conf_authmode(ks_ssl->ssl_config, MBEDTLS_SSL_VERIFY_REQUIRED);
1118 }
1119 mbedtls_ssl_conf_verify(ks_ssl->ssl_config, verify_callback, session);
1120
1121 /* TODO: mbed TLS does not currently support sending the CA chain to the client */
1122 mbedtls_ssl_conf_ca_chain(ks_ssl->ssl_config, ssl_ctx->ca_chain, ssl_ctx->crl);
1123
1124 /* Initialize minimum TLS version */
1125 {
1126 const int configured_tls_version_min =
1128
1129 /* default to TLS 1.2 */
1130 mbedtls_ssl_protocol_version version = MBEDTLS_SSL_VERSION_TLS1_2;
1131
1132 if (configured_tls_version_min > TLS_VER_UNSPEC)
1133 {
1134 version = tls_version_to_ssl_version(configured_tls_version_min);
1135 }
1136
1137 mbedtls_ssl_conf_min_tls_version(ks_ssl->ssl_config, version);
1138 }
1139
1140 /* Initialize maximum TLS version */
1141 {
1142 const int configured_tls_version_max =
1144
1145 mbedtls_ssl_protocol_version version = MBEDTLS_SSL_VERSION_UNKNOWN;
1146
1147 if (configured_tls_version_max > TLS_VER_UNSPEC)
1148 {
1149 version = tls_version_to_ssl_version(configured_tls_version_max);
1150 }
1151 else
1152 {
1153 /* Default to tls_version_max(). */
1154 version = tls_version_to_ssl_version(tls_version_max());
1155 }
1156
1157 mbedtls_ssl_conf_max_tls_version(ks_ssl->ssl_config, version);
1158 }
1159
1160 /* Initialise SSL context */
1161 ALLOC_OBJ_CLEAR(ks_ssl->ctx, mbedtls_ssl_context);
1162 mbedtls_ssl_init(ks_ssl->ctx);
1163 mbed_ok(mbedtls_ssl_setup(ks_ssl->ctx, ks_ssl->ssl_config));
1164 /* We do verification in our own callback depending on the
1165 * exact configuration. We do not rely on the default hostname
1166 * verification. */
1167 ASSERT(mbed_ok(mbedtls_ssl_set_hostname(ks_ssl->ctx, NULL)));
1168
1169#if !defined(MBEDTLS_SSL_KEYING_MATERIAL_EXPORT)
1170 /* Initialize the keying material exporter callback. */
1171 mbedtls_ssl_set_export_keys_cb(ks_ssl->ctx, mbedtls_ssl_export_keys_cb, session);
1172#endif
1173
1174 /* Initialise BIOs */
1176 mbedtls_ssl_set_bio(ks_ssl->ctx, ks_ssl->bio_ctx, ssl_bio_write, ssl_bio_read, NULL);
1177}
1178
1179
1180void
1182{
1183 mbedtls_ssl_send_alert_message(ks_ssl->ctx, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1184 MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY);
1185}
1186
1187void
1188key_state_ssl_free(struct key_state_ssl *ks_ssl)
1189{
1190 if (ks_ssl)
1191 {
1192 CLEAR(ks_ssl->tls_key_cache);
1193
1194 if (ks_ssl->ctx)
1195 {
1196 mbedtls_ssl_free(ks_ssl->ctx);
1197 free(ks_ssl->ctx);
1198 }
1199 if (ks_ssl->ssl_config)
1200 {
1201 mbedtls_ssl_config_free(ks_ssl->ssl_config);
1202 free(ks_ssl->ssl_config);
1203 }
1204 if (ks_ssl->bio_ctx)
1205 {
1206 buf_free_entries(&ks_ssl->bio_ctx->in);
1207 buf_free_entries(&ks_ssl->bio_ctx->out);
1208 free(ks_ssl->bio_ctx);
1209 }
1210 CLEAR(*ks_ssl);
1211 }
1212}
1213
1214int
1215key_state_write_plaintext(struct key_state_ssl *ks, struct buffer *buf)
1216{
1217 int retval = 0;
1218
1219 ASSERT(buf);
1220
1221 retval = key_state_write_plaintext_const(ks, BPTR(buf), BLEN(buf));
1222
1223 if (1 == retval)
1224 {
1225 memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */
1226 buf->len = 0;
1227 }
1228
1229 return retval;
1230}
1231
1232int
1233key_state_write_plaintext_const(struct key_state_ssl *ks, const uint8_t *data, int len)
1234{
1235 int retval = 0;
1236
1237 ASSERT(NULL != ks);
1238 ASSERT(len >= 0);
1239
1240 if (0 == len)
1241 {
1242 return 0;
1243 }
1244
1245 ASSERT(data);
1246
1247 retval = mbedtls_ssl_write(ks->ctx, data, len);
1248
1249 if (retval < 0)
1250 {
1251 if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval)
1252 {
1253 return 0;
1254 }
1255 mbed_log_err(D_TLS_ERRORS, retval, "TLS ERROR: write tls_write_plaintext_const error");
1256 return -1;
1257 }
1258
1259 if (retval != len)
1260 {
1261 msg(D_TLS_ERRORS, "TLS ERROR: write tls_write_plaintext_const incomplete %d/%d", retval,
1262 len);
1263 return -1;
1264 }
1265
1266 /* successful write */
1267 dmsg(D_HANDSHAKE_VERBOSE, "write tls_write_plaintext_const %d bytes", retval);
1268
1269 return 1;
1270}
1271
1272int
1273key_state_read_ciphertext(struct key_state_ssl *ks, struct buffer *buf)
1274{
1275 int retval = 0;
1276 int len = 0;
1277
1278 ASSERT(NULL != ks);
1279 ASSERT(buf);
1280 ASSERT(buf->len >= 0);
1281
1282 if (buf->len)
1283 {
1284 return 0;
1285 }
1286
1287 len = buf_forward_capacity(buf);
1288
1289 retval = endless_buf_read(&ks->bio_ctx->out, BPTR(buf), len);
1290
1291 /* Error during read, check for retry error */
1292 if (retval < 0)
1293 {
1294 if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval)
1295 {
1296 return 0;
1297 }
1298 mbed_log_err(D_TLS_ERRORS, retval, "TLS_ERROR: read tls_read_ciphertext error");
1299 buf->len = 0;
1300 return -1;
1301 }
1302 /* Nothing read, try again */
1303 if (0 == retval)
1304 {
1305 buf->len = 0;
1306 return 0;
1307 }
1308
1309 /* successful read */
1310 dmsg(D_HANDSHAKE_VERBOSE, "read tls_read_ciphertext %d bytes", retval);
1311 buf->len = retval;
1312 return 1;
1313}
1314
1315int
1316key_state_write_ciphertext(struct key_state_ssl *ks, struct buffer *buf)
1317{
1318 int retval = 0;
1319
1320 ASSERT(NULL != ks);
1321 ASSERT(buf);
1322 ASSERT(buf->len >= 0);
1323
1324 if (0 == buf->len)
1325 {
1326 return 0;
1327 }
1328
1329 retval = endless_buf_write(&ks->bio_ctx->in, BPTR(buf), buf->len);
1330
1331 if (retval < 0)
1332 {
1333 if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval)
1334 {
1335 return 0;
1336 }
1337 mbed_log_err(D_TLS_ERRORS, retval, "TLS ERROR: write tls_write_ciphertext error");
1338 return -1;
1339 }
1340
1341 if (retval != buf->len)
1342 {
1343 msg(D_TLS_ERRORS, "TLS ERROR: write tls_write_ciphertext incomplete %d/%d", retval,
1344 buf->len);
1345 return -1;
1346 }
1347
1348 /* successful write */
1349 dmsg(D_HANDSHAKE_VERBOSE, "write tls_write_ciphertext %d bytes", retval);
1350
1351 memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */
1352 buf->len = 0;
1353
1354 return 1;
1355}
1356
1357int
1358key_state_read_plaintext(struct key_state_ssl *ks, struct buffer *buf)
1359{
1360 int retval = 0;
1361 int len = 0;
1362
1363 ASSERT(NULL != ks);
1364 ASSERT(buf);
1365 ASSERT(buf->len >= 0);
1366
1367 if (buf->len)
1368 {
1369 return 0;
1370 }
1371
1372 len = buf_forward_capacity(buf);
1373
1374 retval = mbedtls_ssl_read(ks->ctx, BPTR(buf), len);
1375
1376 /* Error during read, check for retry error */
1377 if (retval < 0)
1378 {
1379 if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval)
1380 {
1381 return 0;
1382 }
1383 mbed_log_err(D_TLS_ERRORS, retval, "TLS_ERROR: read tls_read_plaintext error");
1384 buf->len = 0;
1385 return -1;
1386 }
1387 /* Nothing read, try again */
1388 if (0 == retval)
1389 {
1390 buf->len = 0;
1391 return 0;
1392 }
1393
1394 /* successful read */
1395 dmsg(D_HANDSHAKE_VERBOSE, "read tls_read_plaintext %d bytes", retval);
1396 buf->len = retval;
1397
1398 return 1;
1399}
1400
1401/* **************************************
1402 *
1403 * Information functions
1404 *
1405 * Print information for the end user.
1406 *
1407 ***************************************/
1408void
1409print_details(struct key_state_ssl *ks_ssl, const char *prefix)
1410{
1411 const mbedtls_x509_crt *cert;
1412 char s1[256];
1413 char s2[256];
1414
1415 s1[0] = s2[0] = 0;
1416 snprintf(s1, sizeof(s1), "%s %s, cipher %s", prefix, mbedtls_ssl_get_version(ks_ssl->ctx),
1417 mbedtls_ssl_get_ciphersuite(ks_ssl->ctx));
1418
1419 cert = mbedtls_ssl_get_peer_cert(ks_ssl->ctx);
1420 if (cert != NULL)
1421 {
1422 snprintf(s2, sizeof(s2), ", %u bit key", (unsigned int)mbedtls_pk_get_bitlen(&cert->pk));
1423 }
1424
1425 msg(D_HANDSHAKE, "%s%s", s1, s2);
1426}
1427
1428void
1429show_available_tls_ciphers_list(const char *cipher_list, const char *tls_cert_profile, bool tls13)
1430{
1431 if (tls13)
1432 {
1433 /* mbed TLS has no TLS 1.3 support currently */
1434 return;
1435 }
1436 struct tls_root_ctx tls_ctx;
1437 const int *ciphers = mbedtls_ssl_list_ciphersuites();
1438
1439 tls_ctx_server_new(&tls_ctx);
1440 tls_ctx_set_cert_profile(&tls_ctx, tls_cert_profile);
1441 tls_ctx_restrict_ciphers(&tls_ctx, cipher_list);
1442
1443 if (tls_ctx.allowed_ciphers)
1444 {
1445 ciphers = tls_ctx.allowed_ciphers;
1446 }
1447
1448 while (*ciphers != 0)
1449 {
1450 printf("%s\n", mbedtls_ssl_get_ciphersuite_name(*ciphers));
1451 ciphers++;
1452 }
1453 tls_ctx_free(&tls_ctx);
1454}
1455
1456void
1458{
1459 const mbedtls_ecp_curve_info *pcurve = mbedtls_ecp_curve_list();
1460
1461 if (NULL == pcurve)
1462 {
1463 msg(M_FATAL, "Cannot retrieve curve list from mbed TLS");
1464 }
1465
1466 /* Print curve list */
1467 printf("Available Elliptic curves, listed in order of preference:\n\n");
1468 while (MBEDTLS_ECP_DP_NONE != pcurve->grp_id)
1469 {
1470 printf("%s\n", pcurve->name);
1471 pcurve++;
1472 }
1473}
1474
1475const char *
1477{
1478 static char mbedtls_version[30];
1479 unsigned int pv = mbedtls_version_get_number();
1480 snprintf(mbedtls_version, sizeof(mbedtls_version), "mbed TLS %d.%d.%d", (pv >> 24) & 0xff,
1481 (pv >> 16) & 0xff, (pv >> 8) & 0xff);
1482 return mbedtls_version;
1483}
1484
1485void
1487{
1488 return; /* no external key provider in mbedTLS build */
1489}
1490
1491#endif /* defined(ENABLE_CRYPTO_MBEDTLS) */
char * string_alloc(const char *str, struct gc_arena *gc)
Definition buffer.c:648
#define BPTR(buf)
Definition buffer.h:123
#define ALLOC_ARRAY_CLEAR(dptr, type, n)
Definition buffer.h:1080
static int buf_forward_capacity(const struct buffer *buf)
Definition buffer.h:539
static void secure_memzero(void *data, size_t len)
Securely zeroise memory.
Definition buffer.h:414
#define BLEN(buf)
Definition buffer.h:126
static void gc_free(struct gc_arena *a)
Definition buffer.h:1025
#define ALLOC_OBJ_CLEAR(dptr, type)
Definition buffer.h:1064
static struct gc_arena gc_new(void)
Definition buffer.h:1017
uint64_t counter_type
Definition common.h:31
#define counter_format
Definition common.h:32
char * strsep(char **stringp, const char *delim)
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
int md_full(const char *mdname, const uint8_t *src, int src_len, uint8_t *dst)
Calculates the message digest for the given buffer.
mbedtls_ctr_drbg_context * rand_ctx_get(void)
Returns a singleton instance of the mbed TLS random number generator.
#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.
#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:468
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:51
void management_auth_failure(struct management *man, const char *type, const char *reason)
Definition manage.c:3102
char * management_query_pk_sig(struct management *man, const char *b64_data, const char *algorithm)
Definition manage.c:3763
mbedtls compatibility stub.
static void mbedtls_compat_psa_crypto_init(void)
#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
#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 tls_ctx_server_new(struct tls_root_ctx *ctx)
Initialise a library-specific TLS context for a server.
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_client_new(struct tls_root_ctx *ctx)
Initialises a library-specific TLS context for a client.
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:435
#define UP_TYPE_PRIVATE_KEY
Definition ssl_common.h:42
#define SSLF_CLIENT_CERT_OPTIONAL
Definition ssl_common.h:428
#define SSLF_CLIENT_CERT_NOT_REQUIRED
Definition ssl_common.h:427
#define SSLF_TLS_DEBUG_ENABLED
Definition ssl_common.h:437
#define SSLF_TLS_VERSION_MAX_MASK
Definition ssl_common.h:436
#define SSLF_TLS_VERSION_MIN_SHIFT
Definition ssl_common.h:433
#define SSLF_TLS_VERSION_MIN_MASK
Definition ssl_common.h:434
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:294
const tls_cipher_name_pair * tls_get_cipher_name_pair(const char *cipher_name, size_t len)
Definition ssl_util.c:275
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
Definition buffer.h:1119
Wrapper structure for dynamically allocated memory.
Definition buffer.h:60
int len
Length in bytes of the actual content within the allocated memory.
Definition buffer.h:65
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:116
Definition list.h:53
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:77
const char * iana_name
Definition ssl_util.h:79
const char * openssl_name
Definition ssl_util.h:78
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.
int endpoint
Whether or not this is a server or a client.
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:493
static int cleanup(void **state)
struct gc_arena gc
Definition test_ssl.c:131