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