summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
Diffstat (limited to 'Swiften/TLS/OpenSSL')
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp4
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.cpp50
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h10
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContext.cpp359
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContext.h65
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp32
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContextFactory.h14
7 files changed, 448 insertions, 86 deletions
diff --git a/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp b/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp
index 17ac8cc..8d2d965 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp
+++ b/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp
@@ -30,7 +30,7 @@ OpenSSLCertificate::OpenSSLCertificate(const ByteArray& der) {
#else
const unsigned char* p = vecptr(der);
#endif
- cert = std::shared_ptr<X509>(d2i_X509(NULL, &p, der.size()), X509_free);
+ cert = std::shared_ptr<X509>(d2i_X509(nullptr, &p, der.size()), X509_free);
if (!cert) {
SWIFT_LOG(warning) << "Error creating certificate from DER data" << std::endl;
}
@@ -42,7 +42,7 @@ ByteArray OpenSSLCertificate::toDER() const {
if (!cert) {
return result;
}
- result.resize(i2d_X509(cert.get(), NULL));
+ result.resize(i2d_X509(cert.get(), nullptr));
unsigned char* p = vecptr(result);
i2d_X509(cert.get(), &p);
return result;
diff --git a/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.cpp b/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.cpp
new file mode 100644
index 0000000..c94702c
--- /dev/null
+++ b/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.cpp
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2018 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h>
+
+#include <openssl/pem.h>
+
+namespace Swift {
+
+OpenSSLCertificateFactory::OpenSSLCertificateFactory() {
+}
+
+OpenSSLCertificateFactory::~OpenSSLCertificateFactory() {
+}
+
+Certificate* OpenSSLCertificateFactory::createCertificateFromDER(const ByteArray& der) {
+ return new OpenSSLCertificate(der);
+}
+
+std::vector<Certificate::ref> OpenSSLCertificateFactory::createCertificateChain(const ByteArray& data) {
+ std::vector<Certificate::ref> certificateChain;
+
+ if (data.size() > std::numeric_limits<int>::max()) {
+ return certificateChain;
+ }
+
+ auto bio = std::shared_ptr<BIO>(BIO_new(BIO_s_mem()), BIO_free);
+ BIO_write(bio.get(), vecptr(data), int(data.size()));
+
+ // Attempt parsing data as PEM
+ X509* openSSLCert = nullptr;
+ auto x509certFromPEM = PEM_read_bio_X509(bio.get(), &openSSLCert, nullptr, nullptr);
+ if (x509certFromPEM && openSSLCert) {
+ std::shared_ptr<X509> x509Cert(openSSLCert, X509_free);
+ certificateChain.push_back(std::make_shared<OpenSSLCertificate>(x509Cert));
+ openSSLCert = nullptr;
+ while ((x509certFromPEM = PEM_read_bio_X509(bio.get(), &openSSLCert, nullptr, nullptr)) != nullptr) {
+ std::shared_ptr<X509> x509Cert(openSSLCert, X509_free);
+ certificateChain.push_back(std::make_shared<OpenSSLCertificate>(x509Cert));
+ openSSLCert = nullptr;
+ }
+ }
+
+ return certificateChain;
+}
+
+}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h b/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h
index c996cd5..af45a33 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h
+++ b/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2018 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -12,8 +12,10 @@
namespace Swift {
class OpenSSLCertificateFactory : public CertificateFactory {
public:
- virtual Certificate* createCertificateFromDER(const ByteArray& der) {
- return new OpenSSLCertificate(der);
- }
+ OpenSSLCertificateFactory();
+ virtual ~OpenSSLCertificateFactory() override final;
+
+ virtual Certificate* createCertificateFromDER(const ByteArray& der) override final;
+ virtual std::vector<Certificate::ref> createCertificateChain(const ByteArray& data) override final;
};
}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLContext.cpp b/Swiften/TLS/OpenSSL/OpenSSLContext.cpp
index 0805917..89917ee 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContext.cpp
+++ b/Swiften/TLS/OpenSSL/OpenSSLContext.cpp
@@ -1,8 +1,9 @@
/*
- * Copyright (c) 2010-2016 Isode Limited.
+ * Copyright (c) 2010-2018 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+
#include <Swiften/Base/Platform.h>
#ifdef SWIFTEN_PLATFORM_WINDOWS
@@ -10,15 +11,21 @@
#include <wincrypt.h>
#endif
+#include <cassert>
+#include <memory>
#include <vector>
+
+
+#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/pkcs12.h>
-#include <memory>
#if defined(SWIFTEN_PLATFORM_MACOSX)
#include <Security/Security.h>
#endif
+#include <Swiften/Base/Log.h>
+#include <Swiften/Base/Algorithm.h>
#include <Swiften/TLS/OpenSSL/OpenSSLContext.h>
#include <Swiften/TLS/OpenSSL/OpenSSLCertificate.h>
#include <Swiften/TLS/CertificateWithKey.h>
@@ -39,10 +46,66 @@ static void freeX509Stack(STACK_OF(X509)* stack) {
sk_X509_free(stack);
}
-OpenSSLContext::OpenSSLContext() : state_(Start), context_(0), handle_(0), readBIO_(0), writeBIO_(0) {
+namespace {
+ class OpenSSLInitializerFinalizer {
+ public:
+ OpenSSLInitializerFinalizer() {
+ SSL_load_error_strings();
+ SSL_library_init();
+ OpenSSL_add_all_algorithms();
+
+ // Disable compression
+ /*
+ STACK_OF(SSL_COMP)* compressionMethods = SSL_COMP_get_compression_methods();
+ sk_SSL_COMP_zero(compressionMethods);*/
+ }
+
+ ~OpenSSLInitializerFinalizer() {
+ EVP_cleanup();
+ }
+
+ OpenSSLInitializerFinalizer(const OpenSSLInitializerFinalizer &) = delete;
+ };
+
+ std::unique_ptr<SSL_CTX> createSSL_CTX(OpenSSLContext::Mode mode) {
+ std::unique_ptr<SSL_CTX> sslCtx;
+ switch (mode) {
+ case OpenSSLContext::Mode::Client:
+ sslCtx = std::unique_ptr<SSL_CTX>(SSL_CTX_new(SSLv23_client_method()));
+ break;
+ case OpenSSLContext::Mode::Server:
+ sslCtx = std::unique_ptr<SSL_CTX>(SSL_CTX_new(SSLv23_server_method()));
+ break;
+ }
+ return sslCtx;
+ }
+
+ std::string openSSLInternalErrorToString() {
+ auto bio = std::shared_ptr<BIO>(BIO_new(BIO_s_mem()), BIO_free);
+ ERR_print_errors(bio.get());
+ std::string errorString;
+ errorString.resize(BIO_pending(bio.get()));
+ BIO_read(bio.get(), (void*)errorString.data(), errorString.size());
+ return errorString;
+ }
+ }
+
+OpenSSLContext::OpenSSLContext(Mode mode) : mode_(mode), state_(State::Start) {
ensureLibraryInitialized();
- context_ = SSL_CTX_new(SSLv23_client_method());
- SSL_CTX_set_options(context_, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
+ context_ = createSSL_CTX(mode_);
+ SSL_CTX_set_options(context_.get(), SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
+
+ if (mode_ == Mode::Server) {
+#if OPENSSL_VERSION_NUMBER < 0x1010
+ // Automatically select highest preference curve used for ECDH temporary keys used during
+ // key exchange if possible.
+ // Since version 1.1.0, this option is always enabled.
+ SSL_CTX_set_ecdh_auto(context_.get(), 1);
+#endif
+
+ SSL_CTX_set_tlsext_servername_arg(context_.get(), this);
+ SSL_CTX_set_tlsext_servername_callback(context_.get(), OpenSSLContext::handleServerNameCallback);
+ }
// TODO: implement CRL checking
// TODO: download CRL (HTTP transport)
@@ -52,7 +115,7 @@ OpenSSLContext::OpenSSLContext() : state_(Start), context_(0), handle_(0), readB
// TODO: handle OCSP stapling see https://www.rfc-editor.org/rfc/rfc4366.txt
// Load system certs
#if defined(SWIFTEN_PLATFORM_WINDOWS)
- X509_STORE* store = SSL_CTX_get_cert_store(context_);
+ X509_STORE* store = SSL_CTX_get_cert_store(context_.get());
HCERTSTORE systemStore = CertOpenSystemStore(0, "ROOT");
if (systemStore) {
PCCERT_CONTEXT certContext = NULL;
@@ -68,7 +131,7 @@ OpenSSLContext::OpenSSLContext() : state_(Start), context_(0), handle_(0), readB
}
}
#elif !defined(SWIFTEN_PLATFORM_MACOSX)
- SSL_CTX_set_default_verify_paths(context_);
+ SSL_CTX_set_default_verify_paths(context_.get());
#elif defined(SWIFTEN_PLATFORM_MACOSX) && !defined(SWIFTEN_PLATFORM_IPHONE)
// On Mac OS X 10.5 (OpenSSL < 0.9.8), OpenSSL does not automatically look in the system store.
// On Mac OS X 10.6 (OpenSSL >= 0.9.8), OpenSSL *does* look in the system store to determine trust.
@@ -76,7 +139,7 @@ OpenSSLContext::OpenSSLContext() : state_(Start), context_(0), handle_(0), readB
// the certificates first. See
// http://opensource.apple.com/source/OpenSSL098/OpenSSL098-27/src/crypto/x509/x509_vfy_apple.c
// to understand why. We therefore add all certs from the system store ourselves.
- X509_STORE* store = SSL_CTX_get_cert_store(context_);
+ X509_STORE* store = SSL_CTX_get_cert_store(context_.get());
CFArrayRef anchorCertificates;
if (SecTrustCopyAnchorCertificates(&anchorCertificates) == 0) {
for (int i = 0; i < CFArrayGetCount(anchorCertificates); ++i) {
@@ -99,51 +162,96 @@ OpenSSLContext::OpenSSLContext() : state_(Start), context_(0), handle_(0), readB
}
OpenSSLContext::~OpenSSLContext() {
- SSL_free(handle_);
- SSL_CTX_free(context_);
}
void OpenSSLContext::ensureLibraryInitialized() {
- static bool isLibraryInitialized = false;
- if (!isLibraryInitialized) {
- SSL_load_error_strings();
- SSL_library_init();
- OpenSSL_add_all_algorithms();
+ static OpenSSLInitializerFinalizer openSSLInit;
+}
- // Disable compression
- /*
- STACK_OF(SSL_COMP)* compressionMethods = SSL_COMP_get_compression_methods();
- sk_SSL_COMP_zero(compressionMethods);*/
+void OpenSSLContext::initAndSetBIOs() {
+ // Ownership of BIOs is transferred
+ readBIO_ = BIO_new(BIO_s_mem());
+ writeBIO_ = BIO_new(BIO_s_mem());
+ SSL_set_bio(handle_.get(), readBIO_, writeBIO_);
+}
- isLibraryInitialized = true;
+void OpenSSLContext::accept() {
+ assert(mode_ == Mode::Server);
+ handle_ = std::unique_ptr<SSL>(SSL_new(context_.get()));
+ if (!handle_) {
+ state_ = State::Error;
+ onError(std::make_shared<TLSError>());
+ return;
}
+
+ initAndSetBIOs();
+
+ state_ = State::Accepting;
+ doAccept();
}
void OpenSSLContext::connect() {
- handle_ = SSL_new(context_);
- if (handle_ == nullptr) {
- state_ = Error;
+ connect(std::string());
+}
+
+void OpenSSLContext::connect(const std::string& requestedServerName) {
+ assert(mode_ == Mode::Client);
+ handle_ = std::unique_ptr<SSL>(SSL_new(context_.get()));
+ if (!handle_) {
+ state_ = State::Error;
onError(std::make_shared<TLSError>());
return;
}
- // Ownership of BIOs is ransferred
- readBIO_ = BIO_new(BIO_s_mem());
- writeBIO_ = BIO_new(BIO_s_mem());
- SSL_set_bio(handle_, readBIO_, writeBIO_);
+ if (!requestedServerName.empty()) {
+ if (SSL_set_tlsext_host_name(handle_.get(), const_cast<char*>(requestedServerName.c_str())) != 1) {
+ SWIFT_LOG(error) << "Failed on SSL_set_tlsext_host_name()." << std::endl;
+ }
+ }
+
+ // Ownership of BIOs is transferred to the SSL_CTX instance in handle_.
+ initAndSetBIOs();
- state_ = Connecting;
+ state_ = State::Connecting;
doConnect();
}
+void OpenSSLContext::doAccept() {
+ auto acceptResult = SSL_accept(handle_.get());
+ auto error = SSL_get_error(handle_.get(), acceptResult);
+ switch (error) {
+ case SSL_ERROR_NONE: {
+ state_ = State::Connected;
+ //std::cout << x->name << std::endl;
+ //const char* comp = SSL_get_current_compression(handle_.get());
+ //std::cout << "Compression: " << SSL_COMP_get_name(comp) << std::endl;
+ onConnected();
+ // The following call is important so the client knowns the handshake is finished.
+ sendPendingDataToNetwork();
+ break;
+ }
+ case SSL_ERROR_WANT_READ:
+ sendPendingDataToNetwork();
+ break;
+ case SSL_ERROR_WANT_WRITE:
+ sendPendingDataToNetwork();
+ break;
+ default:
+ SWIFT_LOG(warning) << openSSLInternalErrorToString() << std::endl;
+ state_ = State::Error;
+ onError(std::make_shared<TLSError>());
+ sendPendingDataToNetwork();
+ }
+}
+
void OpenSSLContext::doConnect() {
- int connectResult = SSL_connect(handle_);
- int error = SSL_get_error(handle_, connectResult);
+ int connectResult = SSL_connect(handle_.get());
+ int error = SSL_get_error(handle_.get(), connectResult);
switch (error) {
case SSL_ERROR_NONE: {
- state_ = Connected;
+ state_ = State::Connected;
//std::cout << x->name << std::endl;
- //const char* comp = SSL_get_current_compression(handle_);
+ //const char* comp = SSL_get_current_compression(handle_.get());
//std::cout << "Compression: " << SSL_COMP_get_name(comp) << std::endl;
onConnected();
break;
@@ -152,11 +260,30 @@ void OpenSSLContext::doConnect() {
sendPendingDataToNetwork();
break;
default:
- state_ = Error;
+ SWIFT_LOG(warning) << openSSLInternalErrorToString() << std::endl;
+ state_ = State::Error;
onError(std::make_shared<TLSError>());
}
}
+int OpenSSLContext::handleServerNameCallback(SSL* ssl, int*, void* arg) {
+ if (ssl == nullptr)
+ return SSL_TLSEXT_ERR_NOACK;
+
+ const char* servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
+ if (servername) {
+ auto serverNameString = std::string(servername);
+ auto context = reinterpret_cast<OpenSSLContext*>(arg);
+ context->onServerNameRequested(serverNameString);
+
+ if (context->abortTLSHandshake_) {
+ context->abortTLSHandshake_ = false;
+ return SSL_TLSEXT_ERR_ALERT_FATAL;
+ }
+ }
+ return SSL_TLSEXT_ERR_OK;
+}
+
void OpenSSLContext::sendPendingDataToNetwork() {
int size = BIO_pending(writeBIO_);
if (size > 0) {
@@ -170,23 +297,26 @@ void OpenSSLContext::sendPendingDataToNetwork() {
void OpenSSLContext::handleDataFromNetwork(const SafeByteArray& data) {
BIO_write(readBIO_, vecptr(data), data.size());
switch (state_) {
- case Connecting:
+ case State::Accepting:
+ doAccept();
+ break;
+ case State::Connecting:
doConnect();
break;
- case Connected:
+ case State::Connected:
sendPendingDataToApplication();
break;
- case Start: assert(false); break;
- case Error: /*assert(false);*/ break;
+ case State::Start: assert(false); break;
+ case State::Error: /*assert(false);*/ break;
}
}
void OpenSSLContext::handleDataFromApplication(const SafeByteArray& data) {
- if (SSL_write(handle_, vecptr(data), data.size()) >= 0) {
+ if (SSL_write(handle_.get(), vecptr(data), data.size()) >= 0) {
sendPendingDataToNetwork();
}
else {
- state_ = Error;
+ state_ = State::Error;
onError(std::make_shared<TLSError>());
}
}
@@ -194,19 +324,115 @@ void OpenSSLContext::handleDataFromApplication(const SafeByteArray& data) {
void OpenSSLContext::sendPendingDataToApplication() {
SafeByteArray data;
data.resize(SSL_READ_BUFFERSIZE);
- int ret = SSL_read(handle_, vecptr(data), data.size());
+ int ret = SSL_read(handle_.get(), vecptr(data), data.size());
while (ret > 0) {
data.resize(ret);
onDataForApplication(data);
data.resize(SSL_READ_BUFFERSIZE);
- ret = SSL_read(handle_, vecptr(data), data.size());
+ ret = SSL_read(handle_.get(), vecptr(data), data.size());
}
- if (ret < 0 && SSL_get_error(handle_, ret) != SSL_ERROR_WANT_READ) {
- state_ = Error;
+ if (ret < 0 && SSL_get_error(handle_.get(), ret) != SSL_ERROR_WANT_READ) {
+ state_ = State::Error;
onError(std::make_shared<TLSError>());
}
}
+bool OpenSSLContext::setCertificateChain(const std::vector<Certificate::ref>& certificateChain) {
+ if (certificateChain.size() == 0) {
+ SWIFT_LOG(warning) << "Trying to load empty certificate chain." << std::endl;
+ return false;
+ }
+
+ // load endpoint certificate
+ auto openSSLCert = std::dynamic_pointer_cast<OpenSSLCertificate>(certificateChain[0]);
+ if (!openSSLCert) {
+ return false;
+ }
+
+ if (SSL_CTX_use_certificate(context_.get(), openSSLCert->getInternalX509().get()) != 1) {
+ return false;
+ }
+
+ if (certificateChain.size() > 1) {
+ for (auto certificate : range(certificateChain.begin() + 1, certificateChain.end())) {
+ auto openSSLCert = std::dynamic_pointer_cast<OpenSSLCertificate>(certificate);
+ if (!openSSLCert) {
+ return false;
+ }
+ if (SSL_CTX_add_extra_chain_cert(context_.get(), openSSLCert->getInternalX509().get()) != 1) {
+ SWIFT_LOG(warning) << "Trying to load empty certificate chain." << std::endl;
+ return false;
+ }
+ }
+ }
+
+ if (handle_) {
+ // This workaround is needed as OpenSSL has a shortcut to not do anything
+ // if you set the SSL_CTX to the existing SSL_CTX and not reloading the
+ // certificates from the SSL_CTX.
+ auto dummyContext = createSSL_CTX(mode_);
+ SSL_set_SSL_CTX(handle_.get(), dummyContext.get());
+ SSL_set_SSL_CTX(handle_.get(), context_.get());
+ }
+
+ return true;
+}
+
+int empty_or_preset_password_cb(char* buf, int max_len, int flag, void* password);
+
+int empty_or_preset_password_cb(char* buf, int max_len, int /* flag */, void* password) {
+ char* charPassword = (char*)password;
+ if (charPassword == nullptr) {
+ return 0;
+ }
+ int len = strlen(charPassword);
+ if(len > max_len) {
+ return 0;
+ }
+ memcpy(buf, charPassword, len);
+ return len;
+}
+
+bool OpenSSLContext::setPrivateKey(const PrivateKey::ref& privateKey) {
+ if (privateKey->getData().size() > std::numeric_limits<int>::max()) {
+ return false;
+ }
+
+ auto bio = std::shared_ptr<BIO>(BIO_new(BIO_s_mem()), BIO_free);
+ BIO_write(bio.get(), vecptr(privateKey->getData()), int(privateKey->getData().size()));
+
+ SafeByteArray safePassword;
+ void* password = nullptr;
+ if (privateKey->getPassword()) {
+ safePassword = privateKey->getPassword().get();
+ safePassword.push_back(0);
+ password = safePassword.data();
+ }
+ auto resultKey = PEM_read_bio_PrivateKey(bio.get(), nullptr, empty_or_preset_password_cb, password);
+ if (resultKey) {
+ if (handle_) {
+ auto result = SSL_use_PrivateKey(handle_.get(), resultKey);;
+ if (result != 1) {
+ return false;
+ }
+ }
+ else {
+ auto result = SSL_CTX_use_PrivateKey(context_.get(), resultKey);
+ if (result != 1) {
+ return false;
+ }
+ }
+ }
+ else {
+ return false;
+ }
+ return true;
+}
+
+void OpenSSLContext::setAbortTLSHandshake(bool abort) {
+ abortTLSHandshake_ = abort;
+}
+
bool OpenSSLContext::setClientCertificate(CertificateWithKey::ref certificate) {
std::shared_ptr<PKCS12Certificate> pkcs12Certificate = std::dynamic_pointer_cast<PKCS12Certificate>(certificate);
if (!pkcs12Certificate || pkcs12Certificate->isNull()) {
@@ -216,16 +442,16 @@ bool OpenSSLContext::setClientCertificate(CertificateWithKey::ref certificate) {
// Create a PKCS12 structure
BIO* bio = BIO_new(BIO_s_mem());
BIO_write(bio, vecptr(pkcs12Certificate->getData()), pkcs12Certificate->getData().size());
- std::shared_ptr<PKCS12> pkcs12(d2i_PKCS12_bio(bio, NULL), PKCS12_free);
+ std::shared_ptr<PKCS12> pkcs12(d2i_PKCS12_bio(bio, nullptr), PKCS12_free);
BIO_free(bio);
if (!pkcs12) {
return false;
}
// Parse PKCS12
- X509 *certPtr = 0;
- EVP_PKEY* privateKeyPtr = 0;
- STACK_OF(X509)* caCertsPtr = 0;
+ X509 *certPtr = nullptr;
+ EVP_PKEY* privateKeyPtr = nullptr;
+ STACK_OF(X509)* caCertsPtr = nullptr;
SafeByteArray password(pkcs12Certificate->getPassword());
password.push_back(0);
int result = PKCS12_parse(pkcs12.get(), reinterpret_cast<const char*>(vecptr(password)), &privateKeyPtr, &certPtr, &caCertsPtr);
@@ -237,21 +463,40 @@ bool OpenSSLContext::setClientCertificate(CertificateWithKey::ref certificate) {
std::shared_ptr<STACK_OF(X509)> caCerts(caCertsPtr, freeX509Stack);
// Use the key & certificates
- if (SSL_CTX_use_certificate(context_, cert.get()) != 1) {
+ if (SSL_CTX_use_certificate(context_.get(), cert.get()) != 1) {
return false;
}
- if (SSL_CTX_use_PrivateKey(context_, privateKey.get()) != 1) {
+ if (SSL_CTX_use_PrivateKey(context_.get(), privateKey.get()) != 1) {
return false;
}
for (int i = 0; i < sk_X509_num(caCerts.get()); ++i) {
- SSL_CTX_add_extra_chain_cert(context_, sk_X509_value(caCerts.get(), i));
+ SSL_CTX_add_extra_chain_cert(context_.get(), sk_X509_value(caCerts.get(), i));
}
return true;
}
+bool OpenSSLContext::setDiffieHellmanParameters(const ByteArray& parametersInOpenSslDer) {
+ auto bio = std::unique_ptr<BIO, decltype(&BIO_free)>(BIO_new(BIO_s_mem()), BIO_free);
+ if (bio) {
+ BIO_write(bio.get(), vecptr(parametersInOpenSslDer), parametersInOpenSslDer.size());
+ auto result = 0L;
+ if (auto dhparams = d2i_DHparams_bio(bio.get(), NULL)) {
+ if (handle_) {
+ result = SSL_set_tmp_dh(handle_.get(), dhparams);
+ }
+ else {
+ result = SSL_CTX_set_tmp_dh(context_.get(), dhparams);
+ }
+ DH_free(dhparams);
+ }
+ return result == 1;
+ }
+ return false;
+}
+
std::vector<Certificate::ref> OpenSSLContext::getPeerCertificateChain() const {
std::vector<Certificate::ref> result;
- STACK_OF(X509)* chain = SSL_get_peer_cert_chain(handle_);
+ STACK_OF(X509)* chain = SSL_get_peer_cert_chain(handle_.get());
for (int i = 0; i < sk_X509_num(chain); ++i) {
std::shared_ptr<X509> x509Cert(X509_dup(sk_X509_value(chain, i)), X509_free);
@@ -262,7 +507,7 @@ std::vector<Certificate::ref> OpenSSLContext::getPeerCertificateChain() const {
}
std::shared_ptr<CertificateVerificationError> OpenSSLContext::getPeerCertificateVerificationError() const {
- int verifyResult = SSL_get_verify_result(handle_);
+ int verifyResult = SSL_get_verify_result(handle_.get());
if (verifyResult != X509_V_OK) {
return std::make_shared<CertificateVerificationError>(getVerificationErrorTypeForResult(verifyResult));
}
@@ -274,11 +519,19 @@ std::shared_ptr<CertificateVerificationError> OpenSSLContext::getPeerCertificate
ByteArray OpenSSLContext::getFinishMessage() const {
ByteArray data;
data.resize(MAX_FINISHED_SIZE);
- size_t size = SSL_get_finished(handle_, vecptr(data), data.size());
+ auto size = SSL_get_finished(handle_.get(), vecptr(data), data.size());
data.resize(size);
return data;
}
+ByteArray OpenSSLContext::getPeerFinishMessage() const {
+ ByteArray data;
+ data.resize(MAX_FINISHED_SIZE);
+ auto size = SSL_get_peer_finished(handle_.get(), vecptr(data), data.size());
+ data.resize(size);
+ return data;
+ }
+
CertificateVerificationError::Type OpenSSLContext::getVerificationErrorTypeForResult(int result) {
assert(result != 0);
switch (result) {
diff --git a/Swiften/TLS/OpenSSL/OpenSSLContext.h b/Swiften/TLS/OpenSSL/OpenSSLContext.h
index e75b3c9..cfa852a 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContext.h
+++ b/Swiften/TLS/OpenSSL/OpenSSLContext.h
@@ -1,11 +1,13 @@
/*
- * Copyright (c) 2010-2016 Isode Limited.
+ * Copyright (c) 2010-2018 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
#include <boost/noncopyable.hpp>
#include <boost/signals2.hpp>
@@ -15,40 +17,69 @@
#include <Swiften/TLS/CertificateWithKey.h>
#include <Swiften/TLS/TLSContext.h>
-namespace Swift {
+namespace std {
+ template<>
+ class default_delete<SSL_CTX> {
+ public:
+ void operator()(SSL_CTX *ptr) {
+ SSL_CTX_free(ptr);
+ }
+ };
+ template<>
+ class default_delete<SSL> {
+ public:
+ void operator()(SSL *ptr) {
+ SSL_free(ptr);
+ }
+ };
+}
+
+namespace Swift {
class OpenSSLContext : public TLSContext, boost::noncopyable {
public:
- OpenSSLContext();
- virtual ~OpenSSLContext();
+ OpenSSLContext(Mode mode);
+ virtual ~OpenSSLContext() override final;
- void connect();
- bool setClientCertificate(CertificateWithKey::ref cert);
+ void accept() override final;
+ void connect() override final;
+ void connect(const std::string& requestHostname) override final;
- void handleDataFromNetwork(const SafeByteArray&);
- void handleDataFromApplication(const SafeByteArray&);
+ bool setCertificateChain(const std::vector<Certificate::ref>& certificateChain) override final;
+ bool setPrivateKey(const PrivateKey::ref& privateKey) override final;
+ bool setClientCertificate(CertificateWithKey::ref cert) override final;
+ void setAbortTLSHandshake(bool abort) override final;
+ bool setDiffieHellmanParameters(const ByteArray& parametersInOpenSslDer) override final;
- std::vector<Certificate::ref> getPeerCertificateChain() const;
- std::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
+ void handleDataFromNetwork(const SafeByteArray&) override final;
+ void handleDataFromApplication(const SafeByteArray&) override final;
- virtual ByteArray getFinishMessage() const;
+ std::vector<Certificate::ref> getPeerCertificateChain() const override final;
+ std::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const override final;
+
+ virtual ByteArray getFinishMessage() const override final;
+ virtual ByteArray getPeerFinishMessage() const override final;
private:
static void ensureLibraryInitialized();
-
+ static int handleServerNameCallback(SSL *ssl, int *ad, void *arg);
static CertificateVerificationError::Type getVerificationErrorTypeForResult(int);
+ void initAndSetBIOs();
+ void doAccept();
void doConnect();
void sendPendingDataToNetwork();
void sendPendingDataToApplication();
private:
- enum State { Start, Connecting, Connected, Error };
+ enum class State { Start, Accepting, Connecting, Connected, Error };
+ const Mode mode_;
State state_;
- SSL_CTX* context_;
- SSL* handle_;
- BIO* readBIO_;
- BIO* writeBIO_;
+ std::unique_ptr<SSL_CTX> context_;
+ std::unique_ptr<SSL> handle_;
+ BIO* readBIO_ = nullptr;
+ BIO* writeBIO_ = nullptr;
+ bool abortTLSHandshake_ = false;
};
}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp
index 9f7b2aa..9d0ad72 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp
+++ b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp
@@ -1,22 +1,48 @@
/*
- * Copyright (c) 2010-2016 Isode Limited.
+ * Copyright (c) 2010-2018 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/TLS/OpenSSL/OpenSSLContextFactory.h>
+#include <openssl/bio.h>
+#include <openssl/dh.h>
+#include <openssl/pem.h>
+
#include <Swiften/Base/Log.h>
#include <Swiften/TLS/OpenSSL/OpenSSLContext.h>
+#pragma clang diagnostic ignored "-Wshorten-64-to-32"
+
namespace Swift {
bool OpenSSLContextFactory::canCreate() const {
return true;
}
-TLSContext* OpenSSLContextFactory::createTLSContext(const TLSOptions&) {
- return new OpenSSLContext();
+TLSContext* OpenSSLContextFactory::createTLSContext(const TLSOptions&, TLSContext::Mode mode) {
+ return new OpenSSLContext(mode);
+}
+
+ByteArray OpenSSLContextFactory::convertDHParametersFromPEMToDER(const std::string& dhParametersInPEM) {
+ ByteArray dhParametersInDER;
+
+ auto bio = std::unique_ptr<BIO, decltype(&BIO_free)>(BIO_new(BIO_s_mem()), BIO_free);
+ if (bio) {
+ BIO_write(bio.get(), dhParametersInPEM.data(), dhParametersInPEM.size());
+ if (auto params = PEM_read_bio_DHparams(bio.get(), nullptr, nullptr, nullptr)) {
+ unsigned char* buffer = nullptr;
+ auto len = i2d_DHparams(params, &buffer);
+ if (len > 0) {
+ dhParametersInDER = createByteArray(buffer, static_cast<size_t>(len));
+ free(buffer);
+ }
+ DH_free(params);
+
+ }
+ }
+ return dhParametersInDER;
}
void OpenSSLContextFactory::setCheckCertificateRevocation(bool check) {
diff --git a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h
index e121a1a..db7fa34 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h
+++ b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h
@@ -1,23 +1,23 @@
/*
- * Copyright (c) 2010-2016 Isode Limited.
+ * Copyright (c) 2010-2018 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <cassert>
-
#include <Swiften/TLS/TLSContextFactory.h>
namespace Swift {
class OpenSSLContextFactory : public TLSContextFactory {
public:
- bool canCreate() const;
- virtual TLSContext* createTLSContext(const TLSOptions& tlsOptions);
+ bool canCreate() const override final;
+ virtual TLSContext* createTLSContext(const TLSOptions& tlsOptions, TLSContext::Mode mode) override final;
+
+ virtual ByteArray convertDHParametersFromPEMToDER(const std::string& dhParametersInPEM) override final;
// Not supported
- virtual void setCheckCertificateRevocation(bool b);
- virtual void setDisconnectOnCardRemoval(bool b);
+ virtual void setCheckCertificateRevocation(bool b) override final;
+ virtual void setDisconnectOnCardRemoval(bool b) override final;
};
}