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