OpenVPN 3 Core Library
Loading...
Searching...
No Matches
sslctx.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12// Wrap the mbed TLS 2.3 SSL API as defined in <mbedtls/ssl.h>
13// so that it can be used as the SSL layer by the OpenVPN core.
14
15#ifndef OPENVPN_MBEDTLS_SSL_SSLCTX_H
16#define OPENVPN_MBEDTLS_SSL_SSLCTX_H
17
18#include <vector>
19#include <string>
20#include <sstream>
21#include <cstring>
22#include <memory>
23
24#include <mbedtls/ssl.h>
25#include <mbedtls/oid.h>
26#include <mbedtls/sha1.h>
27#include <mbedtls/debug.h>
28#include <mbedtls/asn1.h>
29#include <mbedtls/version.h>
30
38#include <openvpn/pki/pkcs1.hpp>
43
50
51// An SSL Context is essentially a configuration that can be used
52// to generate an arbitrary number of actual SSL connections objects.
53
54// MbedTLSContext is an SSL Context implementation that uses the
55// mbed TLS library as a backend.
56
57namespace openvpn {
58
59namespace mbedtls_ctx_private {
60namespace {
61
62#if MBEDTLS_VERSION_NUMBER < 0x03000000
63/*
64 * This is a modified list from mbed TLS ssl_ciphersuites.c.
65 * We removed some SHA1 methods near the top of the list to
66 * avoid Chrome warnings about "obsolete cryptography".
67 * We also removed ECDSA, CCM, PSK, and CAMELLIA algs.
68 *
69 * With mbed TLS 3 or newer we trust the default list of
70 * algorithms in mbed TLS
71 */
72
73
74const int ciphersuites[] = // CONST GLOBAL
75 {
76 /* Selected AES-256 ephemeral suites */
77 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
78 MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
79 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
80 MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
81
82 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
83 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
84
85 /* Selected AES-128 ephemeral suites */
86 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
87 MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
88 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
89 MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
90
91 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
92 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
93
94 /* Selected remaining >= 128-bit ephemeral suites */
95 MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
96 MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
97
98 MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
99
100 /* Selected AES-256 suites */
101 MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384,
102 MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256,
103 MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA,
104 MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384,
105 MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384,
106 MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
107
108 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384,
109 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384,
110 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,
111
112 /* Selected AES-128 suites */
113 MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
114 MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
115 MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
116 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
117 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
118 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
119
120 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
121 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
122 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
123
124 /* Selected remaining >= 128-bit suites */
125 MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA,
126 MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
127
128 MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
129
130 0};
131#endif
132
133/*
134 * X509 cert profiles.
135 */
136
137#ifdef OPENVPN_ALLOW_INSECURE_CERTPROFILE
138// This profile includes the broken MD5 alrogithm.
139// We are going to ship support for this algorithm for a limited
140// amount of time to allow our users to switch to something else
141const mbedtls_x509_crt_profile crt_profile_insecure = // CONST GLOBAL
142 {
143 MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_MD5)
144 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA1)
145 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_RIPEMD160)
146 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA224)
147 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256)
148 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384)
149 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512),
150 0xFFFFFFF, /* Any PK alg */
151 0xFFFFFFF, /* Any curve */
152 1024, /* Minimum size for RSA keys */
153};
154#endif
155
156const mbedtls_x509_crt_profile crt_profile_legacy = // CONST GLOBAL
157 {
158 MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA1)
159 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_RIPEMD160)
160 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA224)
161 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256)
162 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384)
163 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512),
164 0xFFFFFFF, /* Any PK alg */
165 0xFFFFFFF, /* Any curve */
166 1024, /* Minimum size for RSA keys */
167};
168
169const mbedtls_x509_crt_profile crt_profile_preferred = // CONST GLOBAL
170 {
171 MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256)
172 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384)
173 | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512),
174 0xFFFFFFF, /* Any PK alg */
175 0xFFFFFFF, /* Any curve */
176 2048, /* Minimum size for RSA keys */
177};
178} // namespace
179} // namespace mbedtls_ctx_private
180
181// Handle different APIs regarding curves
182#if MBEDTLS_VERSION_NUMBER >= 0x03000000
183using mbedtls_compat_group_id = uint16_t;
184#else
185using mbedtls_compat_group_id = mbedtls_ecp_group_id;
186#endif
187
188static inline mbedtls_compat_group_id
189mbedtls_compat_get_group_id(const mbedtls_ecp_curve_info *curve_info)
190{
191#if MBEDTLS_VERSION_NUMBER >= 0x03000000
192 return curve_info->tls_id;
193#else
194 return curve_info->grp_id;
195#endif
196}
197
198#if MBEDTLS_VERSION_NUMBER < 0x03000000
199static inline void
200mbedtls_ssl_conf_groups(mbedtls_ssl_config *conf, mbedtls_compat_group_id *groups)
201{
202 mbedtls_ssl_conf_curves(conf, groups);
203}
204#endif
205
206// Represents an SSL configuration that can be used
207// to instantiate actual SSL sessions.
209{
210 public:
212
213 enum
214 {
215 MAX_CIPHERTEXT_IN = 64 // maximum number of queued input ciphertext packets
216 };
217
218 // The data needed to construct a MbedTLSContext.
219 class Config : public SSLConfigAPI
220 {
221 friend class MbedTLSContext;
222
223 public:
225
227 : external_pki(nullptr),
229 flags(0),
230 ns_cert_type(NSCert::NONE),
231 tls_version_min(TLSVersion::Type::V1_2),
232 tls_cert_profile(TLSCertProfile::UNDEF),
234 {
235 }
236
238 {
239 return SSLFactoryAPI::Ptr(new MbedTLSContext(this));
240 }
241
242 void set_mode(const Mode &mode_arg) override
243 {
244 mode = mode_arg;
245 }
246
247 const Mode &get_mode() const override
248 {
249 return mode;
250 }
251
252 // if this callback is defined, no private key needs to be loaded
253 void set_external_pki_callback(ExternalPKIBase *external_pki_arg, const std::string &alias) override
254 {
255 external_pki = external_pki_arg;
256 external_pki_alias = alias;
257 }
258
259 void set_session_ticket_handler(TLSSessionTicketBase *session_ticket_handler_arg) override
260 {
261 // fixme -- this method should be implemented for server-side TLS session resumption tickets
262 throw MbedTLSException("set_session_ticket_handler not implemented");
263 }
264
265 void set_client_session_tickets(const bool v) override
266 {
267 // fixme -- this method should be implemented for client-side TLS session resumption tickets
268 throw MbedTLSException("set_client_session_tickets not implemented");
269 }
270
271 void enable_legacy_algorithms(const bool v) override
272 {
273 // We ignore the request to enable legacy as we do not have a runtime
274 // configuration for this
275 }
276
277 void set_sni_handler(SNI::HandlerBase *sni_handler) override
278 {
279 // fixme -- this method should be implemented on the server-side for SNI
280 throw MbedTLSException("set_sni_handler not implemented");
281 }
282
283 void set_sni_name(const std::string &sni_name_arg) override
284 {
285 // fixme -- this method should be implemented on the client-side for SNI
286 throw MbedTLSException("set_sni_name not implemented");
287 }
288
289 void set_cn_reject_handler(CommonNameReject *cn_reject_handler_arg) override
290 {
291 throw MbedTLSException("set_cn_reject_handler not implemented");
292 }
293
294 void set_private_key_password(const std::string &pwd) override
295 {
296 priv_key_pwd = pwd;
297 }
298
299 void load_ca(const std::string &ca_txt, bool strict) override
300 {
302 c->parse(ca_txt, "ca", strict);
303 ca_chain = c;
304 }
305
306 void load_crl(const std::string &crl_txt) override
307 {
309 c->parse(crl_txt);
310 crl_chain = c;
311 }
312
313 void load_cert(const std::string &cert_txt) override
314 {
316 c->parse(cert_txt, "cert", true);
317 crt_chain = c;
318 }
319
320 void load_cert(const std::string &cert_txt, const std::string &extra_certs_txt) override
321 {
323 c->parse(cert_txt, "cert", true);
324 if (!extra_certs_txt.empty())
325 c->parse(extra_certs_txt, "extra-certs", true);
326 crt_chain = c;
327 }
328
329 void load_private_key(const std::string &key_txt) override
330 {
332 auto *mbedrng = get_mbed_random_class();
333 p->parse(key_txt, "config", priv_key_pwd, *mbedrng);
334 priv_key = p;
335 }
336
337 void load_dh(const std::string &dh_txt) override
338 {
340 mydh->parse(dh_txt, "server-config");
341 dh = mydh;
342 }
343
344 std::string extract_ca() const override
345 {
346 if (!ca_chain)
347 return std::string();
348 return ca_chain->extract();
349 }
350
351 std::string extract_crl() const override
352 {
353 if (!crl_chain)
354 return std::string();
355 return crl_chain->extract();
356 }
357
358 std::string extract_cert() const override
359 {
360 if (!crt_chain)
361 return std::string();
362 return crt_chain->extract();
363 }
364
365 std::vector<std::string> extract_extra_certs() const override
366 {
367 if (!crt_chain)
368 return std::vector<std::string>();
369 return crt_chain->extract_extra_certs();
370 }
371
372 std::string extract_private_key() const override
373 {
374 if (!priv_key)
375 return std::string();
376 return priv_key->extract();
377 }
378
379 std::string extract_dh() const override
380 {
381 if (!dh)
382 return std::string();
383 return dh->extract();
384 }
385
387 {
388 if (!priv_key)
389 return PKType::PK_NONE;
390 return priv_key->key_type();
391 }
392
393 size_t private_key_length() const override
394 {
395 if (!priv_key)
396 return 0;
397 return priv_key->key_length();
398 }
399
400 void set_frame(const Frame::Ptr &frame_arg) override
401 {
402 frame = frame_arg;
403 }
404
405 void set_debug_level(const int debug_level) override
406 {
407 ssl_debug_level = debug_level;
408 }
409
410 void set_flags(const unsigned int flags_arg) override
411 {
412 flags = flags_arg;
413 }
414
415 void set_ns_cert_type(const NSCert::Type ns_cert_type_arg) override
416 {
417 ns_cert_type = ns_cert_type_arg;
418 }
419
421 {
423 }
424
425 void set_tls_remote(const std::string &tls_remote_arg) override
426 {
427 tls_remote = tls_remote_arg;
428 }
429
430 void set_tls_version_min(const TLSVersion::Type tvm) override
431 {
432 tls_version_min = tvm;
433 }
434
435 void set_tls_version_max(const TLSVersion::Type tvm) override
436 {
437 }
438
439 void set_tls_version_min_override(const std::string &override) override
440 {
442 }
443
445 {
446 tls_cert_profile = type;
447 }
448
449 virtual void set_tls_cipher_list(const std::string &override)
450 {
451 if (!override.empty())
452 tls_cipher_list = override;
453 }
454
455 virtual void set_tls_ciphersuite_list(const std::string &override)
456 {
457 // mbed TLS does not have TLS 1.3 support
458 }
459
460 virtual void set_tls_groups(const std::string &groups)
461 {
462 if (!groups.empty())
463 tls_groups = groups;
464 }
465
466 void set_tls_cert_profile_override(const std::string &override) override
467 {
469 }
470
471 void set_local_cert_enabled(const bool v) override
472 {
474 }
475
476 void set_x509_track(X509Track::ConfigSet x509_track_config_arg) override
477 {
478 x509_track_config = std::move(x509_track_config_arg);
479 }
480
481 void set_rng(const StrongRandomAPI::Ptr &rng_arg) override
482 {
483 rng = rng_arg;
484 }
485
486 std::string validate_cert(const std::string &cert_txt) const override
487 {
488 MbedTLSPKI::X509Cert::Ptr cert = new MbedTLSPKI::X509Cert(cert_txt, "validation cert", true);
489 return cert_txt; // fixme -- implement parse/re-render semantics
490 }
491
492 std::string validate_cert_list(const std::string &certs_txt) const override
493 {
494 MbedTLSPKI::X509Cert::Ptr cert = new MbedTLSPKI::X509Cert(certs_txt, "validation cert list", true);
495 return certs_txt; // fixme -- implement parse/re-render semantics
496 }
497
498 std::string validate_private_key(const std::string &key_txt) const override
499 {
500 auto *mbedrng = get_mbed_random_class();
501 MbedTLSPKI::PKContext::Ptr pkey = new MbedTLSPKI::PKContext(key_txt, "validation", "", *mbedrng);
502 return key_txt; // fixme -- implement parse/re-render semantics
503 }
504
505 std::string validate_dh(const std::string &dh_txt) const override
506 {
507 MbedTLSPKI::DH::Ptr dh = new MbedTLSPKI::DH(dh_txt, "validation");
508 return dh_txt; // fixme -- implement parse/re-render semantics
509 }
510
511 std::string validate_crl(const std::string &crl_txt) const override
512 {
514 return crl_txt; // fixme -- implement parse/re-render semantics
515 }
516
517 void load(const OptionList &opt, const unsigned int lflags) override
518 {
519 // client/server
520 if (lflags & LF_PARSE_MODE)
521 mode = opt.exists("client") ? Mode(Mode::CLIENT) : Mode(Mode::SERVER);
522
523 // possibly disable peer cert verification
525 && opt.exists("client-cert-not-required"))
527
528 // sni
529 {
530 const std::string name = opt.get_optional("sni", 1, 256);
531 if (!name.empty())
532 set_sni_name(name);
533 }
534
535 // ca
536 {
537 std::string ca_txt = opt.cat("ca");
538 if (lflags & LF_RELAY_MODE)
539 ca_txt += opt.cat("relay-extra-ca");
540 load_ca(ca_txt, true);
541 }
542
543 // CRL
544 {
545 const std::string crl_txt = opt.cat("crl-verify");
546 if (!crl_txt.empty())
547 load_crl(crl_txt);
548 }
549
550 // local cert/key
552 {
553 // cert/extra-certs
554 {
555 const std::string &cert_txt = opt.get("cert", 1, Option::MULTILINE);
556 const std::string ec_txt = opt.cat("extra-certs");
557 load_cert(cert_txt, ec_txt);
558 }
559
560 // private key
561 if (!external_pki)
562 {
563 const std::string &key_txt = opt.get("key", 1, Option::MULTILINE);
564 load_private_key(key_txt);
565 }
566 }
567
568 // DH
569 if (mode.is_server() && opt.exists("dh"))
570 {
571 const std::string &dh_txt = opt.get("dh", 1, Option::MULTILINE);
572 load_dh(dh_txt);
573 }
574
575 // relay mode
576 std::string relay_prefix;
577 if (lflags & LF_RELAY_MODE)
578 relay_prefix = "relay-";
579
580 // parse ns-cert-type
581 ns_cert_type = NSCert::ns_cert_type(opt, relay_prefix);
582
583 // parse remote-cert-x options
584 KUParse::remote_cert_tls(opt, relay_prefix, ku, eku);
585 KUParse::remote_cert_ku(opt, relay_prefix, ku);
586 KUParse::remote_cert_eku(opt, relay_prefix, eku);
587
588 // parse tls-remote
589 tls_remote = opt.get_optional(relay_prefix + "tls-remote", 1, 256);
590
591 // parse verify-x509-name
592 verify_x509_name.init(opt, relay_prefix);
593
594 // parse tls-version-min option
595 {
596#if defined(MBEDTLS_SSL_MAJOR_VERSION_3) && defined(MBEDTLS_SSL_MINOR_VERSION_3)
598#elif defined(MBEDTLS_SSL_MAJOR_VERSION_3) && defined(MBEDTLS_SSL_MINOR_VERSION_2)
600#else
602#endif
603 tls_version_min = TLSVersion::parse_tls_version_min(opt, relay_prefix, maxver);
604 }
605
606 // parse tls-cert-profile
608
609 // Overrides for tls cipher suites
610 if (opt.exists("tls-cipher"))
611 tls_cipher_list = opt.get_optional("tls-cipher", 1, 256);
612
613 if (opt.exists("tls-groups"))
614 tls_groups = opt.get_optional("tls-groups", 1, 256);
615
616 // unsupported cert verification options
617 {
618 }
619 }
620
621#ifdef OPENVPN_JSON_INTERNAL
622 SSLConfigAPI::Ptr json_override(const Json::Value &root, const bool load_cert_key) const override
623 {
624 throw MbedTLSException("json_override not implemented");
625 }
626#endif
627
628 bool is_server() const
629 {
630 return mode.is_server();
631 }
632
633 private:
635 {
636 if (!rng)
637 {
638 throw MbedTLSException("RNG not initialised yet");
639 }
640 auto *mbedrng = dynamic_cast<MbedTLSRandom *>(rng.get());
641 if (!mbedrng)
642 {
643 throw MbedTLSException("RNG needs to be MbedTLSRandom");
644 }
645 return mbedrng;
646 }
647
648
649 const mbedtls_x509_crt_profile *select_crt_profile() const
650 {
652 {
653#ifdef OPENVPN_ALLOW_INSECURE_CERTPROFILE
654 case TLSCertProfile::INSECURE:
655 return &mbedtls_ctx_private::crt_profile_insecure;
656#endif
658 return &mbedtls_ctx_private::crt_profile_legacy;
660 return &mbedtls_ctx_private::crt_profile_preferred;
662 return &mbedtls_x509_crt_profile_suiteb;
663 default:
664 throw MbedTLSException("select_crt_profile: unknown cert profile");
665 }
666 }
667
669
670 protected:
671 MbedTLSPKI::X509Cert::Ptr crt_chain; // local cert chain (including client cert + extra certs)
672 MbedTLSPKI::X509Cert::Ptr ca_chain; // CA chain for remote verification
673
674 private:
675 MbedTLSPKI::X509CRL::Ptr crl_chain; // CRL chain for remote verification
677 std::string priv_key_pwd; // private key password
678 MbedTLSPKI::DH::Ptr dh; // diffie-hellman parameters (only needed in server mode)
683 unsigned int flags; // defined in sslconsts.hpp
685 std::vector<unsigned int> ku; // if defined, peer cert X509 key usage must match one of these values
686 std::string eku; // if defined, peer cert X509 extended key usage must match this OID/string
687 std::string tls_remote;
688 VerifyX509Name verify_x509_name; // --verify-x509-name feature
689 TLSVersion::Type tls_version_min; // minimum TLS version that we will negotiate
691 std::string tls_cipher_list;
692 std::string tls_groups;
695 StrongRandomAPI::Ptr rng; // random data source
696 };
697
698 // Represents an actual SSL session.
699 // Normally instantiated by MbedTLSContext::ssl().
700 class SSL : public SSLAPI
701 {
702 // read/write callback errors
703 enum
704 {
705 // assumes that mbed TLS user-defined errors may start at -0x8000
706 CT_WOULD_BLOCK = -0x8000,
707 CT_INTERNAL_ERROR = -0x8001
708 };
709
710 friend class MbedTLSContext;
711
712 public:
714
715 void start_handshake() override
716 {
717 mbedtls_ssl_handshake(ssl);
718 }
719
720 ssize_t write_cleartext_unbuffered(const void *data, const size_t size) override
721 {
722 const int status = mbedtls_ssl_write(ssl, (const unsigned char *)data, size);
723 if (status < 0)
724 {
725 if (status == CT_WOULD_BLOCK)
727 else if (status == CT_INTERNAL_ERROR)
728 throw MbedTLSException("SSL write: internal error");
729 else
730 throw MbedTLSException("SSL write error", status);
731 }
732 else
733 return status;
734 }
735
736 ssize_t read_cleartext(void *data, const size_t capacity) override
737 {
738 if (!overflow)
739 {
740 const int status = mbedtls_ssl_read(ssl, (unsigned char *)data, capacity);
741 if (status < 0)
742 {
743 if (status == CT_WOULD_BLOCK)
745 else if (status == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
747 else if (status == CT_INTERNAL_ERROR)
748 throw MbedTLSException("SSL read: internal error");
749 else
750 throw MbedTLSException("SSL read error", status);
751 }
752 else
753 return status;
754 }
755 else
756 throw ssl_ciphertext_in_overflow();
757 }
758
759 bool read_cleartext_ready() const override
760 {
761 return !ct_in.empty() || mbedtls_ssl_get_bytes_avail(ssl);
762 }
763
764 void write_ciphertext(const BufferPtr &buf) override
765 {
767 ct_in.write_buf(buf);
768 else
769 overflow = true;
770 }
771
772 void write_ciphertext_unbuffered(const unsigned char *data, const size_t size) override
773 {
775 ct_in.write(data, size);
776 else
777 overflow = true;
778 }
779
780 bool read_ciphertext_ready() const override
781 {
782 return !ct_out.empty();
783 }
784
786 {
787 return ct_out.read_buf();
788 }
789
790 std::string ssl_handshake_details() const override
791 {
792 if (ssl)
793 {
794 const char *ver = mbedtls_ssl_get_version(ssl);
795 const char *cs = mbedtls_ssl_get_ciphersuite(ssl);
796 if (ver && cs)
797 return ver + std::string("/") + cs;
798 }
799 return "";
800 }
801
802 bool export_keying_material(const std::string &label, unsigned char *, size_t size) override
803 {
804 return false; // not implemented in our mbed TLS implementation
805 }
806
807 bool did_full_handshake() override
808 {
809 return false; // fixme -- not implemented
810 }
811
812 const AuthCert::Ptr &auth_cert() const override
813 {
814 return authcert;
815 }
816
817 void mark_no_cache() override
818 {
819 // fixme -- this method should be implemented for client-side TLS session resumption tickets
820 }
821
822 virtual ~SSL()
823 {
824 erase();
825 }
826
827 protected:
828 SSL(MbedTLSContext *ctx, const char *hostname)
829 {
830 clear();
831 try
832 {
833 const Config &c = *ctx->config;
834 int endpoint, status;
835
836 // set pointer back to parent
837 parent = ctx;
838
839 // set client/server mode
840 if (c.mode.is_server())
841 {
842 endpoint = MBEDTLS_SSL_IS_SERVER;
843 authcert.reset(new AuthCert());
844 }
845 else if (c.mode.is_client())
846 endpoint = MBEDTLS_SSL_IS_CLIENT;
847 else
848 throw MbedTLSException("unknown client/server mode");
849
850 // init SSL configuration object
851 sslconf = new mbedtls_ssl_config;
852 mbedtls_ssl_config_init(sslconf);
853 mbedtls_ssl_config_defaults(sslconf,
854 endpoint,
855 MBEDTLS_SSL_TRANSPORT_STREAM,
856 MBEDTLS_SSL_PRESET_DEFAULT);
857
858 // init X509 cert profile
859 mbedtls_ssl_conf_cert_profile(sslconf, c.select_crt_profile());
860
861 // init SSL object
862 ssl = new mbedtls_ssl_context;
863 mbedtls_ssl_init(ssl);
864
865 // set minimum TLS version
866#if MBEDTLS_VERSION_NUMBER > 0x03000000
867 mbedtls_ssl_protocol_version version;
868 switch (c.tls_version_min)
869 {
870 default:
872 version = MBEDTLS_SSL_VERSION_TLS1_2;
873 break;
874
876 version = MBEDTLS_SSL_VERSION_TLS1_3;
877 break;
878 }
879 mbedtls_ssl_conf_min_tls_version(sslconf, version);
880#else
881 int major;
882 int minor;
883 switch (c.tls_version_min)
884 {
885#if defined(MBEDTLS_SSL_MAJOR_VERSION_3) && defined(MBEDTLS_SSL_MINOR_VERSION_1)
887 major = MBEDTLS_SSL_MAJOR_VERSION_3;
888 minor = MBEDTLS_SSL_MINOR_VERSION_1;
889 break;
890#endif
891#if defined(MBEDTLS_SSL_MAJOR_VERSION_3) && defined(MBEDTLS_SSL_MINOR_VERSION_2)
893 major = MBEDTLS_SSL_MAJOR_VERSION_3;
894 minor = MBEDTLS_SSL_MINOR_VERSION_2;
895 break;
896#endif
897#if defined(MBEDTLS_SSL_MAJOR_VERSION_3) && defined(MBEDTLS_SSL_MINOR_VERSION_3)
898 default:
900 major = MBEDTLS_SSL_MAJOR_VERSION_3;
901 minor = MBEDTLS_SSL_MINOR_VERSION_3;
902 break;
903#endif
904 }
905 mbedtls_ssl_conf_min_version(sslconf, major, minor);
906#if 0
907 /* force TLS 1.2 as maximum version (debugging only, disable in production) */
908 /* This is basically is the same as tls-version-max that OpenVPN 2.x has but hardcoded */
909 mbedtls_ssl_conf_max_version(sslconf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
910#endif
911#endif
912
913
914 {
915 // peer must present a valid certificate unless SSLConst::NO_VERIFY_PEER.
916 // Presenting a valid certificate can be made optional by specifying
917 // SSL:Const::PEER_CERT_OPTIONAL
918
919 int authmode;
920
922 authmode = MBEDTLS_SSL_VERIFY_NONE;
924 throw MbedTLSException("Optional peer verification not supported");
925 else
926 authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
927
928 mbedtls_ssl_conf_authmode(sslconf, authmode);
929 }
930
931 // set verify callback
932 mbedtls_ssl_conf_verify(sslconf, c.mode.is_server() ? verify_callback_server : verify_callback_client, this);
933
934 // Notes on SSL resume/renegotiation:
935 // SSL resume on server side is controlled by ssl_set_session_cache.
936 // SSL renegotiation is disabled here via MBEDTLS_SSL_RENEGOTIATION_DISABLED
937 // and ssl_legacy_renegotiation defaults to
938 // MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION. To enable session tickets,
939 // MBEDTLS_SSL_SESSION_TICKETS (compile flag) must be defined
940 // in mbed TLS config.h.
941 mbedtls_ssl_conf_renegotiation(sslconf, MBEDTLS_SSL_RENEGOTIATION_DISABLED);
942
943 if (!c.tls_cipher_list.empty())
944 {
946 }
947 else
948 {
949#if MBEDTLS_VERSION_NUMBER < 0x03000000
950 /* With newer versions we trust the default */
951 mbedtls_ssl_conf_ciphersuites(sslconf, mbedtls_ctx_private::ciphersuites);
952#endif
953 }
954
955 if (!c.tls_groups.empty())
956 {
958 }
959 // set CA chain
960 if (c.ca_chain)
961 mbedtls_ssl_conf_ca_chain(sslconf,
962 c.ca_chain->get(),
963 c.crl_chain ? c.crl_chain->get() : nullptr);
964 else if (!(c.flags & SSLConst::NO_VERIFY_PEER))
965 throw MbedTLSException("CA chain not defined");
966
967 // Set hostname for SNI or if a CA chain is configured
968 // Otherwise set the hostname explicitly to null to avoid
969 // MBEDTLS_ERR_SSL_CERTIFICATE_VERIFICATION_WITHOUT_HOSTNAME
970 bool use_hostname = hostname && ((c.flags & SSLConst::ENABLE_CLIENT_SNI) || c.ca_chain);
971 if (mbedtls_ssl_set_hostname(ssl, use_hostname ? hostname : nullptr))
972 throw MbedTLSException("mbedtls_ssl_set_hostname failed");
973
974 // client cert+key
975 if (c.local_cert_enabled)
976 {
977 if (c.external_pki)
978 {
979 // set our own certificate, supporting chain (i.e. extra-certs), and external private key
980 if (c.crt_chain)
981 {
982 if (mbedtls_pk_get_type(&c.crt_chain.get()->get()->pk) == MBEDTLS_PK_RSA)
983 {
985 mbedtls_ssl_conf_own_cert(sslconf, c.crt_chain->get(), epki_ctx.get());
986 }
987 else
988 {
989 throw MbedTLSException("cert has unsupported type for external pki support");
990 }
991 }
992 else
993 throw MbedTLSException("cert is undefined");
994 }
995 else
996 {
997 // set our own certificate, supporting chain (i.e. extra-certs), and private key
998 if (c.crt_chain && c.priv_key)
999 mbedtls_ssl_conf_own_cert(sslconf, c.crt_chain->get(), c.priv_key->get());
1000 else
1001 throw MbedTLSException("cert and/or private key is undefined");
1002 }
1003 }
1004
1005 // set DH
1006 if (c.dh)
1007 {
1008 status = mbedtls_ssl_conf_dh_param_ctx(sslconf, c.dh->get());
1009 if (status < 0)
1010 throw MbedTLSException("error in ssl_set_dh_param_ctx", status);
1011 }
1012
1013 // configure ciphertext buffers
1016
1017 // set BIO
1018 mbedtls_ssl_set_bio(ssl, this, ct_write_func, ct_read_func, NULL);
1019
1020 // set RNG
1021 if (c.rng)
1022 {
1023 rng = c.rng;
1024 mbedtls_ssl_conf_rng(sslconf, rng_callback, this);
1025 }
1026 else
1027 throw MbedTLSException("RNG not defined");
1028
1029 // set debug callback
1030 if (c.ssl_debug_level)
1031 mbedtls_ssl_conf_dbg(sslconf, dbg_callback, ctx);
1032
1033 /* OpenVPN 2.x disables cbc_record_splitting by default, therefore
1034 * we have to do the same here to keep compatibility.
1035 * If not disabled, this setting will trigger bad behaviours on
1036 * TLS1.0 and possibly on other setups */
1037#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
1038 mbedtls_ssl_conf_cbc_record_splitting(sslconf,
1039 MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED);
1040#endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
1041
1042 // Apply the configuration to the SSL connection object
1043 if (mbedtls_ssl_setup(ssl, sslconf) < 0)
1044 throw MbedTLSException("mbedtls_ssl_setup failed");
1045 }
1046 catch (...)
1047 {
1048 erase();
1049 throw;
1050 }
1051 }
1052
1053 mbedtls_ssl_config *sslconf; // SSL configuration parameters for SSL connection object
1054 std::unique_ptr<int[]> allowed_ciphers;
1055 // must have the same lifetime as sslconf
1056 std::unique_ptr<mbedtls_compat_group_id[]> groups;
1057
1058
1060
1061 private:
1062 void set_mbedtls_cipherlist(const std::string &cipher_list)
1063 {
1064 auto num_ciphers = std::count(cipher_list.begin(), cipher_list.end(), ':') + 1;
1065
1066 allowed_ciphers.reset(new int[num_ciphers + 1]);
1067
1068 std::stringstream cipher_list_ss(cipher_list);
1069 std::string ciphersuite;
1070
1071 int i = 0;
1072 while (std::getline(cipher_list_ss, ciphersuite, ':'))
1073 {
1074 const tls_cipher_name_pair *pair = tls_get_cipher_name_pair(ciphersuite);
1075
1076 if (pair && pair->iana_name != ciphersuite)
1077 {
1078 OVPN_LOG_INFO("mbed TLS -- Deprecated cipher suite name '"
1079 << pair->openssl_name << "' please use IANA name ' "
1080 << pair->iana_name << "'");
1081 }
1082
1083 auto cipher_id = mbedtls_ssl_get_ciphersuite_id(ciphersuite.c_str());
1084 if (cipher_id != 0)
1085 {
1086 allowed_ciphers[i] = cipher_id;
1087 i++;
1088 }
1089 else
1090 {
1091 /* OpenVPN 2.x ignores silently ignores unknown cipher suites with
1092 * mbed TLS. We warn about them in OpenVPN 3.x */
1093 OVPN_LOG_INFO("mbed TLS -- warning ignoring unknown cipher suite '"
1094 << ciphersuite << "' in tls-cipher");
1095 }
1096 }
1097
1098 // Last element needs to be null
1099 allowed_ciphers[i] = 0;
1100 mbedtls_ssl_conf_ciphersuites(sslconf, allowed_ciphers.get());
1101 }
1102
1103 void set_mbedtls_groups(const std::string &tls_groups)
1104 {
1105 auto num_groups = std::count(tls_groups.begin(), tls_groups.end(), ':') + 1;
1106
1107 /* add extra space for sentinel at the end */
1108 groups.reset(new mbedtls_compat_group_id[num_groups + 1]);
1109
1110 std::stringstream groups_ss(tls_groups);
1111 std::string group;
1112
1113 int i = 0;
1114 while (std::getline(groups_ss, group, ':'))
1115 {
1116 const mbedtls_ecp_curve_info *ci = mbedtls_ecp_curve_info_from_name(group.c_str());
1117
1118 if (ci)
1119 {
1121 i++;
1122 }
1123 else
1124 {
1125 OVPN_LOG_INFO("mbed TLS -- warning ignoring unknown group '"
1126 << group << "' in tls-groups");
1127 }
1128 }
1129
1132 }
1133
1134 // cleartext read callback
1135 static int ct_read_func(void *arg, unsigned char *data, size_t length)
1136 {
1137 try
1138 {
1139 SSL *self = (SSL *)arg;
1140 const size_t actual = self->ct_in.read(data, length);
1141 return actual > 0 ? (int)actual : CT_WOULD_BLOCK;
1142 }
1143 catch (...)
1144 {
1145 return CT_INTERNAL_ERROR;
1146 }
1147 }
1148
1149 // cleartext write callback
1150 static int ct_write_func(void *arg, const unsigned char *data, size_t length)
1151 {
1152 try
1153 {
1154 SSL *self = (SSL *)arg;
1155 self->ct_out.write(data, length);
1156 return (int)length;
1157 }
1158 catch (...)
1159 {
1160 return CT_INTERNAL_ERROR;
1161 }
1162 }
1163
1164 // RNG callback -- return random data to mbed TLS
1165 static int rng_callback(void *arg, unsigned char *data, size_t len)
1166 {
1167 SSL *self = (SSL *)arg;
1168 return self->rng->rand_bytes_noexcept(data, len)
1169 ? 0
1170 : -1; // using -1 as a general-purpose mbed TLS error code
1171 }
1172
1173 static void dbg_callback(void *arg, int level, const char *filename, int linenum, const char *text)
1174 {
1175 MbedTLSContext *self = (MbedTLSContext *)arg;
1176 if (level <= self->config->ssl_debug_level)
1177 OPENVPN_LOG_NTNL("mbed TLS[" << filename << ":" << linenum << " " << level << "]: "
1178 << text);
1179 }
1180
1181 void clear()
1182 {
1183 parent = nullptr;
1184 ssl = nullptr;
1185 sslconf = nullptr;
1186 overflow = false;
1187 allowed_ciphers = nullptr;
1188 }
1189
1190 void erase()
1191 {
1192 if (ssl)
1193 {
1194 mbedtls_ssl_free(ssl);
1195 mbedtls_ssl_config_free(sslconf);
1196 delete ssl;
1197 delete sslconf;
1198 }
1199 clear();
1200 }
1201
1202 mbedtls_ssl_context *ssl; // underlying SSL connection object
1203 MbedTLSPKI::PKContext epki_ctx; // external PKI context
1204 RandomAPI::Ptr rng; // random data source
1205 MemQStream ct_in; // write ciphertext to here
1206 MemQStream ct_out; // read ciphertext from here
1209 };
1210
1212
1213 // create a new SSL instance
1214 SSLAPI::Ptr ssl() override
1215 {
1216 return SSL::Ptr(new SSL(this, nullptr));
1217 }
1218
1219 // Get the library context. This currently does not exist for mbed TLS
1221 {
1222 return nullptr;
1223 }
1224
1225 // like ssl() above but verify hostname against cert CommonName and/or SubjectAltName
1226 SSLAPI::Ptr ssl(const std::string *hostname, const std::string *cache_key) override
1227 {
1228 return SSL::Ptr(new SSL(this, hostname ? hostname->c_str() : nullptr));
1229 }
1230
1231 const Mode &mode() const override
1232 {
1233 return config->mode;
1234 }
1235
1237 {
1238 erase();
1239 }
1240
1241 constexpr static bool support_key_material_export()
1242 {
1243 /* mbed TLS 2.18+ can support RFC5705 but the API is painful to use */
1244 return false;
1245 }
1246
1247#ifdef UNIT_TEST
1248 static void load_cert_info_into_authcert(AuthCert &authcert, const std::string &cert_txt)
1249 {
1250 const MbedTLSPKI::X509Cert cert(cert_txt, "MbedTLSContext::load_cert_info_into_authcert", true);
1251
1252 // save the Common Name
1253 authcert.cn = MbedTLSPKI::x509_get_common_name(cert.get());
1254
1255 // save the issuer fingerprint
1256 load_issuer_fingerprint_into_authcert(authcert, cert.get());
1257
1258 // save the leaf cert serial number
1259 load_serial_number_into_authcert(authcert, cert.get());
1260
1261 authcert.defined_ = true;
1262 }
1263#endif
1264
1265 protected:
1267 : config(config_arg)
1268 {
1270 {
1271 // Verify that cert is defined
1272 if (!config->crt_chain)
1273 throw MbedTLSException("cert is undefined");
1274 }
1275 }
1276
1277 private:
1278 size_t key_len() const
1279 {
1280 return mbedtls_pk_get_bitlen(&config->crt_chain->get()->pk) / 8;
1281 }
1282
1283 // ns-cert-type verification
1284
1286 {
1287 return config->ns_cert_type != NSCert::NONE;
1288 }
1289
1290 bool verify_ns_cert_type(const mbedtls_x509_crt *cert) const
1291 {
1292#if MBEDTLS_VERSION_NUMBER < 0x03000000
1294 return bool(cert->ns_cert_type & MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER);
1295 else if (config->ns_cert_type == NSCert::CLIENT)
1296 return bool(cert->ns_cert_type & MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT);
1297 else
1298#endif
1299 return false;
1300 }
1301
1302 // remote-cert-ku verification
1303
1305 {
1306 return config->ku.size() > 0;
1307 }
1308
1309 bool verify_x509_cert_ku(const mbedtls_x509_crt *cert)
1310 {
1312 {
1313 for (std::vector<unsigned int>::const_iterator i = config->ku.begin(); i != config->ku.end(); ++i)
1314 {
1315 if (mbedtls_x509_crt_check_key_usage(cert, *i))
1316 return true;
1317 }
1318 }
1319 return false;
1320 }
1321
1322 // remote-cert-eku verification
1323
1325 {
1326 return !config->eku.empty();
1327 }
1328
1329 bool verify_x509_cert_eku(mbedtls_x509_crt *cert)
1330 {
1332 {
1333 mbedtls_x509_sequence *oid_seq = &cert->ext_key_usage;
1334 while (oid_seq != nullptr)
1335 {
1336 mbedtls_x509_buf *oid = &oid_seq->buf;
1337
1338 // first compare against description
1339 {
1340 const char *oid_str;
1341 const int status = mbedtls_oid_get_extended_key_usage(oid, &oid_str);
1342 if (status >= 0 && config->eku == oid_str)
1343 return true;
1344 }
1345
1346 // next compare against OID numeric string
1347 {
1348 char oid_num_str[256];
1349 const int status = mbedtls_oid_get_numeric_string(oid_num_str, sizeof(oid_num_str), oid);
1350 if (status >= 0 && config->eku == oid_num_str)
1351 return true;
1352 }
1353 oid_seq = oid_seq->next;
1354 }
1355 }
1356 return false;
1357 }
1358
1359 static std::string status_string(const mbedtls_x509_crt *cert, const int depth, const uint32_t *flags)
1360 {
1361 std::ostringstream os;
1362 std::string status_str = "OK";
1363 if (*flags)
1364 status_str = "FAIL -- " + MbedTLSException::mbedtls_verify_flags_errtext(*flags);
1365 os << "VERIFY "
1366 << status_str
1367 << " : depth=" << depth
1368 << std::endl
1369 << cert_info(cert);
1370 return os.str();
1371 }
1372
1373 protected:
1374 static int verify_callback_client(void *arg, mbedtls_x509_crt *cert, int depth, uint32_t *flags)
1375 {
1377 MbedTLSContext *self = ssl->parent;
1378 bool fail = false;
1379
1380 // log status
1382 OVPN_LOG_INFO(status_string(cert, depth, flags));
1383
1384 // notify if connection is happening with an insecurely signed cert.
1385
1386 // mbed TLS 3.0 does not allow the weaker signatures by default and also does not give a
1387 // proper accessor to these fields anymore
1388#if MBEDTLS_VERSION_NUMBER < 0x03000000
1389 if (cert->sig_md == MBEDTLS_MD_MD5)
1390 {
1392 }
1393
1394 if (cert->sig_md == MBEDTLS_MD_SHA1)
1395 {
1397 }
1398#endif
1399
1400 // leaf-cert verification
1401 if (depth == 0)
1402 {
1403 // verify ns-cert-type
1404 if (self->ns_cert_type_defined() && !self->verify_ns_cert_type(cert))
1405 {
1406 OVPN_LOG_INFO("VERIFY FAIL -- bad ns-cert-type in leaf certificate");
1407 fail = true;
1408 }
1409
1410 // verify X509 key usage
1411 if (self->x509_cert_ku_defined() && !self->verify_x509_cert_ku(cert))
1412 {
1413 OVPN_LOG_INFO("VERIFY FAIL -- bad X509 key usage in leaf certificate");
1414 fail = true;
1415 }
1416
1417 // verify X509 extended key usage
1418 if (self->x509_cert_eku_defined() && !self->verify_x509_cert_eku(cert))
1419 {
1420 OVPN_LOG_INFO("VERIFY FAIL -- bad X509 extended key usage in leaf certificate");
1421 fail = true;
1422 }
1423
1424 // verify tls-remote
1425 if (!self->config->tls_remote.empty())
1426 {
1427 const std::string subject = TLSRemote::sanitize_x509_name(MbedTLSPKI::x509_get_subject(cert));
1428 const std::string common_name = TLSRemote::sanitize_common_name(MbedTLSPKI::x509_get_common_name(cert));
1429 TLSRemote::log(self->config->tls_remote, subject, common_name);
1430 if (!TLSRemote::test(self->config->tls_remote, subject, common_name))
1431 {
1432 OVPN_LOG_INFO("VERIFY FAIL -- tls-remote match failed");
1433 fail = true;
1434 }
1435 }
1436
1437 // verify-x509-name
1438 const VerifyX509Name &verify_x509 = self->config->verify_x509_name;
1439 if (verify_x509.get_mode() != VerifyX509Name::VERIFY_X509_NONE)
1440 {
1441 bool res = false;
1442 switch (verify_x509.get_mode())
1443 {
1445 res = verify_x509.verify(MbedTLSPKI::x509_get_subject(cert, true));
1446 break;
1447
1450 res = verify_x509.verify(MbedTLSPKI::x509_get_common_name(cert));
1451 break;
1452
1453 default:
1454 break;
1455 }
1456 if (!res)
1457 {
1458 OVPN_LOG_INFO("VERIFY FAIL -- verify-x509-name failed");
1459 fail = true;
1460 }
1461 }
1462 }
1463
1464 if (fail)
1465 *flags |= MBEDTLS_X509_BADCERT_OTHER;
1466 return 0;
1467 }
1468
1469 static int verify_callback_server(void *arg, mbedtls_x509_crt *cert, int depth, uint32_t *flags)
1470 {
1472 MbedTLSContext *self = ssl->parent;
1473 bool fail = false;
1474
1475 if (depth == 1) // issuer cert
1476 {
1477 // save the issuer cert fingerprint
1478 if (ssl->authcert)
1479 {
1480 if (!load_issuer_fingerprint_into_authcert(*ssl->authcert, cert))
1481 {
1482 OVPN_LOG_INFO("VERIFY FAIL -- SHA1 calculation failed.");
1483 fail = true;
1484 }
1485 }
1486 }
1487 else if (depth == 0) // leaf-cert
1488 {
1489 // verify ns-cert-type
1490 if (self->ns_cert_type_defined() && !self->verify_ns_cert_type(cert))
1491 {
1492 OVPN_LOG_INFO("VERIFY FAIL -- bad ns-cert-type in leaf certificate");
1493 fail = true;
1494 }
1495
1496 // verify X509 key usage
1497 if (self->x509_cert_ku_defined() && !self->verify_x509_cert_ku(cert))
1498 {
1499 OVPN_LOG_INFO("VERIFY FAIL -- bad X509 key usage in leaf certificate");
1500 fail = true;
1501 }
1502
1503 // verify X509 extended key usage
1504 if (self->x509_cert_eku_defined() && !self->verify_x509_cert_eku(cert))
1505 {
1506 OVPN_LOG_INFO("VERIFY FAIL -- bad X509 extended key usage in leaf certificate");
1507 fail = true;
1508 }
1509
1510 if (ssl->authcert)
1511 {
1512 // save the Common Name
1513 ssl->authcert->cn = MbedTLSPKI::x509_get_common_name(cert);
1514
1515 // save the leaf cert serial number
1516 load_serial_number_into_authcert(*ssl->authcert, cert);
1517
1518 ssl->authcert->defined_ = true;
1519 }
1520 }
1521
1522 if (fail)
1523 *flags |= MBEDTLS_X509_BADCERT_OTHER;
1524 return 0;
1525 }
1526
1528
1529 private:
1530 static std::string cert_info(const mbedtls_x509_crt *cert, const char *prefix = nullptr)
1531 {
1532 const size_t buf_size = 4096;
1533 std::unique_ptr<char[]> buf(new char[buf_size]);
1534 const int size = mbedtls_x509_crt_info(buf.get(), buf_size, prefix ? prefix : "", cert);
1535 if (size >= 0)
1536 return std::string(buf.get());
1537 else
1538 return "error rendering cert";
1539 }
1540
1541 void erase()
1542 {
1543 }
1544
1545 static int epki_decrypt(void *arg,
1546#if MBEDTLS_VERSION_NUMBER < 0x03000000
1547 int mode,
1548#endif
1549 size_t *olen,
1550 const unsigned char *input,
1551 unsigned char *output,
1552 size_t output_max_len)
1553 {
1554 OVPN_LOG_INFO("MbedTLSContext::epki_decrypt is unimplemented"
1555 << " output_max_len=" << output_max_len);
1556
1557 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1558 }
1559
1560 static int epki_sign(void *arg,
1561 int (*f_rng)(void *, unsigned char *, size_t),
1562 void *p_rng,
1563#if MBEDTLS_VERSION_NUMBER < 0x03000000
1564 int mode,
1565#endif
1566 mbedtls_md_type_t md_alg,
1567 unsigned int hashlen,
1568 const unsigned char *hash,
1569 unsigned char *sig)
1570 {
1571 MbedTLSContext *self = (MbedTLSContext *)arg;
1572 try
1573 {
1574#if MBEDTLS_VERSION_NUMBER < 0x03000000
1575 if (mode == MBEDTLS_RSA_PRIVATE)
1576#else
1577 if (true)
1578#endif
1579 {
1580 size_t digest_prefix_len = 0;
1581 const unsigned char *digest_prefix = nullptr;
1582
1583 /* get signature type */
1584 switch (md_alg)
1585 {
1586 case MBEDTLS_MD_NONE:
1587 break;
1588 case MBEDTLS_MD_MD5:
1589 digest_prefix = PKCS1::DigestPrefix::MD5;
1590 digest_prefix_len = sizeof(PKCS1::DigestPrefix::MD5);
1591 break;
1592 case MBEDTLS_MD_SHA1:
1593 digest_prefix = PKCS1::DigestPrefix::SHA1;
1594 digest_prefix_len = sizeof(PKCS1::DigestPrefix::SHA1);
1595 break;
1596 case MBEDTLS_MD_SHA256:
1597 digest_prefix = PKCS1::DigestPrefix::SHA256;
1598 digest_prefix_len = sizeof(PKCS1::DigestPrefix::SHA256);
1599 break;
1600 case MBEDTLS_MD_SHA384:
1601 digest_prefix = PKCS1::DigestPrefix::SHA384;
1602 digest_prefix_len = sizeof(PKCS1::DigestPrefix::SHA384);
1603 break;
1604 case MBEDTLS_MD_SHA512:
1605 digest_prefix = PKCS1::DigestPrefix::SHA512;
1606 digest_prefix_len = sizeof(PKCS1::DigestPrefix::SHA512);
1607 break;
1608 default:
1609 OVPN_LOG_INFO("MbedTLSContext::epki_sign unrecognized hash_id"
1610#if MBEDTLS_VERSION_NUMBER < 0x03000000
1611 << "mode=" << mode
1612#endif
1613 << " md_alg=" << md_alg << " hashlen=" << hashlen);
1614 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1615 }
1616
1617 /* concatenate digest prefix with hash */
1618 BufferAllocated from_buf(digest_prefix_len + hashlen);
1619 if (digest_prefix_len)
1620 from_buf.write(digest_prefix, digest_prefix_len);
1621 from_buf.write(hash, hashlen);
1622
1623 /* convert from_buf to base64 */
1624 const std::string from_b64 = base64->encode(from_buf);
1625
1626 /* get signature */
1627 std::string sig_b64;
1628 const bool status = self->config->external_pki->sign(self->config->external_pki_alias, from_b64, sig_b64, "RSA_PKCS1_PADDING", "", "");
1629 if (!status)
1630 throw ssl_external_pki("MbedTLS: could not obtain signature");
1631
1632 /* decode base64 signature to binary */
1633 const size_t len = self->key_len();
1634 Buffer sigbuf(sig, len, false);
1635 base64->decode(sigbuf, sig_b64);
1636
1637 /* verify length */
1638 if (sigbuf.size() != len)
1639 throw ssl_external_pki("mbed TLS: incorrect signature length");
1640
1641 /* success */
1642 return 0;
1643 }
1644 else
1645 {
1646 OVPN_LOG_INFO("MbedTLSContext::epki_sign unrecognized parameters"
1647#if MBEDTLS_VERSION_NUMBER < 0x03000000
1648 << "mode=" << mode
1649#endif
1650 << " md_alg=" << md_alg << " hashlen=" << hashlen);
1651 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1652 }
1653 }
1654 catch (const std::exception &e)
1655 {
1656 OPENVPN_LOG("MbedTLSContext::epki_sign exception: " << e.what());
1657 return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1658 }
1659 }
1660
1661 static size_t epki_key_len(void *arg)
1662 {
1663 MbedTLSContext *self = (MbedTLSContext *)arg;
1664 return self->key_len();
1665 }
1666
1667 static void load_serial_number_into_authcert(AuthCert &authcert, const mbedtls_x509_crt *cert)
1668 {
1669 const mbedtls_x509_buf *s = &cert->serial;
1670 if (s->len > 0 && s->len <= authcert.serial.size())
1671 {
1672 const size_t offset = authcert.serial.size() - s->len;
1673 std::memset(authcert.serial.number(), 0, offset);
1674 std::memcpy(authcert.serial.number() + offset, s->p, s->len);
1675 }
1676 }
1677
1678 static bool load_issuer_fingerprint_into_authcert(AuthCert &authcert, const mbedtls_x509_crt *cert)
1679 {
1680 const int SHA_DIGEST_LEN = 20;
1681 static_assert(sizeof(AuthCert::issuer_fp) == SHA_DIGEST_LEN, "size inconsistency");
1682#if MBEDTLS_VERSION_NUMBER < 0x02070000
1683 // mbed TLS 2.7.0 and newer deprecates mbedtls_sha1()
1684 // in favour of mbedtls_sha1_ret().
1685
1686 // We support for older mbed TLS versions
1687 // to be able to build on Debian 9 and Ubuntu 16.
1688 mbedtls_sha1(cert->raw.p, cert->raw.len, authcert->issuer_fp);
1689#elif MBEDTLS_VERSION_NUMBER < 0x03000000
1690 if (mbedtls_sha1_ret(cert->raw.p, cert->raw.len, authcert.issuer_fp))
1691 return false;
1692#else
1693 // mbedtls_sha1_ret is renamed to mbedtls_sha1 in 3.0
1694 if (mbedtls_sha1(cert->raw.p, cert->raw.len, authcert.issuer_fp))
1695 return false;
1696#endif
1697 return true;
1698 }
1699};
1700
1701inline const std::string get_ssl_library_version()
1702{
1703 unsigned int ver = mbedtls_version_get_number();
1704 std::string version = "mbed TLS "
1705 + std::to_string((ver >> 24) & 0xff)
1706 + "." + std::to_string((ver >> 16) & 0xff)
1707 + "." + std::to_string((ver >> 8) & 0xff);
1708
1709 return version;
1710}
1711} // namespace openvpn
1712
1713#endif
const std::uint8_t * number() const
Definition authcert.hpp:235
static constexpr size_t size()
Definition authcert.hpp:245
std::string cn
Definition authcert.hpp:522
std::uint8_t issuer_fp[20]
Definition authcert.hpp:524
std::string encode(const V &data) const
Definition base64.hpp:139
size_t decode(void *data, size_t len, const std::string &str) const
Definition base64.hpp:186
size_t size() const
Returns the size of the buffer in T objects.
Definition buffer.hpp:1242
void write(const T *data, const size_t size)
Write data to the buffer.
Definition buffer.hpp:1563
virtual bool sign(const std::string &alias, const std::string &data, std::string &sig, const std::string &algorithm, const std::string &hashalg, const std::string &saltlen)=0
std::string validate_dh(const std::string &dh_txt) const override
Definition sslctx.hpp:505
void set_private_key_password(const std::string &pwd) override
Definition sslctx.hpp:294
void set_tls_version_min_override(const std::string &override) override
Definition sslctx.hpp:439
SSLFactoryAPI::Ptr new_factory() override
Definition sslctx.hpp:237
StrongRandomAPI::Ptr rng
Definition sslctx.hpp:695
MbedTLSPKI::PKContext::Ptr priv_key
Definition sslctx.hpp:676
void set_external_pki_callback(ExternalPKIBase *external_pki_arg, const std::string &alias) override
Definition sslctx.hpp:253
std::string validate_crl(const std::string &crl_txt) const override
Definition sslctx.hpp:511
void set_client_session_tickets(const bool v) override
Definition sslctx.hpp:265
MbedTLSPKI::DH::Ptr dh
Definition sslctx.hpp:678
void set_ns_cert_type(const NSCert::Type ns_cert_type_arg) override
Definition sslctx.hpp:415
void set_tls_version_min(const TLSVersion::Type tvm) override
Definition sslctx.hpp:430
const Mode & get_mode() const override
Definition sslctx.hpp:247
void enable_legacy_algorithms(const bool v) override
Definition sslctx.hpp:271
void set_tls_cert_profile(const TLSCertProfile::Type type) override
Definition sslctx.hpp:444
void set_rng(const StrongRandomAPI::Ptr &rng_arg) override
Definition sslctx.hpp:481
const mbedtls_x509_crt_profile * select_crt_profile() const
Definition sslctx.hpp:649
void set_tls_cert_profile_override(const std::string &override) override
Definition sslctx.hpp:466
void load_cert(const std::string &cert_txt) override
Definition sslctx.hpp:313
ExternalPKIBase * external_pki
Definition sslctx.hpp:679
std::string extract_private_key() const override
Definition sslctx.hpp:372
void set_tls_remote(const std::string &tls_remote_arg) override
Definition sslctx.hpp:425
void load_ca(const std::string &ca_txt, bool strict) override
Definition sslctx.hpp:299
std::string validate_cert_list(const std::string &certs_txt) const override
Definition sslctx.hpp:492
virtual void set_tls_ciphersuite_list(const std::string &override)
Definition sslctx.hpp:455
void set_session_ticket_handler(TLSSessionTicketBase *session_ticket_handler_arg) override
Definition sslctx.hpp:259
void load_private_key(const std::string &key_txt) override
Definition sslctx.hpp:329
std::string validate_cert(const std::string &cert_txt) const override
Definition sslctx.hpp:486
std::string extract_crl() const override
Definition sslctx.hpp:351
TLSCertProfile::Type tls_cert_profile
Definition sslctx.hpp:690
virtual void set_tls_cipher_list(const std::string &override)
Definition sslctx.hpp:449
void set_cn_reject_handler(CommonNameReject *cn_reject_handler_arg) override
Definition sslctx.hpp:289
void set_tls_version_max(const TLSVersion::Type tvm) override
Definition sslctx.hpp:435
void load_dh(const std::string &dh_txt) override
Definition sslctx.hpp:337
MbedTLSPKI::X509CRL::Ptr crl_chain
Definition sslctx.hpp:675
void load_cert(const std::string &cert_txt, const std::string &extra_certs_txt) override
Definition sslctx.hpp:320
void set_x509_track(X509Track::ConfigSet x509_track_config_arg) override
Definition sslctx.hpp:476
std::vector< std::string > extract_extra_certs() const override
Definition sslctx.hpp:365
std::string extract_cert() const override
Definition sslctx.hpp:358
std::string validate_private_key(const std::string &key_txt) const override
Definition sslctx.hpp:498
void load_crl(const std::string &crl_txt) override
Definition sslctx.hpp:306
void set_flags(const unsigned int flags_arg) override
Definition sslctx.hpp:410
MbedTLSPKI::X509Cert::Ptr crt_chain
Definition sslctx.hpp:671
VerifyX509Name verify_x509_name
Definition sslctx.hpp:688
void set_sni_handler(SNI::HandlerBase *sni_handler) override
Definition sslctx.hpp:277
void set_frame(const Frame::Ptr &frame_arg) override
Definition sslctx.hpp:400
X509Track::ConfigSet x509_track_config
Definition sslctx.hpp:693
std::vector< unsigned int > ku
Definition sslctx.hpp:685
MbedTLSRandom * get_mbed_random_class() const
Definition sslctx.hpp:634
void set_sni_name(const std::string &sni_name_arg) override
Definition sslctx.hpp:283
PKType::Type private_key_type() const override
Definition sslctx.hpp:386
void set_remote_cert_tls(const KUParse::TLSWebType wt) override
Definition sslctx.hpp:420
MbedTLSPKI::X509Cert::Ptr ca_chain
Definition sslctx.hpp:672
std::string extract_dh() const override
Definition sslctx.hpp:379
void set_debug_level(const int debug_level) override
Definition sslctx.hpp:405
void set_mode(const Mode &mode_arg) override
Definition sslctx.hpp:242
virtual void set_tls_groups(const std::string &groups)
Definition sslctx.hpp:460
TLSVersion::Type tls_version_min
Definition sslctx.hpp:689
void load(const OptionList &opt, const unsigned int lflags) override
Definition sslctx.hpp:517
size_t private_key_length() const override
Definition sslctx.hpp:393
void set_local_cert_enabled(const bool v) override
Definition sslctx.hpp:471
std::string extract_ca() const override
Definition sslctx.hpp:344
MbedTLSContext * parent
Hold the array that is used for setting the curves.
Definition sslctx.hpp:1059
ssize_t read_cleartext(void *data, const size_t capacity) override
Definition sslctx.hpp:736
std::unique_ptr< int[]> allowed_ciphers
Definition sslctx.hpp:1054
void write_ciphertext_unbuffered(const unsigned char *data, const size_t size) override
Definition sslctx.hpp:772
mbedtls_ssl_config * sslconf
Definition sslctx.hpp:1053
static int ct_write_func(void *arg, const unsigned char *data, size_t length)
Definition sslctx.hpp:1150
void set_mbedtls_groups(const std::string &tls_groups)
Definition sslctx.hpp:1103
void start_handshake() override
Definition sslctx.hpp:715
ssize_t write_cleartext_unbuffered(const void *data, const size_t size) override
Definition sslctx.hpp:720
void set_mbedtls_cipherlist(const std::string &cipher_list)
Definition sslctx.hpp:1062
MbedTLSPKI::PKContext epki_ctx
Definition sslctx.hpp:1203
void write_ciphertext(const BufferPtr &buf) override
Definition sslctx.hpp:764
std::unique_ptr< mbedtls_compat_group_id[]> groups
Hold the array that is used for setting the allowed ciphers.
Definition sslctx.hpp:1056
bool export_keying_material(const std::string &label, unsigned char *, size_t size) override
Definition sslctx.hpp:802
SSL(MbedTLSContext *ctx, const char *hostname)
Definition sslctx.hpp:828
const AuthCert::Ptr & auth_cert() const override
Definition sslctx.hpp:812
static int rng_callback(void *arg, unsigned char *data, size_t len)
Definition sslctx.hpp:1165
static void dbg_callback(void *arg, int level, const char *filename, int linenum, const char *text)
Definition sslctx.hpp:1173
bool read_ciphertext_ready() const override
Definition sslctx.hpp:780
mbedtls_ssl_context * ssl
Definition sslctx.hpp:1202
static int ct_read_func(void *arg, unsigned char *data, size_t length)
Definition sslctx.hpp:1135
bool did_full_handshake() override
Definition sslctx.hpp:807
bool read_cleartext_ready() const override
Definition sslctx.hpp:759
std::string ssl_handshake_details() const override
Definition sslctx.hpp:790
BufferPtr read_ciphertext() override
Definition sslctx.hpp:785
void mark_no_cache() override
Definition sslctx.hpp:817
static void load_serial_number_into_authcert(AuthCert &authcert, const mbedtls_x509_crt *cert)
Definition sslctx.hpp:1667
bool x509_cert_ku_defined() const
Definition sslctx.hpp:1304
SSLAPI::Ptr ssl() override
Definition sslctx.hpp:1214
bool x509_cert_eku_defined() const
Definition sslctx.hpp:1324
bool verify_ns_cert_type(const mbedtls_x509_crt *cert) const
Definition sslctx.hpp:1290
static int verify_callback_server(void *arg, mbedtls_x509_crt *cert, int depth, uint32_t *flags)
Definition sslctx.hpp:1469
bool verify_x509_cert_ku(const mbedtls_x509_crt *cert)
Definition sslctx.hpp:1309
MbedTLSContext(Config *config_arg)
Definition sslctx.hpp:1266
static constexpr bool support_key_material_export()
Definition sslctx.hpp:1241
static int verify_callback_client(void *arg, mbedtls_x509_crt *cert, int depth, uint32_t *flags)
Definition sslctx.hpp:1374
SSLLib::Ctx libctx() override
Definition sslctx.hpp:1220
const Mode & mode() const override
Definition sslctx.hpp:1231
bool ns_cert_type_defined() const
Definition sslctx.hpp:1285
static int epki_decrypt(void *arg, int mode, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len)
Definition sslctx.hpp:1545
SSLAPI::Ptr ssl(const std::string *hostname, const std::string *cache_key) override
Definition sslctx.hpp:1226
static int epki_sign(void *arg, int(*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, unsigned char *sig)
Definition sslctx.hpp:1560
static bool load_issuer_fingerprint_into_authcert(AuthCert &authcert, const mbedtls_x509_crt *cert)
Definition sslctx.hpp:1678
RCPtr< MbedTLSContext > Ptr
Definition sslctx.hpp:211
bool verify_x509_cert_eku(mbedtls_x509_crt *cert)
Definition sslctx.hpp:1329
size_t key_len() const
Definition sslctx.hpp:1278
static size_t epki_key_len(void *arg)
Definition sslctx.hpp:1661
static std::string cert_info(const mbedtls_x509_crt *cert, const char *prefix=nullptr)
Definition sslctx.hpp:1530
static std::string status_string(const mbedtls_x509_crt *cert, const int depth, const uint32_t *flags)
Definition sslctx.hpp:1359
static std::string mbedtls_verify_flags_errtext(const uint32_t flags)
Definition error.hpp:102
void epki_enable(void *arg, mbedtls_pk_rsa_alt_decrypt_func epki_decrypt, mbedtls_pk_rsa_alt_sign_func epki_sign, mbedtls_pk_rsa_alt_key_len_func epki_key_len)
Definition pkctx.hpp:122
mbedtls_pk_context * get() const
Definition pkctx.hpp:133
bool empty() const
Definition memq.hpp:37
size_t size() const
Definition memq.hpp:32
BufferPtr read_buf()
Definition memq.hpp:60
void write_buf(const BufferPtr &bp)
Definition memq.hpp:54
void set_frame(const Frame::Ptr &frame)
void write(const unsigned char *data, size_t size)
size_t read(unsigned char *data, size_t len)
bool is_server() const
Definition mode.hpp:36
bool is_client() const
Definition mode.hpp:40
std::string get_optional(const std::string &name, size_t index, const size_t max_len) const
Definition options.hpp:1342
std::string cat(const std::string &name) const
Definition options.hpp:1286
const Option & get(const std::string &name) const
Definition options.hpp:1254
bool exists(const std::string &name) const
Definition options.hpp:1325
The smart pointer class.
Definition rc.hpp:119
void reset() noexcept
Points this RCPtr<T> to nullptr safely.
Definition rc.hpp:290
T * get() const noexcept
Returns the raw pointer to the object T, or nullptr.
Definition rc.hpp:321
virtual bool rand_bytes_noexcept(unsigned char *buf, size_t size)=0
Fill a buffer with random bytes without throwing exceptions.
uint32_t tls_warnings
Definition sslapi.hpp:79
RCPtr< SSLFactoryAPI > Ptr
Definition sslapi.hpp:91
void init(const OptionList &opt, const std::string &relay_prefix)
bool verify(const std::string &value) const
#define OPENVPN_LOG_NTNL(args)
#define OPENVPN_LOG(args)
#define OVPN_LOG_INFO(args)
Definition logger.hpp:224
static int mbedtls_x509_crt_has_ext_type(const mbedtls_x509_crt *crt, int ext_type)
#define MBEDTLS_OID_X509_EXT_EXTENDED_KEY_USAGE
void remote_cert_ku(const OptionList &opt, const std::string &relay_prefix, std::vector< unsigned int > &ku)
Definition kuparse.hpp:90
void remote_cert_tls(const TLSWebType wt, std::vector< unsigned int > &ku, std::string &eku)
Definition kuparse.hpp:33
void remote_cert_eku(const OptionList &opt, const std::string &relay_prefix, std::string &eku)
Definition kuparse.hpp:118
static std::string x509_get_common_name(const mbedtls_x509_crt *cert)
static std::string x509_get_subject(const mbedtls_x509_crt *cert, bool new_format=false)
Type ns_cert_type(const std::string &ct)
Definition nscert.hpp:31
void apply_override(Type &type, const std::string &override)
Type default_if_undef(const Type type)
Type parse_tls_cert_profile(const std::string &profile_name)
std::string sanitize_x509_name(const std::string &str)
bool test(const std::string &tls_remote, const std::string &subject, const std::string &common_name)
std::string sanitize_common_name(const std::string &str)
void log(const std::string &tls_remote, const std::string &subject, const std::string &common_name)
void apply_override(Type &tvm, const std::string &override)
Definition tlsver.hpp:89
Type parse_tls_version_min(const std::string &ver, const bool or_highest, const Type max_version)
Definition tlsver.hpp:57
static mbedtls_compat_group_id mbedtls_compat_get_group_id(const mbedtls_ecp_curve_info *curve_info)
Definition sslctx.hpp:189
const tls_cipher_name_pair * tls_get_cipher_name_pair(const std::string &ciphername)
const Base64 * base64
Definition base64.hpp:299
SSLFactoryAPI::ssl_external_pki ssl_external_pki
Definition extpki.hpp:26
static void mbedtls_ssl_conf_groups(mbedtls_ssl_config *conf, mbedtls_compat_group_id *groups)
Definition sslctx.hpp:200
mbedtls_ecp_group_id mbedtls_compat_group_id
Definition sslctx.hpp:185
const std::string get_ssl_library_version()
Definition sslctx.hpp:1701
const std::string cert_txt
reroute_gw flags
std::ostringstream os
static const char * input[]