Squashed 'Sources/OpenVPNAdapter/Libraries/Vendors/openvpn/' changes from daf575ff50..275cf80efb

275cf80efb mac/tuncli: Don't take address of temporary error.
1406187bfc tun/win/tunutil: Don't auto& a temporary iterator.
fe7f984c5d ip/ping6: Use _WIN32, not _MSC_VER (to fix MinGW).
03a906771e win: add OpenSSL as solution configuration
89cc11b300 win: enable building Windows client with OpenSSL
febb24e7d9 openssl/compat.hpp: remove functions already defined in OpenSSL
0833eb1f76 linux/tunsetup: Fix missing asio/errinfo declaration
d54b742910 linux: Improve cpu_time() using glibc/kernel methods
a55fe2b554 tests: Added unit test for linux/cputime.hpp
e33a00e6de [OVPN3-431] agent: Wintun support for agent
42592eb1b1 appveyor: initial commit
3e3f2078e6 win: rename env var in project file
a2496a3616 Wintun: experimental support
58a7866b45 build script: added OPENSSL_DIST parameter to specify a custom OpenSSL build
288ea0277e OpenSSLContext: SSL_CTX_set_ecdh_auto() becomes a no-op in OpenSSL 1.1, so #ifdef out to avoid compiler warnings
3ef5059fa6 TLSSessionTicketBase: removed the ERROR symbol from a local enum in case it conflicts with a global preprocessor symbol
3364ed76b8 TLSSessionTicketBase: removed trailing comma from Status enum
025c7bad88 mbedtls/sslctx: Fix missing override in virtual methods
6cb3243681 mbedTLS: ssl() method accepting hostname should check if it is null
ca31da7d28 bio_memq_stream.hpp: fixed multi-thread race (introduced with OpenSSL 1.1 support) using init_static() approach
2deb402223 OpenSSLContext::tls_ticket_key_callback: get self with SSL_get_ex_data instead of ssl->ctx->app_verify_arg
eec139a100 MSF::find: renamed template type names to avoid conflict with preprocessor symbol (ITER) in test/ssl/proto.cpp
1024d37f33 str_neq: fixed bug where neq was not initialized
c00b6f6302 Listen::List: refactored and extended expand_ports()
448c549a0b cpu_time(): added bool thread parameter to return CPU time of current thread (instead of process)
868801d7d9 Linux library: added cpu_time() method to return the CPU time of the current process
964d2cd428 SSL layer: added did_full_handshake() method and implemented for OpenSSL
dd18d6c806 crypto::str_neq: use atomic_thread_fence(std::memory_order_acq_rel) instead of OPENVPN_COMPILER_FENCE
6a30af9528 OpenSSLSessionCache: use map instead of unordered_map
3ecbcbc81b OptionList: fixed compile errors that occur when get_num<T>() is used with a const type
72e9f858e4 SSL: added SSLConst::PEER_CERT_OPTIONAL flag and implemented for OpenSSL
33f15c8840 OpenSSL: use OPENSSL_VERSION_NUMBER instead of SSLEAY_VERSION_NUMBER
cadb712ea9 ProfileMerge: added "static-key" to is_fileref_directive()
85befa316a TLS session tickets: work around an issue in OpenSSL session ticket keying callback
f43c4c1440 TLSSessionTicketBase: misc fixes/enhancements
c5f4d59d39 OpenSSLContext: added missing X509_free() to rebuild_authcert()
658fcc50eb OptionList: added get_num methods with min/max but no default
162eeaa485 SSL layer: added RFC 5077 TLS session resumption ticket support
e0a821ddd6 OpenSSLContext: use C++11 member initializers
1ea5acce3c OpenSSLContext: minor changes to handshake_details()
74c0a4f995 string: added copy_fill() method
3e5921c06d AuthCert: added is_uninitialized() method
3d6b6b2319 library: added convenience method MSF::find() for maps/sets
18f5f4d1b5 SSLConfigAPI: remove set_enable_renegotiation()
18dcfd616c Added crypto::str_neq() function for securely comparing variable-length strings
4fc5725b9e RunContext: added get_servers() method
ae22f155fd server: determine when server-side session ID should be preserved on soon-to-be-closed connections
5e34759d50 client: HALT/RESTART message was not properly purging the Session ID when required
e1647eb407 Fix builds with GCC 4.8 compilers
b55f78dd1d test_sitnl.cpp: account for old iptools output
236d39258b Allow overriding DEP_DIR by environment variable
d56e049ea4 Refactor dependencies to be in a cmake script
e9dc75ec90 sitnl: add unit tests
faad8454be sitnl: pick the best gw by longest prefix and lowest metric
dfcc4bc437 [OVPN3-354] cli.cpp: support for round-robin DNS and redirect gw
8a502f3b61 [OVPN3-354] tun linux: support for round-robin DNS and redirect gw
c9315c7dc1 gwnetlink.hpp: specify destination when looking for gateway
89f091daf0 sitnl: implement interface filtering when looking for gateway
220de072a2 sitnl: support for multipart messages
5771dfc0ee transport: remove ip_hole_punch API
d448b4a7db tun/builder/client.hpp: use "override" method specifier
d85e92621d Make reproducible builds possible
7150f72e09 tun: remove code duplications in Linux tun implementations
8112f0cd7c [OVPN3-378] cli: support for TunBuilder API
6f0e9f6388 Fix Asio 0003 patch.
964662bacb Add /bigobj to build.py
74e40a8907 Upgrade ASIO to 0.13.0
a2713ce1f6 PureTLS: enable SNI by default when configuring client
19a44dbdda Merge branch 'qa'
a5fdf43726 InitProcess: comment clarification that crypto_init declaration causes SSL library init when instantiated
dec3bc140e OpenSSL: Revert a commit that breaks OpenSSL initialization
16a4e3d4a7 [OVPN3-405] asio: A quick fix for incorrect error message encoding
aa785c30c1 Fix Base64::UCharWrap compiler warnings
51a1469e6b Merge various fixes
218cfa39cb Explicitly disable TAP support when parsing configurations
3a0e768ecd Explicitly disable any potential TAP support
aba98471fc Fix base64 unit test with mbedtls and windows
9f84174f0b Add unit tests for Base64
017bc545ce Add base64 decode for void* data
452a353b2d Fix lzo build script to use it as dependency for the unit tests
dfdd528dc1 Convert unit test to Googletest
bd9ee482e6 Add copyright header to test_comp
059f20f2b2 Move compression unit test from common to core repository
5a024cde5c Added Snappy corpus for testing compression/decompression.
ec4d400933 Add compatibility functions for OpenSSL 1.1.0
9768562a01 OpenSSL 1.1: Add argument to external sign to specify algorithm
1bbd2cc78c OpenSSL 1.1: Replace RSA_F_RSA_EAY_PRIVATE_ENCRYPT with Openssl variant
c959a3cff0 OpenSSL 1.1: Replace remaining direct access to members
4307f024ca OpenSSL 1.1: And missing remaining compat implementations
3385c45151 OpenSSL 1.1: Use opaque pointer for HMAC_CTX
f29453f4ca OpenSSL 1.1: Add compat includes for HMAC
c107a1f6ab OpenSSL 1.1: Remove support for OpenSSL older than 1.0.0
024a10adc2 OpenSSL 1.1: Use EVP_MD_ctx as opaque pointer
35d82906c4 OpenSSL 1.1: Change EVP_CIPHER ctx field to pointer
ebf4b7e87d OpenSSL 1.1: Use X509_digest to get certificate digest
7d3e5d02f2 OpenSSL 1.1: Use SSL_get_ex_data instead of direct access
8717f822ca OpenSSL 1.1: Replace ctx->current with X509_STORE_CTX_get_current_cert
67fbe1ab3f OpenSSL 1.1: Use X509_check_purpose to check certificate types
7b5a92d58e OpenSSL 1.1: Change OpenSSL TLS version logic to match mbed TLS
c28b7d1893 OpenSSL 1.1: Adjust default OpenSSL cipher suites
f108044a09 OpenSSL 1.1: Add defines for TLS 1.3 in tlsver.hpp
ee1308b505 OpenSSL 1.1: Replace initialisation of RSA_meth with access method
905d681af1 OpenSSL 1.1: Use standard tls methods
cf28e4600c OpenSSL 1.1: Change BIO wrappers around to use access methods
5e6571163d OpenSSL 1.1: Implement compat methods for new BIO methods in 1.0.2
8837539a73 Use std::nothrow as argument for new
e6ec025932 Merge branch 'qa'
752a38c067 [OVPN3-397] size.hpp: wrap typedef in guards
d4e50f8c54 Merge branch 'qa'
d8d14e1991 [UCONNECT-1027] implement ResolveThread and ensure it is properly detachable
525a9a88a6 Merge branch qa
30ea53cb92 Replace custom memcpy implementation
de7c672ee7 Workaround for compiler bug in memneq
84fcecd5e7 Fix missing override annotation in udp/tcp/httpcli
1a3a69a496 [UCONNECT-1027] use one AsioWork object for the whole pre-resolve opertation
c4cbf93f9b Revert "[UCONNECT-1027] remotelist: create standalone object for resolve thread"
6ef089164e Allow unit tests to be also compiled with mbed TLS and on Windows
7c67bf7f50 Add unit tests for route emulation and establish common test suite
64a7b2f124 Add build file for core unit tests
0a0d080a49 Implement allowing local LAN access
2105b4b7c0 Fix Android route exclusion emulation

