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-2024 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#else /* if HAVE_MBEDTLS_SSL_CONF_EXPORT_KEYS_EXT_CB */
255#error either mbedtls_ssl_conf_export_keys_ext_cb or mbedtls_ssl_set_export_keys_cb 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 struct tls_key_cache *cache = &session->key[KS_PRIMARY].ks_ssl.tls_key_cache;
266
267 /* If the type is NONE, we either have no cached secrets or
268 * there is no PRF, in both cases we cannot generate key material */
269 if (cache->tls_prf_type == MBEDTLS_SSL_TLS_PRF_NONE)
270 {
271 return false;
272 }
273
274 int ret = mbedtls_ssl_tls_prf(cache->tls_prf_type, cache->master_secret,
275 sizeof(cache->master_secret),
276 label, cache->client_server_random,
277 sizeof(cache->client_server_random),
278 ekm, ekm_size);
279
280 if (mbed_ok(ret))
281 {
282 return true;
283 }
284 else
285 {
286 secure_memzero(ekm, session->opt->ekm_size);
287 return false;
288 }
289}
290
291bool
292tls_ctx_set_options(struct tls_root_ctx *ctx, unsigned int ssl_flags)
293{
294 return true;
295}
296
297static const char *
298tls_translate_cipher_name(const char *cipher_name)
299{
300 const tls_cipher_name_pair *pair = tls_get_cipher_name_pair(cipher_name, strlen(cipher_name));
301
302 if (NULL == pair)
303 {
304 /* No translation found, return original */
305 return cipher_name;
306 }
307
308 if (0 != strcmp(cipher_name, pair->iana_name))
309 {
310 /* Deprecated name found, notify user */
311 msg(M_WARN, "Deprecated cipher suite name '%s', please use IANA name '%s'", pair->openssl_name, pair->iana_name);
312 }
313
314 return pair->iana_name;
315}
316
317void
318tls_ctx_restrict_ciphers_tls13(struct tls_root_ctx *ctx, const char *ciphers)
319{
320 if (ciphers == NULL)
321 {
322 /* Nothing to do, return without warning message */
323 return;
324 }
325
326 msg(M_WARN, "mbed TLS does not support setting tls-ciphersuites. "
327 "Ignoring TLS 1.3 cipher list: %s", ciphers);
328}
329
330void
331tls_ctx_restrict_ciphers(struct tls_root_ctx *ctx, const char *ciphers)
332{
333 char *tmp_ciphers, *tmp_ciphers_orig, *token;
334
335 if (NULL == ciphers)
336 {
337 return; /* Nothing to do */
338 }
339
340 ASSERT(NULL != ctx);
341
342 /* Get number of ciphers */
343 int cipher_count = get_num_elements(ciphers, ':');
344
345 /* Allocate an array for them */
346 ALLOC_ARRAY_CLEAR(ctx->allowed_ciphers, int, cipher_count+1)
347
348 /* Parse allowed ciphers, getting IDs */
349 int i = 0;
350 tmp_ciphers_orig = tmp_ciphers = string_alloc(ciphers, NULL);
351
352 token = strtok(tmp_ciphers, ":");
353 while (token)
354 {
355 ctx->allowed_ciphers[i] = mbedtls_ssl_get_ciphersuite_id(
356 tls_translate_cipher_name(token));
357 if (0 != ctx->allowed_ciphers[i])
358 {
359 i++;
360 }
361 token = strtok(NULL, ":");
362 }
363 free(tmp_ciphers_orig);
364}
365
366void
367tls_ctx_set_cert_profile(struct tls_root_ctx *ctx, const char *profile)
368{
369 if (!profile || 0 == strcmp(profile, "legacy")
370 || 0 == strcmp(profile, "insecure"))
371 {
372 ctx->cert_profile = openvpn_x509_crt_profile_legacy;
373 }
374 else if (0 == strcmp(profile, "preferred"))
375 {
376 ctx->cert_profile = openvpn_x509_crt_profile_preferred;
377 }
378 else if (0 == strcmp(profile, "suiteb"))
379 {
380 ctx->cert_profile = openvpn_x509_crt_profile_suiteb;
381 }
382 else
383 {
384 msg(M_FATAL, "ERROR: Invalid cert profile: %s", profile);
385 }
386}
387
388void
389tls_ctx_set_tls_groups(struct tls_root_ctx *ctx, const char *groups)
390{
391 ASSERT(ctx);
392 struct gc_arena gc = gc_new();
393
394 /* Get number of groups and allocate an array in ctx */
395 int groups_count = get_num_elements(groups, ':');
396 ALLOC_ARRAY_CLEAR(ctx->groups, mbedtls_compat_group_id, groups_count + 1)
397
398 /* Parse allowed ciphers, getting IDs */
399 int i = 0;
400 char *tmp_groups = string_alloc(groups, &gc);
401
402 const char *token;
403 while ((token = strsep(&tmp_groups, ":")))
404 {
405 const mbedtls_ecp_curve_info *ci =
406 mbedtls_ecp_curve_info_from_name(token);
407 if (!ci)
408 {
409 msg(M_WARN, "Warning unknown curve/group specified: %s", token);
410 }
411 else
412 {
414 i++;
415 }
416 }
417
418 /* Recent mbedtls versions state that the list of groups must be terminated
419 * with 0. Older versions state that it must be terminated with MBEDTLS_ECP_DP_NONE
420 * which is also 0, so this works either way. */
421 ctx->groups[i] = 0;
422
423 gc_free(&gc);
424}
425
426
427void
428tls_ctx_check_cert_time(const struct tls_root_ctx *ctx)
429{
430 ASSERT(ctx);
431 if (ctx->crt_chain == NULL)
432 {
433 return; /* Nothing to check if there is no certificate */
434 }
435
436 if (mbedtls_x509_time_is_future(&ctx->crt_chain->valid_from))
437 {
438 msg(M_WARN, "WARNING: Your certificate is not yet valid!");
439 }
440
441 if (mbedtls_x509_time_is_past(&ctx->crt_chain->valid_to))
442 {
443 msg(M_WARN, "WARNING: Your certificate has expired!");
444 }
445}
446
447void
448tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file,
449 bool dh_inline)
450{
451 if (dh_inline)
452 {
453 if (!mbed_ok(mbedtls_dhm_parse_dhm(ctx->dhm_ctx,
454 (const unsigned char *) dh_file,
455 strlen(dh_file) + 1)))
456 {
457 msg(M_FATAL, "Cannot read inline DH parameters");
458 }
459 }
460 else
461 {
462 if (!mbed_ok(mbedtls_dhm_parse_dhmfile(ctx->dhm_ctx, dh_file)))
463 {
464 msg(M_FATAL, "Cannot read DH parameters from file %s", dh_file);
465 }
466 }
467
468 msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with " counter_format " bit key",
470}
471
472void
473tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve_name
474 )
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,
486 bool pkcs12_file_inline, 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,
502 bool cert_inline)
503{
504 ASSERT(NULL != ctx);
505
506 if (!ctx->crt_chain)
507 {
508 ALLOC_OBJ_CLEAR(ctx->crt_chain, mbedtls_x509_crt);
509 }
510
511 if (cert_inline)
512 {
513 if (!mbed_ok(mbedtls_x509_crt_parse(ctx->crt_chain,
514 (const unsigned char *)cert_file,
515 strlen(cert_file) + 1)))
516 {
517 msg(M_FATAL, "Cannot load inline certificate file");
518 }
519 }
520 else
521 {
522 if (!mbed_ok(mbedtls_x509_crt_parse_file(ctx->crt_chain, cert_file)))
523 {
524 msg(M_FATAL, "Cannot load certificate file %s", cert_file);
525 }
526 }
527}
528
529int
530tls_ctx_load_priv_file(struct tls_root_ctx *ctx, const char *priv_key_file,
531 bool priv_key_inline)
532{
533 int status;
534 ASSERT(NULL != ctx);
535
536 if (!ctx->priv_key)
537 {
538 ALLOC_OBJ_CLEAR(ctx->priv_key, mbedtls_pk_context);
539 }
540
541 if (priv_key_inline)
542 {
544 (const unsigned char *) priv_key_file,
545 strlen(priv_key_file) + 1, NULL, 0,
546 mbedtls_ctr_drbg_random,
547 rand_ctx_get());
548
549 if (MBEDTLS_ERR_PK_PASSWORD_REQUIRED == status)
550 {
551 char passbuf[512] = {0};
552 pem_password_callback(passbuf, 512, 0, NULL);
554 (const unsigned char *) priv_key_file,
555 strlen(priv_key_file) + 1,
556 (unsigned char *) passbuf,
557 strlen(passbuf),
558 mbedtls_ctr_drbg_random,
559 rand_ctx_get());
560 }
561 }
562 else
563 {
565 priv_key_file,
566 NULL,
567 mbedtls_ctr_drbg_random,
568 rand_ctx_get());
569 if (MBEDTLS_ERR_PK_PASSWORD_REQUIRED == status)
570 {
571 char passbuf[512] = {0};
572 pem_password_callback(passbuf, 512, 0, NULL);
574 priv_key_file, passbuf,
575 mbedtls_ctr_drbg_random,
576 rand_ctx_get());
577 }
578 }
579 if (!mbed_ok(status))
580 {
581#ifdef ENABLE_MANAGEMENT
582 if (management && (MBEDTLS_ERR_PK_PASSWORD_MISMATCH == status))
583 {
585 }
586#endif
587 msg(M_WARN, "Cannot load private key file %s",
588 print_key_filename(priv_key_file, priv_key_inline));
589 return 1;
590 }
591
593 ctx->priv_key,
594 mbedtls_ctr_drbg_random,
595 rand_ctx_get())))
596 {
597 msg(M_WARN, "Private key does not match the certificate");
598 return 1;
599 }
600
601 return 0;
602}
603
622static inline int
623external_pkcs1_sign( void *ctx_voidptr,
624 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
625#if MBEDTLS_VERSION_NUMBER < 0x03020100
626 int mode,
627#endif
628 mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash,
629 unsigned char *sig )
630{
631 struct external_context *const ctx = ctx_voidptr;
632 int rv;
633 uint8_t *to_sign = NULL;
634 size_t asn_len = 0, oid_size = 0;
635 const char *oid = NULL;
636
637 if (NULL == ctx)
638 {
639 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
640 }
641
642#if MBEDTLS_VERSION_NUMBER < 0x03020100
643 if (MBEDTLS_RSA_PRIVATE != mode)
644 {
645 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
646 }
647#endif
648
649 /*
650 * Support a wide range of hashes. TLSv1.1 and before only need SIG_RSA_RAW,
651 * but TLSv1.2 needs the full suite of hashes.
652 *
653 * This code has been taken from mbed TLS pkcs11_sign(), under the GPLv2.0+.
654 */
655 if (md_alg != MBEDTLS_MD_NONE)
656 {
657 const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );
658 if (md_info == NULL)
659 {
660 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
661 }
662
663 if (!mbed_ok(mbedtls_oid_get_oid_by_md( md_alg, &oid, &oid_size )))
664 {
665 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
666 }
667
668 hashlen = mbedtls_md_get_size( md_info );
669 asn_len = 10 + oid_size;
670 }
671
672 if ((SIZE_MAX - hashlen) < asn_len
673 || ctx->signature_length < (asn_len + hashlen))
674 {
675 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
676 }
677
678 ALLOC_ARRAY_CLEAR(to_sign, uint8_t, asn_len + hashlen);
679 uint8_t *p = to_sign;
680 if (md_alg != MBEDTLS_MD_NONE)
681 {
682 /*
683 * DigestInfo ::= SEQUENCE {
684 * digestAlgorithm DigestAlgorithmIdentifier,
685 * digest Digest }
686 *
687 * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
688 *
689 * Digest ::= OCTET STRING
690 */
691 *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
692 *p++ = (unsigned char) ( 0x08 + oid_size + hashlen );
693 *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
694 *p++ = (unsigned char) ( 0x04 + oid_size );
695 *p++ = MBEDTLS_ASN1_OID;
696 *p++ = oid_size & 0xFF;
697 memcpy( p, oid, oid_size );
698 p += oid_size;
699 *p++ = MBEDTLS_ASN1_NULL;
700 *p++ = 0x00;
701 *p++ = MBEDTLS_ASN1_OCTET_STRING;
702 *p++ = hashlen;
703
704 /* Double-check ASN length */
705 ASSERT(asn_len == p - to_sign);
706 }
707
708 /* Copy the hash to be signed */
709 memcpy(p, hash, hashlen);
710
711 /* Call external signature function */
712 if (!ctx->sign(ctx->sign_ctx, to_sign, asn_len + hashlen, sig,
713 ctx->signature_length))
714 {
715 rv = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
716 goto done;
717 }
718
719 rv = 0;
720
721done:
722 free(to_sign);
723 return rv;
724}
725
726static inline size_t
727external_key_len(void *vctx)
728{
729 struct external_context *const ctx = vctx;
730
731 return ctx->signature_length;
732}
733
734int
736 external_sign_func sign_func, void *sign_ctx)
737{
738 ASSERT(NULL != ctx);
739
740 if (ctx->crt_chain == NULL)
741 {
742 msg(M_WARN, "ERROR: external key requires a certificate.");
743 return 1;
744 }
745
746 if (mbedtls_pk_get_type(&ctx->crt_chain->pk) != MBEDTLS_PK_RSA)
747 {
748 msg(M_WARN, "ERROR: external key with mbed TLS requires a "
749 "certificate with an RSA key.");
750 return 1;
751 }
752
753 ctx->external_key.signature_length = mbedtls_pk_get_len(&ctx->crt_chain->pk);
754 ctx->external_key.sign = sign_func;
756
757 ALLOC_OBJ_CLEAR(ctx->priv_key, mbedtls_pk_context);
758 if (!mbed_ok(mbedtls_pk_setup_rsa_alt(ctx->priv_key, &ctx->external_key,
759 NULL, external_pkcs1_sign, external_key_len)))
760 {
761 return 1;
762 }
763
764 return 0;
765}
766
767#ifdef ENABLE_MANAGEMENT
769static bool
770management_sign_func(void *sign_ctx, const void *src, size_t src_len,
771 void *dst, size_t dst_len)
772{
773 bool ret = false;
774 char *src_b64 = NULL;
775 char *dst_b64 = NULL;
776
777 if (!management || (openvpn_base64_encode(src, src_len, &src_b64) <= 0))
778 {
779 goto cleanup;
780 }
781
782 /*
783 * We only support RSA external keys and PKCS1 signatures at the moment
784 * in mbed TLS, so the signature parameter is hardcoded to this encoding
785 */
786 if (!(dst_b64 = management_query_pk_sig(management, src_b64,
787 "RSA_PKCS1_PADDING")))
788 {
789 goto cleanup;
790 }
791
792 if (openvpn_base64_decode(dst_b64, dst, dst_len) != dst_len)
793 {
794 goto cleanup;
795 }
796
797 ret = true;
798cleanup:
799 free(src_b64);
800 free(dst_b64);
801
802 return ret;
803}
804
805int
807{
808 return tls_ctx_use_external_signing_func(ctx, management_sign_func, NULL);
809}
810
811#endif /* ifdef ENABLE_MANAGEMENT */
812
813void
814tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file,
815 bool ca_inline, const char *ca_path, bool tls_server)
816{
817 if (ca_path)
818 {
819 msg(M_FATAL, "ERROR: mbed TLS cannot handle the capath directive");
820 }
821
822 if (ca_file && ca_inline)
823 {
824 if (!mbed_ok(mbedtls_x509_crt_parse(ctx->ca_chain,
825 (const unsigned char *) ca_file,
826 strlen(ca_file) + 1)))
827 {
828 msg(M_FATAL, "Cannot load inline CA certificates");
829 }
830 }
831 else
832 {
833 /* Load CA file for verifying peer supplied certificate */
834 if (!mbed_ok(mbedtls_x509_crt_parse_file(ctx->ca_chain, ca_file)))
835 {
836 msg(M_FATAL, "Cannot load CA certificate file %s", ca_file);
837 }
838 }
839}
840
841void
842tls_ctx_load_extra_certs(struct tls_root_ctx *ctx, const char *extra_certs_file,
843 bool extra_certs_inline)
844{
845 ASSERT(NULL != ctx);
846
847 if (!ctx->crt_chain)
848 {
849 ALLOC_OBJ_CLEAR(ctx->crt_chain, mbedtls_x509_crt);
850 }
851
852 if (extra_certs_inline)
853 {
854 if (!mbed_ok(mbedtls_x509_crt_parse(ctx->crt_chain,
855 (const unsigned char *) extra_certs_file,
856 strlen(extra_certs_file) + 1)))
857 {
858 msg(M_FATAL, "Cannot load inline extra-certs file");
859 }
860 }
861 else
862 {
863 if (!mbed_ok(mbedtls_x509_crt_parse_file(ctx->crt_chain, extra_certs_file)))
864 {
865 msg(M_FATAL, "Cannot load extra-certs file: %s", extra_certs_file);
866 }
867 }
868}
869
870/* **************************************
871 *
872 * Key-state specific functions
873 *
874 ***************************************/
875
876/*
877 * "Endless buffer"
878 */
879
880static inline void
881buf_free_entry(buffer_entry *entry)
882{
883 if (NULL != entry)
884 {
885 free(entry->data);
886 free(entry);
887 }
888}
889
890static void
891buf_free_entries(endless_buffer *buf)
892{
893 while (buf->first_block)
894 {
895 buffer_entry *cur_block = buf->first_block;
896 buf->first_block = cur_block->next_block;
897 buf_free_entry(cur_block);
898 }
899 buf->last_block = NULL;
900}
901
902static int
903endless_buf_read( endless_buffer *in, unsigned char *out, size_t out_len )
904{
905 size_t read_len = 0;
906
907 if (in->first_block == NULL)
908 {
909 return MBEDTLS_ERR_SSL_WANT_READ;
910 }
911
912 while (in->first_block != NULL && read_len < out_len)
913 {
914 int block_len = in->first_block->length - in->data_start;
915 if (block_len <= out_len - read_len)
916 {
917 buffer_entry *cur_entry = in->first_block;
918 memcpy(out + read_len, cur_entry->data + in->data_start,
919 block_len);
920
921 read_len += block_len;
922
923 in->first_block = cur_entry->next_block;
924 in->data_start = 0;
925
926 if (in->first_block == NULL)
927 {
928 in->last_block = NULL;
929 }
930
931 buf_free_entry(cur_entry);
932 }
933 else
934 {
935 memcpy(out + read_len, in->first_block->data + in->data_start,
936 out_len - read_len);
937 in->data_start += out_len - read_len;
938 read_len = out_len;
939 }
940 }
941
942 return read_len;
943}
944
945static int
946endless_buf_write( endless_buffer *out, const unsigned char *in, size_t len )
947{
948 buffer_entry *new_block = malloc(sizeof(buffer_entry));
949 if (NULL == new_block)
950 {
951 return MBEDTLS_ERR_NET_SEND_FAILED;
952 }
953
954 new_block->data = malloc(len);
955 if (NULL == new_block->data)
956 {
957 free(new_block);
958 return MBEDTLS_ERR_NET_SEND_FAILED;
959 }
960
961 new_block->length = len;
962 new_block->next_block = NULL;
963
964 memcpy(new_block->data, in, len);
965
966 if (NULL == out->first_block)
967 {
968 out->first_block = new_block;
969 }
970
971 if (NULL != out->last_block)
972 {
973 out->last_block->next_block = new_block;
974 }
975
976 out->last_block = new_block;
977
978 return len;
979}
980
981static int
982ssl_bio_read( void *ctx, unsigned char *out, size_t out_len)
983{
984 bio_ctx *my_ctx = (bio_ctx *) ctx;
985 return endless_buf_read(&my_ctx->in, out, out_len);
986}
987
988static int
989ssl_bio_write( void *ctx, const unsigned char *in, size_t in_len)
990{
991 bio_ctx *my_ctx = (bio_ctx *) ctx;
992 return endless_buf_write(&my_ctx->out, in, in_len);
993}
994
995static void
996my_debug( void *ctx, int level, const char *file, int line,
997 const char *str )
998{
999 int my_loglevel = (level < 3) ? D_TLS_DEBUG_MED : D_TLS_DEBUG;
1000 msg(my_loglevel, "mbed TLS msg (%s:%d): %s", file, line, str);
1001}
1002
1003/*
1004 * Further personalise the RNG using a hash of the public key
1005 */
1006void
1007tls_ctx_personalise_random(struct tls_root_ctx *ctx)
1008{
1009 static char old_sha256_hash[32] = {0};
1010 unsigned char sha256_hash[32] = {0};
1011 mbedtls_ctr_drbg_context *cd_ctx = rand_ctx_get();
1012
1013 if (NULL != ctx->crt_chain)
1014 {
1015 mbedtls_x509_crt *cert = ctx->crt_chain;
1016
1017 if (!md_full("SHA256", cert->tbs.p, cert->tbs.len, sha256_hash))
1018 {
1019 msg(M_WARN, "WARNING: failed to personalise random");
1020 }
1021
1022 if (0 != memcmp(old_sha256_hash, sha256_hash, sizeof(sha256_hash)))
1023 {
1024 if (!mbed_ok(mbedtls_compat_ctr_drbg_update(cd_ctx, sha256_hash, 32)))
1025 {
1026 msg(M_WARN, "WARNING: failed to personalise random, could not update CTR_DRBG");
1027 }
1028 memcpy(old_sha256_hash, sha256_hash, sizeof(old_sha256_hash));
1029 }
1030 }
1031}
1032
1033int
1034tls_version_max(void)
1035{
1036#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1037 return TLS_VER_1_2;
1038#else /* defined(MBEDTLS_SSL_PROTO_TLS1_2) */
1039 #error "mbedtls is compiled without support for TLS 1.2."
1040#endif /* defined(MBEDTLS_SSL_PROTO_TLS1_2) */
1041}
1042
1051tls_version_to_ssl_version(int tls_ver)
1052{
1053 switch (tls_ver)
1054 {
1055#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1056 case TLS_VER_1_2:
1058#endif
1059
1060#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
1061 case TLS_VER_1_3:
1063#endif
1064
1065 default:
1066 msg(M_FATAL, "%s: invalid or unsupported TLS version %d", __func__, tls_ver);
1068 }
1069}
1070
1071void
1072backend_tls_ctx_reload_crl(struct tls_root_ctx *ctx, const char *crl_file,
1073 bool crl_inline)
1074{
1075 ASSERT(crl_file);
1076
1077 if (ctx->crl == NULL)
1078 {
1079 ALLOC_OBJ_CLEAR(ctx->crl, mbedtls_x509_crl);
1080 }
1081 mbedtls_x509_crl_free(ctx->crl);
1082
1083 if (crl_inline)
1084 {
1085 if (!mbed_ok(mbedtls_x509_crl_parse(ctx->crl,
1086 (const unsigned char *)crl_file,
1087 strlen(crl_file) + 1)))
1088 {
1089 msg(M_WARN, "CRL: cannot parse inline CRL");
1090 goto err;
1091 }
1092 }
1093 else
1094 {
1095 if (!mbed_ok(mbedtls_x509_crl_parse_file(ctx->crl, crl_file)))
1096 {
1097 msg(M_WARN, "CRL: cannot read CRL from file %s", crl_file);
1098 goto err;
1099 }
1100 }
1101 return;
1102
1103err:
1104 mbedtls_x509_crl_free(ctx->crl);
1105}
1106
1107void
1108key_state_ssl_init(struct key_state_ssl *ks_ssl,
1109 const struct tls_root_ctx *ssl_ctx, bool is_server,
1110 struct tls_session *session)
1111{
1112 ASSERT(NULL != ssl_ctx);
1113 ASSERT(ks_ssl);
1114 CLEAR(*ks_ssl);
1115
1116 /* Initialise SSL config */
1117 ALLOC_OBJ_CLEAR(ks_ssl->ssl_config, mbedtls_ssl_config);
1118 mbedtls_ssl_config_init(ks_ssl->ssl_config);
1119 mbedtls_ssl_config_defaults(ks_ssl->ssl_config, ssl_ctx->endpoint,
1120 MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);
1121#ifdef MBEDTLS_DEBUG_C
1122 /* We only want to have mbed TLS generate debug level logging when we would
1123 * also display it.
1124 * In fact mbed TLS 2.25.0 crashes generating debug log if Curve25591 is
1125 * selected for DH (https://github.com/ARMmbed/mbedtls/issues/4208) */
1126 if (session->opt->ssl_flags & SSLF_TLS_DEBUG_ENABLED)
1127 {
1128 mbedtls_debug_set_threshold(3);
1129 }
1130 else
1131 {
1132 mbedtls_debug_set_threshold(2);
1133 }
1134#endif
1135 mbedtls_ssl_conf_dbg(ks_ssl->ssl_config, my_debug, NULL);
1136 mbedtls_ssl_conf_rng(ks_ssl->ssl_config, mbedtls_ctr_drbg_random,
1137 rand_ctx_get());
1138
1139 mbedtls_ssl_conf_cert_profile(ks_ssl->ssl_config, &ssl_ctx->cert_profile);
1140
1141 if (ssl_ctx->allowed_ciphers)
1142 {
1143 mbedtls_ssl_conf_ciphersuites(ks_ssl->ssl_config, ssl_ctx->allowed_ciphers);
1144 }
1145
1146 if (ssl_ctx->groups)
1147 {
1148 mbedtls_ssl_conf_groups(ks_ssl->ssl_config, ssl_ctx->groups);
1149 }
1150
1151 /* Disable TLS renegotiations if the mbedtls library supports that feature.
1152 * OpenVPN's renegotiation creates new SSL sessions and does not depend on
1153 * this feature and TLS renegotiations have been problematic in the past. */
1154#if defined(MBEDTLS_SSL_RENEGOTIATION)
1155 mbedtls_ssl_conf_renegotiation(ks_ssl->ssl_config, MBEDTLS_SSL_RENEGOTIATION_DISABLED);
1156#endif /* MBEDTLS_SSL_RENEGOTIATION */
1157
1158 /* Disable record splitting (for now). OpenVPN assumes records are sent
1159 * unfragmented, and changing that will require thorough review and
1160 * testing. Since OpenVPN is not susceptible to BEAST, we can just
1161 * disable record splitting as a quick fix. */
1162#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
1163 mbedtls_ssl_conf_cbc_record_splitting(ks_ssl->ssl_config,
1164 MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED);
1165#endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
1166
1167 /* Initialise authentication information */
1168 if (is_server)
1169 {
1170 mbed_ok(mbedtls_ssl_conf_dh_param_ctx(ks_ssl->ssl_config,
1171 ssl_ctx->dhm_ctx));
1172 }
1173
1174 mbed_ok(mbedtls_ssl_conf_own_cert(ks_ssl->ssl_config, ssl_ctx->crt_chain,
1175 ssl_ctx->priv_key));
1176
1177 /* Initialise SSL verification */
1178 if (session->opt->ssl_flags & SSLF_CLIENT_CERT_OPTIONAL)
1179 {
1180 mbedtls_ssl_conf_authmode(ks_ssl->ssl_config, MBEDTLS_SSL_VERIFY_OPTIONAL);
1181 }
1182 else if (!(session->opt->ssl_flags & SSLF_CLIENT_CERT_NOT_REQUIRED))
1183 {
1184 mbedtls_ssl_conf_authmode(ks_ssl->ssl_config, MBEDTLS_SSL_VERIFY_REQUIRED);
1185 }
1186 mbedtls_ssl_conf_verify(ks_ssl->ssl_config, verify_callback, session);
1187
1188 /* TODO: mbed TLS does not currently support sending the CA chain to the client */
1189 mbedtls_ssl_conf_ca_chain(ks_ssl->ssl_config, ssl_ctx->ca_chain, ssl_ctx->crl);
1190
1191 /* Initialize minimum TLS version */
1192 {
1193 const int configured_tls_version_min =
1194 (session->opt->ssl_flags >> SSLF_TLS_VERSION_MIN_SHIFT)
1196
1197 /* default to TLS 1.2 */
1199
1200 if (configured_tls_version_min > TLS_VER_UNSPEC)
1201 {
1202 version = tls_version_to_ssl_version(configured_tls_version_min);
1203 }
1204
1206 }
1207
1208 /* Initialize maximum TLS version */
1209 {
1210 const int configured_tls_version_max =
1211 (session->opt->ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT)
1213
1215
1216 if (configured_tls_version_max > TLS_VER_UNSPEC)
1217 {
1218 version = tls_version_to_ssl_version(configured_tls_version_max);
1219 }
1220 else
1221 {
1222 /* Default to tls_version_max(). */
1223 version = tls_version_to_ssl_version(tls_version_max());
1224 }
1225
1227 }
1228
1229#if HAVE_MBEDTLS_SSL_CONF_EXPORT_KEYS_EXT_CB
1230 /* Initialize keying material exporter, old style. */
1231 mbedtls_ssl_conf_export_keys_ext_cb(ks_ssl->ssl_config,
1232 mbedtls_ssl_export_keys_cb, session);
1233#endif
1234
1235 /* Initialise SSL context */
1236 ALLOC_OBJ_CLEAR(ks_ssl->ctx, mbedtls_ssl_context);
1237 mbedtls_ssl_init(ks_ssl->ctx);
1238 mbed_ok(mbedtls_ssl_setup(ks_ssl->ctx, ks_ssl->ssl_config));
1239 /* We do verification in our own callback depending on the
1240 * exact configuration. We do not rely on the default hostname
1241 * verification. */
1242 ASSERT(mbed_ok(mbedtls_ssl_set_hostname(ks_ssl->ctx, NULL)));
1243
1244#if HAVE_MBEDTLS_SSL_SET_EXPORT_KEYS_CB
1245 /* Initialize keying material exporter, new style. */
1246 mbedtls_ssl_set_export_keys_cb(ks_ssl->ctx, mbedtls_ssl_export_keys_cb, session);
1247#endif
1248
1249 /* Initialise BIOs */
1251 mbedtls_ssl_set_bio(ks_ssl->ctx, ks_ssl->bio_ctx, ssl_bio_write,
1252 ssl_bio_read, NULL);
1253}
1254
1255
1256void
1258{
1259 mbedtls_ssl_send_alert_message(ks_ssl->ctx, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1260 MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY);
1261}
1262
1263void
1264key_state_ssl_free(struct key_state_ssl *ks_ssl)
1265{
1266 if (ks_ssl)
1267 {
1268 CLEAR(ks_ssl->tls_key_cache);
1269
1270 if (ks_ssl->ctx)
1271 {
1272 mbedtls_ssl_free(ks_ssl->ctx);
1273 free(ks_ssl->ctx);
1274 }
1275 if (ks_ssl->ssl_config)
1276 {
1277 mbedtls_ssl_config_free(ks_ssl->ssl_config);
1278 free(ks_ssl->ssl_config);
1279 }
1280 if (ks_ssl->bio_ctx)
1281 {
1282 buf_free_entries(&ks_ssl->bio_ctx->in);
1283 buf_free_entries(&ks_ssl->bio_ctx->out);
1284 free(ks_ssl->bio_ctx);
1285 }
1286 CLEAR(*ks_ssl);
1287 }
1288}
1289
1290int
1291key_state_write_plaintext(struct key_state_ssl *ks, struct buffer *buf)
1292{
1293 int retval = 0;
1294
1295 ASSERT(buf);
1296
1297 retval = key_state_write_plaintext_const(ks, BPTR(buf), BLEN(buf));
1298
1299 if (1 == retval)
1300 {
1301 memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */
1302 buf->len = 0;
1303 }
1304
1305 return retval;
1306}
1307
1308int
1309key_state_write_plaintext_const(struct key_state_ssl *ks, const uint8_t *data, int len)
1310{
1311 int retval = 0;
1313
1314 ASSERT(NULL != ks);
1315 ASSERT(len >= 0);
1316
1317 if (0 == len)
1318 {
1319 perf_pop();
1320 return 0;
1321 }
1322
1323 ASSERT(data);
1324
1325 retval = mbedtls_ssl_write(ks->ctx, data, len);
1326
1327 if (retval < 0)
1328 {
1329 perf_pop();
1330 if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval)
1331 {
1332 return 0;
1333 }
1334 mbed_log_err(D_TLS_ERRORS, retval,
1335 "TLS ERROR: write tls_write_plaintext_const error");
1336 return -1;
1337 }
1338
1339 if (retval != len)
1340 {
1342 "TLS ERROR: write tls_write_plaintext_const incomplete %d/%d",
1343 retval, len);
1344 perf_pop();
1345 return -1;
1346 }
1347
1348 /* successful write */
1349 dmsg(D_HANDSHAKE_VERBOSE, "write tls_write_plaintext_const %d bytes", retval);
1350
1351 perf_pop();
1352 return 1;
1353}
1354
1355int
1356key_state_read_ciphertext(struct key_state_ssl *ks, struct buffer *buf)
1357{
1358 int retval = 0;
1359 int len = 0;
1360
1362
1363 ASSERT(NULL != ks);
1364 ASSERT(buf);
1365 ASSERT(buf->len >= 0);
1366
1367 if (buf->len)
1368 {
1369 perf_pop();
1370 return 0;
1371 }
1372
1373 len = buf_forward_capacity(buf);
1374
1375 retval = endless_buf_read(&ks->bio_ctx->out, BPTR(buf), len);
1376
1377 /* Error during read, check for retry error */
1378 if (retval < 0)
1379 {
1380 perf_pop();
1381 if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval)
1382 {
1383 return 0;
1384 }
1385 mbed_log_err(D_TLS_ERRORS, retval, "TLS_ERROR: read tls_read_ciphertext error");
1386 buf->len = 0;
1387 return -1;
1388 }
1389 /* Nothing read, try again */
1390 if (0 == retval)
1391 {
1392 buf->len = 0;
1393 perf_pop();
1394 return 0;
1395 }
1396
1397 /* successful read */
1398 dmsg(D_HANDSHAKE_VERBOSE, "read tls_read_ciphertext %d bytes", retval);
1399 buf->len = retval;
1400 perf_pop();
1401 return 1;
1402}
1403
1404int
1405key_state_write_ciphertext(struct key_state_ssl *ks, struct buffer *buf)
1406{
1407 int retval = 0;
1409
1410 ASSERT(NULL != ks);
1411 ASSERT(buf);
1412 ASSERT(buf->len >= 0);
1413
1414 if (0 == buf->len)
1415 {
1416 perf_pop();
1417 return 0;
1418 }
1419
1420 retval = endless_buf_write(&ks->bio_ctx->in, BPTR(buf), buf->len);
1421
1422 if (retval < 0)
1423 {
1424 perf_pop();
1425
1426 if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval)
1427 {
1428 return 0;
1429 }
1430 mbed_log_err(D_TLS_ERRORS, retval,
1431 "TLS ERROR: write tls_write_ciphertext error");
1432 return -1;
1433 }
1434
1435 if (retval != buf->len)
1436 {
1437 msg(D_TLS_ERRORS, "TLS ERROR: write tls_write_ciphertext incomplete %d/%d",
1438 retval, buf->len);
1439 perf_pop();
1440 return -1;
1441 }
1442
1443 /* successful write */
1444 dmsg(D_HANDSHAKE_VERBOSE, "write tls_write_ciphertext %d bytes", retval);
1445
1446 memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */
1447 buf->len = 0;
1448
1449 perf_pop();
1450 return 1;
1451}
1452
1453int
1454key_state_read_plaintext(struct key_state_ssl *ks, struct buffer *buf)
1455{
1456 int retval = 0;
1457 int len = 0;
1458
1460
1461 ASSERT(NULL != ks);
1462 ASSERT(buf);
1463 ASSERT(buf->len >= 0);
1464
1465 if (buf->len)
1466 {
1467 perf_pop();
1468 return 0;
1469 }
1470
1471 len = buf_forward_capacity(buf);
1472
1473 retval = mbedtls_ssl_read(ks->ctx, BPTR(buf), len);
1474
1475 /* Error during read, check for retry error */
1476 if (retval < 0)
1477 {
1478 if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval)
1479 {
1480 return 0;
1481 }
1482 mbed_log_err(D_TLS_ERRORS, retval, "TLS_ERROR: read tls_read_plaintext error");
1483 buf->len = 0;
1484 perf_pop();
1485 return -1;
1486 }
1487 /* Nothing read, try again */
1488 if (0 == retval)
1489 {
1490 buf->len = 0;
1491 perf_pop();
1492 return 0;
1493 }
1494
1495 /* successful read */
1496 dmsg(D_HANDSHAKE_VERBOSE, "read tls_read_plaintext %d bytes", retval);
1497 buf->len = retval;
1498
1499 perf_pop();
1500 return 1;
1501}
1502
1503/* **************************************
1504 *
1505 * Information functions
1506 *
1507 * Print information for the end user.
1508 *
1509 ***************************************/
1510void
1511print_details(struct key_state_ssl *ks_ssl, const char *prefix)
1512{
1513 const mbedtls_x509_crt *cert;
1514 char s1[256];
1515 char s2[256];
1516
1517 s1[0] = s2[0] = 0;
1518 snprintf(s1, sizeof(s1), "%s %s, cipher %s",
1519 prefix,
1520 mbedtls_ssl_get_version(ks_ssl->ctx),
1521 mbedtls_ssl_get_ciphersuite(ks_ssl->ctx));
1522
1523 cert = mbedtls_ssl_get_peer_cert(ks_ssl->ctx);
1524 if (cert != NULL)
1525 {
1526 snprintf(s2, sizeof(s2), ", %u bit key",
1527 (unsigned int) mbedtls_pk_get_bitlen(&cert->pk));
1528 }
1529
1530 msg(D_HANDSHAKE, "%s%s", s1, s2);
1531}
1532
1533void
1534show_available_tls_ciphers_list(const char *cipher_list,
1535 const char *tls_cert_profile,
1536 bool tls13)
1537{
1538 if (tls13)
1539 {
1540 /* mbed TLS has no TLS 1.3 support currently */
1541 return;
1542 }
1543 struct tls_root_ctx tls_ctx;
1544 const int *ciphers = mbedtls_ssl_list_ciphersuites();
1545
1546 tls_ctx_server_new(&tls_ctx);
1547 tls_ctx_set_cert_profile(&tls_ctx, tls_cert_profile);
1548 tls_ctx_restrict_ciphers(&tls_ctx, cipher_list);
1549
1550 if (tls_ctx.allowed_ciphers)
1551 {
1552 ciphers = tls_ctx.allowed_ciphers;
1553 }
1554
1555 while (*ciphers != 0)
1556 {
1557 printf("%s\n", mbedtls_ssl_get_ciphersuite_name(*ciphers));
1558 ciphers++;
1559 }
1560 tls_ctx_free(&tls_ctx);
1561}
1562
1563void
1565{
1566 const mbedtls_ecp_curve_info *pcurve = mbedtls_ecp_curve_list();
1567
1568 if (NULL == pcurve)
1569 {
1570 msg(M_FATAL, "Cannot retrieve curve list from mbed TLS");
1571 }
1572
1573 /* Print curve list */
1574 printf("Available Elliptic curves, listed in order of preference:\n\n");
1575 while (MBEDTLS_ECP_DP_NONE != pcurve->grp_id)
1576 {
1577 printf("%s\n", pcurve->name);
1578 pcurve++;
1579 }
1580}
1581
1582const char *
1584{
1585 static char mbedtls_version[30];
1586 unsigned int pv = mbedtls_version_get_number();
1587 snprintf(mbedtls_version, sizeof(mbedtls_version), "mbed TLS %d.%d.%d",
1588 (pv>>24)&0xff, (pv>>16)&0xff, (pv>>8)&0xff );
1589 return mbedtls_version;
1590}
1591
1592void
1594{
1595 return; /* no external key provider in mbedTLS build */
1596}
1597
1598#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:91
unsigned char master_secret[48]
Definition ssl_mbedtls.h:94
mbedtls_tls_prf_types tls_prf_type
Definition ssl_mbedtls.h:93
unsigned char client_server_random[64]
Definition ssl_mbedtls.h:92
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