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