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