git-subtree-dir: Sources/OpenVPNAdapter/Libraries/Vendors/openvpn
git-subtree-split: 275cf80efb7a08adc920f7ca49075c776e596b08
This commit is contained in:
Sergey Abramchuk
2019-06-17 09:44:01 +03:00
parent e9b9b66317
commit 5edb23a7ab
126 changed files with 42387 additions and 1287 deletions
+186
View File
@@ -0,0 +1,186 @@
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
#pragma once
#include <string>
#include <map>
#include <set>
#include <tuple>
#include <memory>
#include <utility>
#include <openssl/ssl.h>
#include <openvpn/common/rc.hpp>
#include <openvpn/common/msfind.hpp>
namespace openvpn {
// Client-side session cache.
// (We don't cache server-side sessions because we use TLS
// session resumption tickets which are stateless on the server).
class OpenSSLSessionCache : public RC<thread_unsafe_refcount>
{
public:
typedef RCPtr<OpenSSLSessionCache> Ptr;
OPENVPN_EXCEPTION(openssl_sess_cache_error);
// Wrapper for OpenSSL SSL_SESSION pointers that manages reference counts.
class Session
{
public:
Session(::SSL_SESSION* sess) // caller must pre-increment refcount on sess
: sess_(sess)
{
}
Session(Session&& other) noexcept
{
sess_ = other.sess_;
other.sess_ = nullptr;
}
Session& operator=(Session&& other) noexcept
{
if (sess_)
::SSL_SESSION_free(sess_);
sess_ = other.sess_;
other.sess_ = nullptr;
return *this;
}
::SSL_SESSION* openssl_session() const
{
return sess_;
}
bool operator<(const Session& rhs) const // used when Session is a std::set key
{
return sess_ < rhs.sess_;
}
explicit operator bool() const
{
return sess_ != nullptr;
}
~Session()
{
if (sess_)
::SSL_SESSION_free(sess_);
}
private:
// These methods are deleted because we have no way to increment
// an SSL_SESSION refcount until OpenSSL 1.1.
Session(const Session&) = delete;
Session& operator=(const Session&) = delete;
::SSL_SESSION* sess_;
};
class Key
{
public:
typedef std::unique_ptr<Key> UPtr;
Key(const std::string& key_arg,
OpenSSLSessionCache::Ptr cache_arg)
: key(key_arg),
cache(std::move(cache_arg))
{
//OPENVPN_LOG("OpenSSLSessionCache::Key CONSTRUCT key=" << key);
}
void commit(::SSL_SESSION* sess)
{
if (!sess)
return;
auto mi = MSF::find(cache->map, key);
if (mi)
{
/* auto ins = */ mi->second.emplace(sess);
//OPENVPN_LOG("OpenSSLSessionCache::Key::commit ADD=" << ins.second << " key=" << key);
}
else
{
//OPENVPN_LOG("OpenSSLSessionCache::Key::commit CREATE key=" << key);
auto ins = cache->map.emplace(std::piecewise_construct,
std::forward_as_tuple(key),
std::forward_as_tuple());
ins.first->second.emplace(sess);
}
}
private:
const std::string key;
OpenSSLSessionCache::Ptr cache;
};
// Remove a session from the map after calling func() on it.
// This would be a lot cleaner if we had C++17 std::set::extract().
template <typename FUNC>
void extract(const std::string& key, FUNC func)
{
auto mi = MSF::find(map, key);
if (mi)
{
//OPENVPN_LOG("OpenSSLSessionCache::Key::lookup EXISTS key=" << key);
SessionSet& ss = mi->second;
if (ss.empty())
throw openssl_sess_cache_error("internal error: SessionSet is empty");
auto ssi = ss.begin();
try {
func(ssi->openssl_session());
}
catch (...)
{
remove_session(mi, ss, ssi);
throw;
}
remove_session(mi, ss, ssi);
}
else
{
//OPENVPN_LOG("OpenSSLSessionCache::Key::lookup NOT_FOUND key=" << key);
}
}
private:
struct SessionSet : public std::set<Session>
{
};
typedef std::map<std::string, SessionSet> Map;
void remove_session(Map::iterator mi, SessionSet& ss, SessionSet::iterator ssi)
{
ss.erase(ssi);
if (ss.empty())
map.erase(mi);
}
Map map;
};
}
+429 -132
View File
@@ -32,6 +32,8 @@
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#include <openssl/rsa.h>
#include <openssl/rand.h>
#include <openvpn/common/size.hpp>
#include <openvpn/common/exception.hpp>
@@ -60,6 +62,7 @@
#include <openvpn/openssl/pki/dh.hpp>
#include <openvpn/openssl/pki/x509store.hpp>
#include <openvpn/openssl/bio/bio_memq_stream.hpp>
#include <openvpn/openssl/ssl/sess_cache.hpp>
// An SSL Context is essentially a configuration that can be used
// to generate an arbitrary number of actual SSL connections objects.
@@ -89,16 +92,6 @@ namespace openvpn {
public:
typedef RCPtr<Config> Ptr;
Config() : external_pki(nullptr),
ssl_debug_level(0),
flags(0),
ns_cert_type(NSCert::NONE),
tls_version_min(TLSVersion::UNDEF),
tls_cert_profile(TLSCertProfile::UNDEF),
local_cert_enabled(true),
force_aes_cbc_ciphersuites(false),
enable_renegotiation(false) {}
virtual SSLFactoryAPI::Ptr new_factory()
{
return SSLFactoryAPI::Ptr(new OpenSSLContext(this));
@@ -120,6 +113,18 @@ namespace openvpn {
external_pki = external_pki_arg;
}
// server side
virtual void set_session_ticket_handler(TLSSessionTicketBase* session_ticket_handler_arg)
{
session_ticket_handler = session_ticket_handler_arg;
}
// client side
virtual void set_client_session_tickets(const bool v)
{
client_session_tickets = v;
}
virtual void set_private_key_password(const std::string& pwd)
{
pkey.set_private_key_password(pwd);
@@ -259,11 +264,6 @@ namespace openvpn {
local_cert_enabled = v;
}
virtual void set_enable_renegotiation(const bool v)
{
enable_renegotiation = v;
}
virtual void set_force_aes_cbc_ciphersuites(const bool v)
{
force_aes_cbc_ciphersuites = v;
@@ -407,20 +407,21 @@ namespace openvpn {
OpenSSLPKI::X509List extra_certs; // from OpenVPN "extra-certs" option
OpenSSLPKI::PKey pkey; // private key
OpenSSLPKI::DH dh; // diffie-hellman parameters (only needed in server mode)
ExternalPKIBase* external_pki;
ExternalPKIBase* external_pki = nullptr;
TLSSessionTicketBase* session_ticket_handler = nullptr; // server side only
Frame::Ptr frame;
int ssl_debug_level;
unsigned int flags; // defined in sslconsts.hpp
NSCert::Type ns_cert_type;
int ssl_debug_level = 0;
unsigned int flags = 0; // defined in sslconsts.hpp
NSCert::Type ns_cert_type{NSCert::NONE};
std::vector<unsigned int> ku; // if defined, peer cert X509 key usage must match one of these values
std::string eku; // if defined, peer cert X509 extended key usage must match this OID/string
std::string tls_remote;
TLSVersion::Type tls_version_min; // minimum TLS version that we will negotiate
TLSCertProfile::Type tls_cert_profile;
TLSVersion::Type tls_version_min{TLSVersion::UNDEF}; // minimum TLS version that we will negotiate
TLSCertProfile::Type tls_cert_profile{TLSCertProfile::UNDEF};
X509Track::ConfigSet x509_track_config;
bool local_cert_enabled;
bool force_aes_cbc_ciphersuites;
bool enable_renegotiation;
bool local_cert_enabled = true;
bool force_aes_cbc_ciphersuites = false;
bool client_session_tickets = false;
};
// Represents an actual SSL session.
@@ -445,7 +446,10 @@ namespace openvpn {
if (status == -1 && BIO_should_retry(ssl_bio))
return SSLConst::SHOULD_RETRY;
else
OPENVPN_THROW(OpenSSLException, "OpenSSLContext::SSL::write_cleartext: BIO_write failed, size=" << size << " status=" << status);
{
mark_no_cache();
OPENVPN_THROW(OpenSSLException, "OpenSSLContext::SSL::write_cleartext: BIO_write failed, size=" << size << " status=" << status);
}
}
else
return status;
@@ -461,7 +465,10 @@ namespace openvpn {
if (status == -1 && BIO_should_retry(ssl_bio))
return SSLConst::SHOULD_RETRY;
else
OPENVPN_THROW(OpenSSLException, "OpenSSLContext::SSL::read_cleartext: BIO_read failed, cap=" << capacity << " status=" << status);
{
mark_no_cache();
OPENVPN_THROW(OpenSSLException, "OpenSSLContext::SSL::read_cleartext: BIO_read failed, cap=" << capacity << " status=" << status);
}
}
else
return status;
@@ -508,11 +515,31 @@ namespace openvpn {
return ssl_handshake_details(ssl);
}
virtual const AuthCert::Ptr& auth_cert() const
// Return true if we did a full SSL handshake/negotiation.
// Return false for cached, reused, or persisted sessions.
// Also returns false if previously called on this session.
virtual bool did_full_handshake() override
{
if (called_did_full_handshake)
return false;
called_did_full_handshake = true;
return !SSL_session_reused(ssl);
}
virtual const AuthCert::Ptr& auth_cert()
{
// Reused sessions don't call the cert verify callbacks,
// so we must use an alternative method to build authcert.
if (authcert && authcert->is_uninitialized())
rebuild_authcert();
return authcert;
}
virtual void mark_no_cache()
{
sess_cache_key.reset();
}
~SSL()
{
ssl_erase();
@@ -520,26 +547,39 @@ namespace openvpn {
static void init_static()
{
SSL_library_init();
bmq_stream::init_static();
mydata_index = SSL_get_ex_new_index(0, (char *)"OpenSSLContext::SSL", nullptr, nullptr, nullptr);
context_data_index = SSL_get_ex_new_index(0, (char *)"OpenSSLContext", nullptr, nullptr, nullptr);
// We actually override some of the OpenSSL SSLv23 methods here,
// in particular the ssl_pending method. We want ssl_pending
// to return 0 until the SSL negotiation establishes the
// actual method. The default OpenSSL SSLv23 ssl_pending method
// (ssl_undefined_const_function) triggers an OpenSSL error condition
// which is not what we want.
/*
* We actually override some of the OpenSSL SSLv23 methods here,
* in particular the ssl_pending method. We want ssl_pending
* to return 0 until the SSL negotiation establishes the
* actual method. The default OpenSSL SSLv23 ssl_pending method
* (ssl_undefined_const_function) triggers an OpenSSL error condition
* when calling SSL_pending early which is not what we want.
*
* This depends on SSL23 being a generic method and OpenSSL later
* switching to a spefic TLS method (TLS10method etc..) with
* ssl23_get_client_method that has the proper ssl3_pending pending method.
*
* OpenSSL 1.1.x does not allow hacks like this anymore. So overriding is not
* possible. Fortunately OpenSSL 1.1 also always defines ssl_pending method to
* be ssl3_pending, so this hack is no longer needed.
*/
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ssl23_method_client_ = *SSLv23_client_method();
ssl23_method_client_.ssl_pending = ssl_pending_override;
ssl23_method_server_ = *SSLv23_server_method();
ssl23_method_server_.ssl_pending = ssl_pending_override;
#endif
}
private:
SSL(const OpenSSLContext& ctx, const char *hostname)
SSL(const OpenSSLContext& ctx, const std::string* hostname, const std::string* cache_key)
{
ssl_clear();
try {
@@ -556,7 +596,7 @@ namespace openvpn {
{
X509_VERIFY_PARAM *param = SSL_get0_param(ssl);
X509_VERIFY_PARAM_set_hostflags(param, 0);
X509_VERIFY_PARAM_set1_host(param, hostname, 0);
X509_VERIFY_PARAM_set1_host(param, hostname->c_str(), 0);
}
// init BIOs
@@ -576,6 +616,17 @@ namespace openvpn {
}
else if (ctx.config->mode.is_client())
{
if (cache_key && ctx.sess_cache)
{
// see if a cached session already exists for our cache_key
ctx.sess_cache->extract(*cache_key, [this](SSL_SESSION* sess) {
if (!SSL_set_session(ssl, sess))
throw OpenSSLException("SSL_set_session failed");
});
// cache the session before its end-of-life if no errors occur
sess_cache_key.reset(new OpenSSLSessionCache::Key(*cache_key, ctx.sess_cache));
}
SSL_set_connect_state(ssl);
if (ctx.config->flags & SSLConst::ENABLE_SNI)
if (SSL_set_tlsext_host_name(ssl, hostname) != 1)
@@ -591,7 +642,10 @@ namespace openvpn {
if (mydata_index < 0)
throw ssl_context_error("OpenSSLContext::SSL: mydata_index is uninitialized");
if (context_data_index < 0)
throw ssl_context_error("OpenSSLContext::SSL: context_data_index is uninitialized");
SSL_set_ex_data (ssl, mydata_index, this);
SSL_set_ex_data (ssl, context_data_index, (void*) &ctx);
}
catch (...)
{
@@ -600,6 +654,29 @@ namespace openvpn {
}
}
void rebuild_authcert()
{
authcert.reset(new AuthCert());
::X509 *cert = SSL_get_peer_certificate(ssl);
if (cert)
{
// save the issuer cert fingerprint
static_assert(sizeof(AuthCert::issuer_fp) == SHA_DIGEST_LENGTH, "size inconsistency");
unsigned int md_len = sizeof(AuthCert::issuer_fp);
X509_digest (cert, EVP_sha1 (), authcert->issuer_fp, &md_len);
// save the Common Name
authcert->cn = x509_get_field(cert, NID_commonName);
// save the leaf cert serial number
const ASN1_INTEGER *ai = X509_get_serialNumber(cert);
authcert->sn = ai ? ASN1_INTEGER_get(ai) : -1;
X509_free (cert);
}
}
// Indicate no data available for our custom SSLv23 method
static int ssl_pending_override(const ::SSL *)
{
@@ -607,12 +684,15 @@ namespace openvpn {
}
// Print a one line summary of SSL/TLS session handshake.
static std::string ssl_handshake_details (const ::SSL *c_ssl)
static std::string ssl_handshake_details (::SSL *c_ssl)
{
std::ostringstream os;
os << SSL_get_version (c_ssl);
const SSL_CIPHER *ciph = SSL_get_current_cipher (c_ssl);
os << SSL_get_version (c_ssl) << ", cipher " << SSL_CIPHER_get_version (ciph) << ' ' << SSL_CIPHER_get_name (ciph);
if (ciph)
os << ", cipher " << SSL_CIPHER_get_version (ciph) << ' ' << SSL_CIPHER_get_name (ciph);
::X509 *cert = SSL_get_peer_certificate (c_ssl);
if (cert != nullptr)
@@ -620,16 +700,18 @@ namespace openvpn {
EVP_PKEY *pkey = X509_get_pubkey (cert);
if (pkey != nullptr)
{
if (pkey->type == EVP_PKEY_RSA && pkey->pkey.rsa != nullptr && pkey->pkey.rsa->n != nullptr)
os << ", " << BN_num_bits (pkey->pkey.rsa->n) << " bit RSA";
if (EVP_PKEY_id (pkey) == EVP_PKEY_RSA && EVP_PKEY_get0_RSA (pkey) != nullptr && RSA_get0_n(EVP_PKEY_get0_RSA (pkey)) != nullptr)
os << ", " << BN_num_bits (RSA_get0_n(EVP_PKEY_get0_RSA (pkey))) << " bit RSA";
#ifndef OPENSSL_NO_DSA
else if (pkey->type == EVP_PKEY_DSA && pkey->pkey.dsa != nullptr && pkey->pkey.dsa->p != nullptr)
os << ", " << BN_num_bits (pkey->pkey.dsa->p) << " bit DSA";
else if (EVP_PKEY_id (pkey) == EVP_PKEY_DSA && EVP_PKEY_get0_DSA (pkey) != nullptr && DSA_get0_p(EVP_PKEY_get0_DSA (pkey))!= nullptr)
os << ", " << BN_num_bits (DSA_get0_p(EVP_PKEY_get0_DSA (pkey))) << " bit DSA";
#endif
EVP_PKEY_free (pkey);
}
X509_free (cert);
}
if (SSL_session_reused(c_ssl))
os << " [REUSED]";
return os.str();
}
@@ -641,6 +723,8 @@ namespace openvpn {
ct_in = nullptr;
ct_out = nullptr;
overflow = false;
called_did_full_handshake = false;
sess_cache_key.reset();
}
void ssl_erase()
@@ -655,7 +739,14 @@ namespace openvpn {
if (ssl_bio)
BIO_free_all(ssl_bio);
if (ssl)
SSL_free(ssl);
{
if (sess_cache_key)
{
SSL_set_shutdown(ssl, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
sess_cache_key->commit(SSL_get1_session(ssl));
}
SSL_free(ssl);
}
openssl_clear_error_stack();
ssl_clear();
}
@@ -669,35 +760,51 @@ namespace openvpn {
return bio;
}
#if OPENSSL_VERSION_NUMBER < 0x10100000L
/*
* Return modified OpenSSL SSLv23 methods,
* as configured in init_static().
*/
static const SSL_METHOD* ssl23_method_client()
static const SSL_METHOD* tls_method_client()
{
return &ssl23_method_client_;
}
static const SSL_METHOD* ssl23_method_server()
static const SSL_METHOD* tls_method_server()
{
return &ssl23_method_server_;
}
#else
static const SSL_METHOD* tls_method_client ()
{
return TLS_client_method ();
}
static const SSL_METHOD* tls_method_server ()
{
return TLS_server_method ();
}
#endif
::SSL *ssl; // OpenSSL SSL object
BIO *ssl_bio; // read/write cleartext from here
BIO *ct_in; // write ciphertext to here
BIO *ct_out; // read ciphertext from here
AuthCert::Ptr authcert;
OpenSSLSessionCache::Key::UPtr sess_cache_key; // client-side only
bool ssl_bio_linkage;
bool overflow;
bool called_did_full_handshake;
// Helps us to store pointer to self in ::SSL object
static int mydata_index;
static int context_data_index;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
// Modified SSLv23 methods
static SSL_METHOD ssl23_method_client_;
static SSL_METHOD ssl23_method_server_;
#endif
};
private:
@@ -707,22 +814,20 @@ namespace openvpn {
: external_pki(external_pki_arg), n_errors(0)
{
RSA *rsa = nullptr;
RSA_METHOD *rsa_meth = nullptr;
RSA *pub_rsa = nullptr;
RSA *pub_rsa = nullptr;
RSA_METHOD *rsa_meth = nullptr;
const char *errtext = "";
/* allocate custom RSA method object */
rsa_meth = new RSA_METHOD;
std::memset(rsa_meth, 0, sizeof(RSA_METHOD));
rsa_meth->name = "OpenSSLContext::ExternalPKIImpl private key RSA Method";
rsa_meth->rsa_pub_enc = rsa_pub_enc;
rsa_meth->rsa_pub_dec = rsa_pub_dec;
rsa_meth->rsa_priv_enc = rsa_priv_enc;
rsa_meth->rsa_priv_dec = rsa_priv_dec;
rsa_meth->init = nullptr;
rsa_meth->finish = rsa_finish;
rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
rsa_meth->app_data = (char *)this;
rsa_meth = RSA_meth_new ("OpenSSLContext::ExternalPKIImpl private key RSA Method", RSA_METHOD_FLAG_NO_CHECK);
RSA_meth_set_pub_enc (rsa_meth, rsa_pub_enc);
RSA_meth_set_pub_dec (rsa_meth, rsa_pub_dec);
RSA_meth_set_priv_enc (rsa_meth, rsa_priv_enc);
RSA_meth_set_priv_dec (rsa_meth, rsa_priv_dec);
RSA_meth_set_init (rsa_meth, nullptr);
RSA_meth_set_finish (rsa_meth, rsa_finish);
RSA_meth_set0_app_data (rsa_meth, this);
/* allocate RSA object */
rsa = RSA_new();
@@ -734,16 +839,26 @@ namespace openvpn {
}
/* get the public key */
if (cert->cert_info->key->pkey == nullptr) /* nullptr before SSL_CTX_use_certificate() is called */
if (X509_get0_pubkey(cert) == nullptr) /* nullptr before SSL_CTX_use_certificate() is called */
{
errtext = "pkey is NULL";
goto err;
}
pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
if (EVP_PKEY_id (X509_get0_pubkey(cert)) != EVP_PKEY_RSA )
{
errtext = "pkey is not RSA";
goto err;
}
pub_rsa = EVP_PKEY_get0_RSA (X509_get0_pubkey(cert));
/* initialize RSA object */
rsa->n = BN_dup(pub_rsa->n);
rsa->flags |= RSA_FLAG_EXT_PKEY;
rsa = RSA_new ();
/* only set e and n as d (private key) is outside our control */
RSA_set0_key(rsa, BN_dup(RSA_get0_n(pub_rsa)), BN_dup(RSA_get0_e(pub_rsa)), nullptr);
RSA_set_flags (rsa, RSA_FLAG_EXT_PKEY);
if (!RSA_set_method(rsa, rsa_meth))
{
errtext = "RSA_set_method";
@@ -766,7 +881,7 @@ namespace openvpn {
else
{
if (rsa_meth)
free(rsa_meth);
RSA_meth_free (rsa_meth);
}
OPENVPN_THROW(OpenSSLException, "OpenSSLContext::ExternalPKIImpl: " << errtext);
}
@@ -779,21 +894,29 @@ namespace openvpn {
/* called at RSA_free */
static int rsa_finish(RSA *rsa)
{
free ((void*)rsa->meth);
rsa->meth = nullptr;
RSA_meth_free (const_cast<RSA_METHOD*>(RSA_get_method (rsa)));
return 1;
}
/* sign arbitrary data */
static int rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
{
ExternalPKIImpl* self = (ExternalPKIImpl*)rsa->meth->app_data;
ExternalPKIImpl* self = (ExternalPKIImpl*)(RSA_meth_get0_app_data (RSA_get_method(rsa)));
try {
if (padding != RSA_PKCS1_PADDING)
if (padding != RSA_PKCS1_PADDING && padding != RSA_NO_PADDING)
{
RSAerr (RSA_F_RSA_EAY_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
throw ssl_external_pki("OpenSSL: bad padding size");
RSAerr (RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
throw ssl_external_pki("OpenSSL: bad padding type");
}
std::string padding_algo;
if (padding == RSA_PKCS1_PADDING)
{
padding_algo = "RSA_PKCS1_PADDING";
}
else if (padding == RSA_NO_PADDING)
{
padding_algo = "RSA_NO_PADDING";
}
/* convert 'from' to base64 */
@@ -802,7 +925,7 @@ namespace openvpn {
/* get signature */
std::string sig_b64;
const bool status = self->external_pki->sign(from_b64, sig_b64);
const bool status = self->external_pki->sign(from_b64, sig_b64, padding_algo);
if (!status)
throw ssl_external_pki("OpenSSL: could not obtain signature");
@@ -828,7 +951,7 @@ namespace openvpn {
static void not_implemented(RSA *rsa)
{
ExternalPKIImpl* self = (ExternalPKIImpl*)rsa->meth->app_data;
ExternalPKIImpl* self = (ExternalPKIImpl*)(RSA_meth_get0_app_data (RSA_get_method (rsa)));
++self->n_errors;
}
@@ -862,17 +985,14 @@ namespace openvpn {
/////// start of main class implementation
OpenSSLContext(Config* config_arg)
: config(config_arg),
ctx(nullptr),
epki(nullptr)
: config(config_arg)
{
try
{
// Create new SSL_CTX for server or client mode
const bool ssl23 = (!config->force_aes_cbc_ciphersuites || (config->tls_version_min > TLSVersion::UNDEF));
if (config->mode.is_server())
{
ctx = SSL_CTX_new(ssl23 ? SSL::ssl23_method_server() : TLSv1_server_method());
ctx = SSL_CTX_new(SSL::tls_method_server());
if (ctx == nullptr)
throw OpenSSLException("OpenSSLContext: SSL_CTX_new failed for server method");
@@ -881,48 +1001,84 @@ namespace openvpn {
OPENVPN_THROW(ssl_context_error, "OpenSSLContext: DH not defined");
if (!SSL_CTX_set_tmp_dh(ctx, config->dh.obj()))
throw OpenSSLException("OpenSSLContext: SSL_CTX_set_tmp_dh failed");
if (config->enable_renegotiation)
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER);
if (config->flags & SSLConst::SERVER_TO_SERVER)
SSL_CTX_set_purpose(ctx, X509_PURPOSE_SSL_SERVER);
}
else if (config->mode.is_client())
{
ctx = SSL_CTX_new(ssl23 ? SSL::ssl23_method_client() : TLSv1_client_method());
ctx = SSL_CTX_new(SSL::tls_method_client());
if (ctx == nullptr)
throw OpenSSLException("OpenSSLContext: SSL_CTX_new failed for client method");
if (config->enable_renegotiation)
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT); // note: SSL_set_session must be called as well
}
else
OPENVPN_THROW(ssl_context_error, "OpenSSLContext: unknown config->mode");
// Set SSL options
if (!config->enable_renegotiation)
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
if (!(config->flags & SSLConst::NO_VERIFY_PEER))
{
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
int vf = SSL_VERIFY_PEER;
if (!(config->flags & SSLConst::PEER_CERT_OPTIONAL))
vf |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
SSL_CTX_set_verify(ctx, vf,
config->mode.is_client() ? verify_callback_client : verify_callback_server);
SSL_CTX_set_verify_depth(ctx, 16);
}
long sslopt = SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE | SSL_OP_NO_COMPRESSION;
if (!config->enable_renegotiation)
sslopt |= SSL_OP_NO_TICKET;
if (ssl23)
/* Disable SSLv2 and SSLv3, might be a noop but does not hurt */
sslopt |= SSL_OP_NO_SSLv2;
sslopt |= SSL_OP_NO_SSLv3;
if (config->mode.is_server())
{
sslopt |= SSL_OP_NO_SSLv2;
sslopt |= SSL_OP_NO_SSLv3;
if (config->tls_version_min > TLSVersion::V1_0)
sslopt |= SSL_OP_NO_TLSv1;
# ifdef SSL_OP_NO_TLSv1_1
if (config->tls_version_min > TLSVersion::V1_1)
sslopt |= SSL_OP_NO_TLSv1_1;
# endif
# ifdef SSL_OP_NO_TLSv1_2
if (config->tls_version_min > TLSVersion::V1_2)
sslopt |= SSL_OP_NO_TLSv1_2;
# endif
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
if (config->session_ticket_handler)
{
const std::string sess_id_context = config->session_ticket_handler->session_id_context();
if (!SSL_CTX_set_session_id_context(ctx, (unsigned char *)sess_id_context.c_str(), sess_id_context.length()))
throw OpenSSLException("OpenSSLContext: SSL_CTX_set_session_id_context failed");
if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, tls_ticket_key_callback))
throw OpenSSLException("OpenSSLContext: SSL_CTX_set_tlsext_ticket_key_cb failed");
}
else
sslopt |= SSL_OP_NO_TICKET;
}
else
{
if (config->client_session_tickets)
{
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT);
sess_cache.reset(new OpenSSLSessionCache);
}
else
{
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
sslopt |= SSL_OP_NO_TICKET;
}
}
/* mbed TLS also ignores tls version when force aes cbc cipher suites is on */
if (!config->force_aes_cbc_ciphersuites)
{
if (!config->force_aes_cbc_ciphersuites || config->tls_version_min > TLSVersion::UNDEF)
{
if (config->tls_version_min > TLSVersion::V1_0)
sslopt |= SSL_OP_NO_TLSv1;
# ifdef SSL_OP_NO_TLSv1_1
if (config->tls_version_min > TLSVersion::V1_1)
sslopt |= SSL_OP_NO_TLSv1_1;
# endif
# ifdef SSL_OP_NO_TLSv1_2
if (config->tls_version_min > TLSVersion::V1_2)
sslopt |= SSL_OP_NO_TLSv1_2;
# endif
# ifdef SSL_OP_NO_TLSv1_3
if (config->tls_version_min > TLSVersion::V1_3)
sslopt |= SSL_OP_NO_TLSv1_3;
# endif
}
}
SSL_CTX_set_options(ctx, sslopt);
@@ -933,10 +1089,27 @@ namespace openvpn {
}
else
{
if (!SSL_CTX_set_cipher_list(ctx, "DEFAULT:!EXP:!PSK:!SRP:!LOW:!RC4:!kRSA:!MD5:!SSLv2"))
OPENVPN_THROW(ssl_context_error, "OpenSSLContext: SSL_CTX_set_cipher_list failed");
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
SSL_CTX_set_ecdh_auto(ctx, 1);
if (!SSL_CTX_set_cipher_list(ctx,
/* default list as a basis */
"DEFAULT"
/* Disable export ciphers, low and medium */
":!EXP:!LOW:!MEDIUM"
/* Disable static (EC)DH keys (no forward secrecy) */
":!kDH:!kECDH"
/* Disable DSA private keys */
":!DSS"
/* Disable RC4 cipher */
":!RC4"
/* Disable MD5 */
":!MD5"
/* Disable unsupported TLS modes */
":!PSK:!SRP:!kRSA"
/* Disable SSLv2 cipher suites*/
":!SSLv2"
))
OPENVPN_THROW(ssl_context_error, "OpenSSLContext: SSL_CTX_set_cipher_list failed");
#if OPENSSL_VERSION_NUMBER >= 0x10002000L && OPENSSL_VERSION_NUMBER < 0x10100000L
SSL_CTX_set_ecdh_auto(ctx, 1); // this method becomes a no-op in OpenSSL 1.1
#endif
}
@@ -1019,9 +1192,6 @@ namespace openvpn {
else if (!(config->flags & SSLConst::NO_VERIFY_PEER))
OPENVPN_THROW(ssl_context_error, "OpenSSLContext: CA not defined");
// keep a reference to this in ctx, for use by verify callback
ctx->app_verify_arg = this;
// Show handshake debugging info
if (config->ssl_debug_level)
SSL_CTX_set_info_callback (ctx, info_callback);
@@ -1037,13 +1207,13 @@ namespace openvpn {
// create a new SSL instance
virtual SSLAPI::Ptr ssl()
{
return SSL::Ptr(new SSL(*this, nullptr));
return SSL::Ptr(new SSL(*this, nullptr, nullptr));
}
// like ssl() above but verify hostname against cert CommonName and/or SubjectAltName
virtual SSLAPI::Ptr ssl(const std::string& hostname)
virtual SSLAPI::Ptr ssl(const std::string* hostname, const std::string* cache_key)
{
return SSL::Ptr(new SSL(*this, hostname.c_str()));
return SSL::Ptr(new SSL(*this, hostname, cache_key));
}
void update_trust(const CertCRLList& cc)
@@ -1070,12 +1240,12 @@ namespace openvpn {
return config->ns_cert_type != NSCert::NONE;
}
bool verify_ns_cert_type(const ::X509* cert) const
bool verify_ns_cert_type(::X509* cert) const
{
if (config->ns_cert_type == NSCert::SERVER)
return (cert->ex_flags & EXFLAG_NSCERT) && (cert->ex_nscert & NS_SSL_SERVER);
return X509_check_purpose (cert, X509_PURPOSE_SSL_SERVER, 0);
else if (config->ns_cert_type == NSCert::CLIENT)
return (cert->ex_flags & EXFLAG_NSCERT) && (cert->ex_nscert & NS_SSL_CLIENT);
return X509_check_purpose (cert, X509_PURPOSE_SSL_CLIENT, 0);
else
return true;
}
@@ -1285,9 +1455,14 @@ namespace openvpn {
x509_get_serial_hex(cert));
break;
case X509Track::SHA1:
xts.emplace_back(X509Track::SHA1,
depth,
render_hex_sep(cert->sha1_hash, SHA_DIGEST_LENGTH, ':', true));
{
unsigned char buf[EVP_MAX_MD_SIZE];
unsigned int len = EVP_MAX_MD_SIZE;
X509_digest (cert, EVP_sha1 (), buf, &len);
xts.emplace_back (X509Track::SHA1,
depth,
render_hex_sep (buf, len, ':', true));
}
break;
case X509Track::CN:
x509_track_extract_nid(X509Track::CN, NID_commonName, cert, depth, xts);
@@ -1363,13 +1538,16 @@ namespace openvpn {
::SSL* ssl = (::SSL*) X509_STORE_CTX_get_ex_data (ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
// get OpenSSLContext
const OpenSSLContext* self = (OpenSSLContext*) ssl->ctx->app_verify_arg;
const OpenSSLContext* self = (OpenSSLContext*) SSL_get_ex_data (ssl, SSL::context_data_index);
// get depth
const int depth = X509_STORE_CTX_get_error_depth(ctx);
// get current certificate
X509* current_cert = X509_STORE_CTX_get_current_cert (ctx);
// log subject
const std::string subject = x509_get_subject(ctx->current_cert);
const std::string subject = x509_get_subject(current_cert);
if (self->config->flags & SSLConst::LOG_VERIFY_STATUS)
OPENVPN_LOG_SSL(cert_status_line(preverify_ok, depth, X509_STORE_CTX_get_error(ctx), subject));
@@ -1377,21 +1555,21 @@ namespace openvpn {
if (depth == 0)
{
// verify ns-cert-type
if (self->ns_cert_type_defined() && !self->verify_ns_cert_type(ctx->current_cert))
if (self->ns_cert_type_defined() && !self->verify_ns_cert_type(current_cert))
{
OPENVPN_LOG_SSL("VERIFY FAIL -- bad ns-cert-type in leaf certificate");
preverify_ok = false;
}
// verify X509 key usage
if (self->x509_cert_ku_defined() && !self->verify_x509_cert_ku(ctx->current_cert))
if (self->x509_cert_ku_defined() && !self->verify_x509_cert_ku(current_cert))
{
OPENVPN_LOG_SSL("VERIFY FAIL -- bad X509 key usage in leaf certificate");
preverify_ok = false;
}
// verify X509 extended key usage
if (self->x509_cert_eku_defined() && !self->verify_x509_cert_eku(ctx->current_cert))
if (self->x509_cert_eku_defined() && !self->verify_x509_cert_eku(current_cert))
{
OPENVPN_LOG_SSL("VERIFY FAIL -- bad X509 extended key usage in leaf certificate");
preverify_ok = false;
@@ -1401,7 +1579,7 @@ namespace openvpn {
if (!self->config->tls_remote.empty())
{
const std::string subj = TLSRemote::sanitize_x509_name(subject);
const std::string common_name = TLSRemote::sanitize_common_name(x509_get_field(ctx->current_cert, NID_commonName));
const std::string common_name = TLSRemote::sanitize_common_name(x509_get_field(current_cert, NID_commonName));
TLSRemote::log(self->config->tls_remote, subj, common_name);
if (!TLSRemote::test(self->config->tls_remote, subj, common_name))
{
@@ -1420,7 +1598,7 @@ namespace openvpn {
::SSL* ssl = (::SSL*) X509_STORE_CTX_get_ex_data (ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
// get OpenSSLContext
const OpenSSLContext* self = (OpenSSLContext*) ssl->ctx->app_verify_arg;
const OpenSSLContext* self = (OpenSSLContext*) SSL_get_ex_data (ssl, SSL::context_data_index);
// get OpenSSLContext::SSL
SSL* self_ssl = (SSL *) SSL_get_ex_data (ssl, SSL::mydata_index);
@@ -1431,9 +1609,12 @@ namespace openvpn {
// get depth
const int depth = X509_STORE_CTX_get_error_depth(ctx);
// get current certificate
X509* current_cert = X509_STORE_CTX_get_current_cert (ctx);
// log subject
if (self->config->flags & SSLConst::LOG_VERIFY_STATUS)
OPENVPN_LOG_SSL(cert_status_line(preverify_ok, depth, err, x509_get_subject(ctx->current_cert)));
OPENVPN_LOG_SSL(cert_status_line(preverify_ok, depth, err, x509_get_subject(current_cert)));
// record cert error in authcert
if (!preverify_ok && self_ssl->authcert)
@@ -1445,13 +1626,15 @@ namespace openvpn {
if (self_ssl->authcert)
{
static_assert(sizeof(AuthCert::issuer_fp) == SHA_DIGEST_LENGTH, "size inconsistency");
std::memcpy(self_ssl->authcert->issuer_fp, ctx->current_cert->sha1_hash, sizeof(AuthCert::issuer_fp));
unsigned int digest_len = sizeof(AuthCert::issuer_fp);
if (!X509_digest (current_cert, EVP_sha1 (), self_ssl->authcert->issuer_fp, &digest_len))
preverify_ok = false;
}
}
else if (depth == 0) // leaf cert
{
// verify ns-cert-type
if (self->ns_cert_type_defined() && !self->verify_ns_cert_type(ctx->current_cert))
if (self->ns_cert_type_defined() && !self->verify_ns_cert_type(current_cert))
{
OPENVPN_LOG_SSL("VERIFY FAIL -- bad ns-cert-type in leaf certificate");
if (self_ssl->authcert)
@@ -1460,7 +1643,7 @@ namespace openvpn {
}
// verify X509 key usage
if (self->x509_cert_ku_defined() && !self->verify_x509_cert_ku(ctx->current_cert))
if (self->x509_cert_ku_defined() && !self->verify_x509_cert_ku(current_cert))
{
OPENVPN_LOG_SSL("VERIFY FAIL -- bad X509 key usage in leaf certificate");
if (self_ssl->authcert)
@@ -1469,7 +1652,7 @@ namespace openvpn {
}
// verify X509 extended key usage
if (self->x509_cert_eku_defined() && !self->verify_x509_cert_eku(ctx->current_cert))
if (self->x509_cert_eku_defined() && !self->verify_x509_cert_eku(current_cert))
{
OPENVPN_LOG_SSL("VERIFY FAIL -- bad X509 extended key usage in leaf certificate");
if (self_ssl->authcert)
@@ -1480,17 +1663,17 @@ namespace openvpn {
if (self_ssl->authcert)
{
// save the Common Name
self_ssl->authcert->cn = x509_get_field(ctx->current_cert, NID_commonName);
self_ssl->authcert->cn = x509_get_field(current_cert, NID_commonName);
// save the leaf cert serial number
const ASN1_INTEGER *ai = X509_get_serialNumber(ctx->current_cert);
const ASN1_INTEGER *ai = X509_get_serialNumber(current_cert);
self_ssl->authcert->sn = ai ? ASN1_INTEGER_get(ai) : -1;
}
}
// x509-track enabled?
if (self_ssl->authcert && self_ssl->authcert->x509_track)
x509_track_extract_from_cert(ctx->current_cert,
x509_track_extract_from_cert(current_cert,
depth,
self->config->x509_track_config,
*self_ssl->authcert->x509_track);
@@ -1513,6 +1696,116 @@ namespace openvpn {
}
}
static int tls_ticket_key_callback(::SSL *ssl,
unsigned char key_name[16],
unsigned char iv[EVP_MAX_IV_LENGTH],
::EVP_CIPHER_CTX *ctx,
::HMAC_CTX *hctx,
int enc)
{
// get OpenSSLContext
const OpenSSLContext* self = (OpenSSLContext*) SSL_get_ex_data (ssl, SSL::context_data_index);
if (!self)
return -1;
// get user-defined session ticket handler
TLSSessionTicketBase* t = self->config->session_ticket_handler;
if (!t)
return -1;
if (enc)
{
// create new ticket
TLSSessionTicketBase::Name name;
TLSSessionTicketBase::Key key;
switch (t->create_session_ticket_key(name, key))
{
case TLSSessionTicketBase::NO_TICKET:
case TLSSessionTicketBase::TICKET_EXPIRING: // doesn't really make sense for enc==1?
// NOTE: OpenSSL may segfault on a zero return.
// This appears to be fixed by:
// commit dbdb96617cce2bd4356d57f53ecc327d0e31f2ad
// Author: Todd Short <tshort@akamai.com>
// Date: Thu May 12 18:16:52 2016 -0400
// Fix session ticket and SNI
//OPENVPN_LOG("tls_ticket_key_callback: create: no ticket or expiring ticket");
#if OPENSSL_VERSION_NUMBER < 0x1000212fL // 1.0.2r
if (!randomize_name_key(name, key))
return -1;
// fallthrough
#else
return 0;
#endif
case TLSSessionTicketBase::TICKET_AVAILABLE:
if (!RAND_bytes(iv, EVP_MAX_IV_LENGTH))
return -1;
if (!tls_ticket_init_cipher_hmac(key, iv, ctx, hctx, enc))
return -1;
static_assert(TLSSessionTicketBase::Name::SIZE == 16, "unexpected name size");
std::memcpy(key_name, name.value_, TLSSessionTicketBase::Name::SIZE);
//OPENVPN_LOG("tls_ticket_key_callback: created ticket");
return 1;
default:
//OPENVPN_LOG("tls_ticket_key_callback: create: bad ticket");
return -1;
}
}
else
{
// lookup existing ticket
static_assert(TLSSessionTicketBase::Name::SIZE == 16, "unexpected name size");
const TLSSessionTicketBase::Name name(key_name);
TLSSessionTicketBase::Key key;
switch (t->lookup_session_ticket_key(name, key))
{
case TLSSessionTicketBase::TICKET_AVAILABLE:
if (!tls_ticket_init_cipher_hmac(key, iv, ctx, hctx, enc))
return -1;
//OPENVPN_LOG("tls_ticket_key_callback: found ticket");
return 1;
case TLSSessionTicketBase::TICKET_EXPIRING:
if (!tls_ticket_init_cipher_hmac(key, iv, ctx, hctx, enc))
return -1;
//OPENVPN_LOG("tls_ticket_key_callback: expiring ticket");
return 2;
case TLSSessionTicketBase::NO_TICKET:
//OPENVPN_LOG("tls_ticket_key_callback: lookup: no ticket");
return 0;
default:
//OPENVPN_LOG("tls_ticket_key_callback: lookup: bad ticket");
return -1;
}
}
}
static bool tls_ticket_init_cipher_hmac(const TLSSessionTicketBase::Key& key,
unsigned char iv[EVP_MAX_IV_LENGTH],
::EVP_CIPHER_CTX *ctx,
::HMAC_CTX *hctx,
const int enc)
{
static_assert(TLSSessionTicketBase::Key::CIPHER_KEY_SIZE == 32, "unexpected cipher key size");
if (!EVP_CipherInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key.cipher_value_, iv, enc))
return false;
if (!HMAC_Init_ex(hctx, key.hmac_value_, TLSSessionTicketBase::Key::HMAC_KEY_SIZE, EVP_sha256(), nullptr))
return false;
return true;
}
static bool randomize_name_key(TLSSessionTicketBase::Name& name,
TLSSessionTicketBase::Key& key)
{
if (!RAND_bytes(name.value_, TLSSessionTicketBase::Name::SIZE))
return false;
if (!RAND_bytes(key.cipher_value_, TLSSessionTicketBase::Key::CIPHER_KEY_SIZE))
return false;
if (!RAND_bytes(key.hmac_value_, TLSSessionTicketBase::Key::HMAC_KEY_SIZE))
return false;
return true;
}
void erase()
{
if (epki)
@@ -1528,14 +1821,18 @@ namespace openvpn {
}
Config::Ptr config;
SSL_CTX* ctx;
ExternalPKIImpl* epki;
SSL_CTX* ctx = nullptr;
ExternalPKIImpl* epki = nullptr;
OpenSSLSessionCache::Ptr sess_cache; // client-side only
};
int OpenSSLContext::SSL::mydata_index = -1;
int OpenSSLContext::SSL::context_data_index = -1;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
SSL_METHOD OpenSSLContext::SSL::ssl23_method_client_;
SSL_METHOD OpenSSLContext::SSL::ssl23_method_server_;
#endif
}
#endif