1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
42 //#define QSSLSOCKET_DEBUG
44 #include "qsslsocket_openssl_p.h"
45 #include "qsslsocket_openssl_symbols_p.h"
46 #include "qsslsocket.h"
47 #include "qsslcertificate_p.h"
48 #include "qsslcipher_p.h"
50 #include <QtCore/qdatetime.h>
51 #include <QtCore/qdebug.h>
52 #include <QtCore/qdir.h>
53 #include <QtCore/qdiriterator.h>
54 #include <QtCore/qelapsedtimer.h>
55 #include <QtCore/qfile.h>
56 #include <QtCore/qfileinfo.h>
57 #include <QtCore/qmutex.h>
58 #include <QtCore/qthread.h>
59 #include <QtCore/qurl.h>
60 #include <QtCore/qvarlengtharray.h>
61 #include <QLibrary> // for loading the security lib for the CA store
65 #if defined(Q_OS_MAC) && !defined(Q_OS_IOS)
66 #define kSecTrustSettingsDomainSystem 2 // so we do not need to include the header file
67 PtrSecCertificateGetData QSslSocketPrivate::ptrSecCertificateGetData = 0;
68 PtrSecTrustSettingsCopyCertificates QSslSocketPrivate::ptrSecTrustSettingsCopyCertificates = 0;
69 PtrSecTrustCopyAnchorCertificates QSslSocketPrivate::ptrSecTrustCopyAnchorCertificates = 0;
70 #elif defined(Q_OS_WIN)
71 PtrCertOpenSystemStoreW QSslSocketPrivate::ptrCertOpenSystemStoreW = 0;
72 PtrCertFindCertificateInStore QSslSocketPrivate::ptrCertFindCertificateInStore = 0;
73 PtrCertCloseStore QSslSocketPrivate::ptrCertCloseStore = 0;
76 bool QSslSocketPrivate::s_libraryLoaded = false;
77 bool QSslSocketPrivate::s_loadedCiphersAndCerts = false;
78 bool QSslSocketPrivate::s_loadRootCertsOnDemand = false;
82 From OpenSSL's thread(3) manual page:
84 OpenSSL can safely be used in multi-threaded applications provided that at
85 least two callback functions are set.
87 locking_function(int mode, int n, const char *file, int line) is needed to
88 perform locking on shared data structures. (Note that OpenSSL uses a
89 number of global data structures that will be implicitly shared
90 whenever multiple threads use OpenSSL.) Multi-threaded
91 applications will crash at random if it is not set. ...
93 id_function(void) is a function that returns a thread ID. It is not
94 needed on Windows nor on platforms where getpid() returns a different
95 ID for each thread (most notably Linux)
100 inline QOpenSslLocks()
101 : initLocker(QMutex::Recursive),
102 locksLocker(QMutex::Recursive)
104 QMutexLocker locker(&locksLocker);
105 int numLocks = q_CRYPTO_num_locks();
106 locks = new QMutex *[numLocks];
107 memset(locks, 0, numLocks * sizeof(QMutex *));
109 inline ~QOpenSslLocks()
111 QMutexLocker locker(&locksLocker);
112 for (int i = 0; i < q_CRYPTO_num_locks(); ++i)
116 QSslSocketPrivate::deinitialize();
118 inline QMutex *lock(int num)
120 QMutexLocker locker(&locksLocker);
121 QMutex *tmp = locks[num];
123 tmp = locks[num] = new QMutex(QMutex::Recursive);
142 Q_GLOBAL_STATIC(QOpenSslLocks, openssl_locks)
145 static void locking_function(int mode, int lockNumber, const char *, int)
147 QMutex *mutex = openssl_locks()->lock(lockNumber);
150 if (mode & CRYPTO_LOCK)
155 static unsigned long id_function()
157 return (quintptr)QThread::currentThreadId();
161 QSslSocketBackendPrivate::QSslSocketBackendPrivate()
169 // Calls SSL_library_init().
173 QSslSocketBackendPrivate::~QSslSocketBackendPrivate()
178 QSslCipher QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(SSL_CIPHER *cipher)
183 QString descriptionOneLine = QString::fromLatin1(q_SSL_CIPHER_description(cipher, buf, sizeof(buf)));
185 QStringList descriptionList = descriptionOneLine.split(QLatin1String(" "), QString::SkipEmptyParts);
186 if (descriptionList.size() > 5) {
188 ciph.d->isNull = false;
189 ciph.d->name = descriptionList.at(0);
191 QString protoString = descriptionList.at(1);
192 ciph.d->protocolString = protoString;
193 ciph.d->protocol = QSsl::UnknownProtocol;
194 if (protoString == QLatin1String("SSLv3"))
195 ciph.d->protocol = QSsl::SslV3;
196 else if (protoString == QLatin1String("SSLv2"))
197 ciph.d->protocol = QSsl::SslV2;
198 else if (protoString == QLatin1String("TLSv1"))
199 ciph.d->protocol = QSsl::TlsV1_0;
200 else if (protoString == QLatin1String("TLSv1.1"))
201 ciph.d->protocol = QSsl::TlsV1_1;
202 else if (protoString == QLatin1String("TLSv1.2"))
203 ciph.d->protocol = QSsl::TlsV1_2;
205 if (descriptionList.at(2).startsWith(QLatin1String("Kx=")))
206 ciph.d->keyExchangeMethod = descriptionList.at(2).mid(3);
207 if (descriptionList.at(3).startsWith(QLatin1String("Au=")))
208 ciph.d->authenticationMethod = descriptionList.at(3).mid(3);
209 if (descriptionList.at(4).startsWith(QLatin1String("Enc=")))
210 ciph.d->encryptionMethod = descriptionList.at(4).mid(4);
211 ciph.d->exportable = (descriptionList.size() > 6 && descriptionList.at(6) == QLatin1String("export"));
213 ciph.d->bits = cipher->strength_bits;
214 ciph.d->supportedBits = cipher->alg_bits;
220 // ### This list is shared between all threads, and protected by a
221 // mutex. Investigate using thread local storage instead.
225 QList<QPair<int, int> > errors;
227 Q_GLOBAL_STATIC(QSslErrorList, _q_sslErrorList)
228 static int q_X509Callback(int ok, X509_STORE_CTX *ctx)
231 // Store the error and at which depth the error was detected.
232 _q_sslErrorList()->errors << qMakePair<int, int>(q_X509_STORE_CTX_get_error(ctx), q_X509_STORE_CTX_get_error_depth(ctx));
233 #ifdef QSSLSOCKET_DEBUG
234 qDebug() << "verification error: dumping bad certificate";
235 qDebug() << QSslCertificatePrivate::QSslCertificate_from_X509(q_X509_STORE_CTX_get_current_cert(ctx)).toPem();
236 qDebug() << "dumping chain";
237 foreach (QSslCertificate cert, QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates(q_X509_STORE_CTX_get_chain(ctx))) {
238 QString certFormat(QStringLiteral("O=%1 CN=%2 L=%3 OU=%4 C=%5 ST=%6"));
239 qDebug() << "Issuer:" << "O=" << cert.issuerInfo(QSslCertificate::Organization)
240 << "CN=" << cert.issuerInfo(QSslCertificate::CommonName)
241 << "L=" << cert.issuerInfo(QSslCertificate::LocalityName)
242 << "OU=" << cert.issuerInfo(QSslCertificate::OrganizationalUnitName)
243 << "C=" << cert.issuerInfo(QSslCertificate::CountryName)
244 << "ST=" << cert.issuerInfo(QSslCertificate::StateOrProvinceName);
245 qDebug() << "Subject:" << "O=" << cert.subjectInfo(QSslCertificate::Organization)
246 << "CN=" << cert.subjectInfo(QSslCertificate::CommonName)
247 << "L=" << cert.subjectInfo(QSslCertificate::LocalityName)
248 << "OU=" << cert.subjectInfo(QSslCertificate::OrganizationalUnitName)
249 << "C=" << cert.subjectInfo(QSslCertificate::CountryName)
250 << "ST=" << cert.subjectInfo(QSslCertificate::StateOrProvinceName);
251 qDebug() << "Valid:" << cert.effectiveDate() << "-" << cert.expiryDate();
255 // Always return OK to allow verification to continue. We're handle the
256 // errors gracefully after collecting all errors, after verification has
261 long QSslSocketBackendPrivate::setupOpenSslOptions(QSsl::SslProtocol protocol, QSsl::SslOptions sslOptions)
264 if (protocol == QSsl::TlsV1SslV3 || protocol == QSsl::SecureProtocols)
265 options = SSL_OP_ALL|SSL_OP_NO_SSLv2;
267 options = SSL_OP_ALL;
269 // This option is disabled by default, so we need to be able to clear it
270 if (sslOptions & QSsl::SslOptionDisableEmptyFragments)
271 options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
273 options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
275 #ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
276 // This option is disabled by default, so we need to be able to clear it
277 if (sslOptions & QSsl::SslOptionDisableLegacyRenegotiation)
278 options &= ~SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
280 options |= SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
283 #ifdef SSL_OP_NO_TICKET
284 if (sslOptions & QSsl::SslOptionDisableSessionTickets)
285 options |= SSL_OP_NO_TICKET;
287 #ifdef SSL_OP_NO_COMPRESSION
288 if (sslOptions & QSsl::SslOptionDisableCompression)
289 options |= SSL_OP_NO_COMPRESSION;
295 bool QSslSocketBackendPrivate::initSslContext()
299 // Create and initialize SSL context. Accept SSLv2, SSLv3 and TLSv1_0.
300 bool client = (mode == QSslSocket::SslClientMode);
302 bool reinitialized = false;
305 switch (configuration.protocol) {
307 #ifndef OPENSSL_NO_SSL2
308 ctx = q_SSL_CTX_new(client ? q_SSLv2_client_method() : q_SSLv2_server_method());
310 ctx = 0; // SSL 2 not supported by the system, but chosen deliberately -> error
314 ctx = q_SSL_CTX_new(client ? q_SSLv3_client_method() : q_SSLv3_server_method());
316 case QSsl::SecureProtocols: // SslV2 will be disabled below
317 case QSsl::TlsV1SslV3: // SslV2 will be disabled below
318 case QSsl::AnyProtocol:
320 ctx = q_SSL_CTX_new(client ? q_SSLv23_client_method() : q_SSLv23_server_method());
323 ctx = q_SSL_CTX_new(client ? q_TLSv1_client_method() : q_TLSv1_server_method());
326 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
327 ctx = q_SSL_CTX_new(client ? q_TLSv1_1_client_method() : q_TLSv1_1_server_method());
329 ctx = 0; // TLS 1.1 not supported by the system, but chosen deliberately -> error
333 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
334 ctx = q_SSL_CTX_new(client ? q_TLSv1_2_client_method() : q_TLSv1_2_server_method());
336 ctx = 0; // TLS 1.2 not supported by the system, but chosen deliberately -> error
341 // After stopping Flash 10 the SSL library looses its ciphers. Try re-adding them
342 // by re-initializing the library.
343 if (!reinitialized) {
344 reinitialized = true;
345 if (q_SSL_library_init() == 1)
349 q->setErrorString(QSslSocket::tr("Error creating SSL context (%1)").arg(getErrorsFromOpenSsl()));
350 q->setSocketError(QAbstractSocket::SslInternalError);
351 emit q->error(QAbstractSocket::SslInternalError);
355 // Enable bug workarounds.
356 long options = setupOpenSslOptions(configuration.protocol, configuration.sslOptions);
357 q_SSL_CTX_set_options(ctx, options);
359 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
360 // Tell OpenSSL to release memory early
361 // http://www.openssl.org/docs/ssl/SSL_CTX_set_mode.html
362 if (q_SSLeay() >= 0x10000000L)
363 q_SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
366 // Initialize ciphers
367 QByteArray cipherString;
369 QList<QSslCipher> ciphers = configuration.ciphers;
370 if (ciphers.isEmpty())
371 ciphers = defaultCiphers();
372 foreach (const QSslCipher &cipher, ciphers) {
376 cipherString.append(':');
377 cipherString.append(cipher.name().toLatin1());
380 if (!q_SSL_CTX_set_cipher_list(ctx, cipherString.data())) {
381 q->setErrorString(QSslSocket::tr("Invalid or empty cipher list (%1)").arg(getErrorsFromOpenSsl()));
382 q->setSocketError(QAbstractSocket::SslInvalidUserDataError);
383 emit q->error(QAbstractSocket::SslInvalidUserDataError);
387 // Add all our CAs to this store.
388 QList<QSslCertificate> expiredCerts;
389 foreach (const QSslCertificate &caCertificate, q->caCertificates()) {
390 // add expired certs later, so that the
391 // valid ones are used before the expired ones
392 if (caCertificate.expiryDate() < QDateTime::currentDateTime()) {
393 expiredCerts.append(caCertificate);
395 q_X509_STORE_add_cert(ctx->cert_store, reinterpret_cast<X509 *>(caCertificate.handle()));
399 bool addExpiredCerts = true;
400 #if defined(Q_OS_MAC) && (MAC_OS_X_VERSION_MAX_ALLOWED == MAC_OS_X_VERSION_10_5)
401 //On Leopard SSL does not work if we add the expired certificates.
402 if (QSysInfo::MacintoshVersion == QSysInfo::MV_10_5)
403 addExpiredCerts = false;
405 // now add the expired certs
406 if (addExpiredCerts) {
407 foreach (const QSslCertificate &caCertificate, expiredCerts) {
408 q_X509_STORE_add_cert(ctx->cert_store, reinterpret_cast<X509 *>(caCertificate.handle()));
412 if (s_loadRootCertsOnDemand && allowRootCertOnDemandLoading) {
413 // tell OpenSSL the directories where to look up the root certs on demand
414 QList<QByteArray> unixDirs = unixRootCertDirectories();
415 for (int a = 0; a < unixDirs.count(); ++a)
416 q_SSL_CTX_load_verify_locations(ctx, 0, unixDirs.at(a).constData());
419 // Register a custom callback to get all verification errors.
420 X509_STORE_set_verify_cb_func(ctx->cert_store, q_X509Callback);
422 if (!configuration.localCertificate.isNull()) {
423 // Require a private key as well.
424 if (configuration.privateKey.isNull()) {
425 q->setErrorString(QSslSocket::tr("Cannot provide a certificate with no key, %1").arg(getErrorsFromOpenSsl()));
426 q->setSocketError(QAbstractSocket::SslInvalidUserDataError);
427 emit q->error(QAbstractSocket::SslInvalidUserDataError);
432 if (!q_SSL_CTX_use_certificate(ctx, reinterpret_cast<X509 *>(configuration.localCertificate.handle()))) {
433 q->setErrorString(QSslSocket::tr("Error loading local certificate, %1").arg(getErrorsFromOpenSsl()));
434 q->setSocketError(QAbstractSocket::SslInternalError);
435 emit q->error(QAbstractSocket::SslInternalError);
439 if (configuration.privateKey.algorithm() == QSsl::Opaque) {
440 pkey = reinterpret_cast<EVP_PKEY *>(configuration.privateKey.handle());
443 pkey = q_EVP_PKEY_new();
444 // before we were using EVP_PKEY_assign_R* functions and did not use EVP_PKEY_free.
445 // this lead to a memory leak. Now we use the *_set1_* functions which do not
446 // take ownership of the RSA/DSA key instance because the QSslKey already has ownership.
447 if (configuration.privateKey.algorithm() == QSsl::Rsa)
448 q_EVP_PKEY_set1_RSA(pkey, reinterpret_cast<RSA *>(configuration.privateKey.handle()));
450 q_EVP_PKEY_set1_DSA(pkey, reinterpret_cast<DSA *>(configuration.privateKey.handle()));
453 if (!q_SSL_CTX_use_PrivateKey(ctx, pkey)) {
454 q->setErrorString(QSslSocket::tr("Error loading private key, %1").arg(getErrorsFromOpenSsl()));
455 q->setSocketError(QAbstractSocket::SslInternalError);
456 emit q->error(QAbstractSocket::SslInternalError);
459 if (configuration.privateKey.algorithm() == QSsl::Opaque)
460 pkey = 0; // Don't free the private key, it belongs to QSslKey
462 // Check if the certificate matches the private key.
463 if (!q_SSL_CTX_check_private_key(ctx)) {
464 q->setErrorString(QSslSocket::tr("Private key does not certify public key, %1").arg(getErrorsFromOpenSsl()));
465 q->setSocketError(QAbstractSocket::SslInvalidUserDataError);
466 emit q->error(QAbstractSocket::SslInvalidUserDataError);
471 // Initialize peer verification.
472 if (configuration.peerVerifyMode == QSslSocket::VerifyNone) {
473 q_SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
475 q_SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, q_X509Callback);
478 // Set verification depth.
479 if (configuration.peerVerifyDepth != 0)
480 q_SSL_CTX_set_verify_depth(ctx, configuration.peerVerifyDepth);
482 // Create and initialize SSL session
483 if (!(ssl = q_SSL_new(ctx))) {
484 // ### Bad error code
485 q->setErrorString(QSslSocket::tr("Error creating SSL session, %1").arg(getErrorsFromOpenSsl()));
486 q->setSocketError(QAbstractSocket::SslInternalError);
487 emit q->error(QAbstractSocket::SslInternalError);
491 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
492 if ((configuration.protocol == QSsl::TlsV1SslV3 ||
493 configuration.protocol == QSsl::TlsV1_0 ||
494 configuration.protocol == QSsl::TlsV1_1 ||
495 configuration.protocol == QSsl::TlsV1_2 ||
496 configuration.protocol == QSsl::SecureProtocols ||
497 configuration.protocol == QSsl::AnyProtocol) &&
498 client && q_SSLeay() >= 0x00090806fL) {
499 // Set server hostname on TLS extension. RFC4366 section 3.1 requires it in ACE format.
500 QString tlsHostName = verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName;
501 if (tlsHostName.isEmpty())
502 tlsHostName = hostName;
503 QByteArray ace = QUrl::toAce(tlsHostName);
504 // only send the SNI header if the URL is valid and not an IP
506 && !QHostAddress().setAddress(tlsHostName)
507 && !(configuration.sslOptions & QSsl::SslOptionDisableServerNameIndication)) {
508 if (!q_SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, ace.data()))
509 qWarning("could not set SSL_CTRL_SET_TLSEXT_HOSTNAME, Server Name Indication disabled");
514 // Clear the session.
518 // Initialize memory BIOs for encryption and decryption.
519 readBio = q_BIO_new(q_BIO_s_mem());
520 writeBio = q_BIO_new(q_BIO_s_mem());
521 if (!readBio || !writeBio) {
522 q->setErrorString(QSslSocket::tr("Error creating SSL session: %1").arg(getErrorsFromOpenSsl()));
523 q->setSocketError(QAbstractSocket::SslInternalError);
524 emit q->error(QAbstractSocket::SslInternalError);
529 q_SSL_set_bio(ssl, readBio, writeBio);
531 if (mode == QSslSocket::SslClientMode)
532 q_SSL_set_connect_state(ssl);
534 q_SSL_set_accept_state(ssl);
539 void QSslSocketBackendPrivate::destroySslContext()
550 q_EVP_PKEY_free(pkey);
558 void QSslSocketPrivate::deinitialize()
560 q_CRYPTO_set_id_callback(0);
561 q_CRYPTO_set_locking_callback(0);
562 q_ERR_free_strings();
568 Does the minimum amount of initialization to determine whether SSL
572 bool QSslSocketPrivate::supportsSsl()
574 return ensureLibraryLoaded();
577 bool QSslSocketPrivate::ensureLibraryLoaded()
579 if (!q_resolveOpenSslSymbols())
582 // Check if the library itself needs to be initialized.
583 QMutexLocker locker(openssl_locks()->initLock());
585 if (!s_libraryLoaded) {
586 s_libraryLoaded = true;
588 // Initialize OpenSSL.
589 q_CRYPTO_set_id_callback(id_function);
590 q_CRYPTO_set_locking_callback(locking_function);
591 if (q_SSL_library_init() != 1)
593 q_SSL_load_error_strings();
594 q_OpenSSL_add_all_algorithms();
596 // Initialize OpenSSL's random seed.
597 if (!q_RAND_status()) {
606 if (attempts < 500) {
608 struct timespec ts = {0, 33333333};
613 randomish.msec = attempts;
615 randomish.stack = (void *)&randomish;
616 randomish.msec = QTime::currentTime().msec();
617 randomish.sec = QTime::currentTime().second();
618 q_RAND_seed((const char *)&randomish, sizeof(randomish));
619 } while (!q_RAND_status() && --attempts);
627 void QSslSocketPrivate::ensureCiphersAndCertsLoaded()
629 QMutexLocker locker(openssl_locks()->initLock());
630 if (s_loadedCiphersAndCerts)
632 s_loadedCiphersAndCerts = true;
634 resetDefaultCiphers();
636 #ifndef QT_NO_LIBRARY
637 //load symbols needed to receive certificates from system store
638 #if defined(Q_OS_MAC) && !defined(Q_OS_IOS)
639 QLibrary securityLib("/System/Library/Frameworks/Security.framework/Versions/Current/Security");
640 if (securityLib.load()) {
641 ptrSecCertificateGetData = (PtrSecCertificateGetData) securityLib.resolve("SecCertificateGetData");
642 if (!ptrSecCertificateGetData)
643 qWarning("could not resolve symbols in security library"); // should never happen
645 ptrSecTrustSettingsCopyCertificates = (PtrSecTrustSettingsCopyCertificates) securityLib.resolve("SecTrustSettingsCopyCertificates");
646 if (!ptrSecTrustSettingsCopyCertificates) { // method was introduced in Leopard, use legacy method if it's not there
647 ptrSecTrustCopyAnchorCertificates = (PtrSecTrustCopyAnchorCertificates) securityLib.resolve("SecTrustCopyAnchorCertificates");
648 if (!ptrSecTrustCopyAnchorCertificates)
649 qWarning("could not resolve symbols in security library"); // should never happen
652 qWarning("could not load security library");
654 #elif defined(Q_OS_WIN)
655 HINSTANCE hLib = LoadLibraryW(L"Crypt32");
657 #if defined(Q_OS_WINCE)
658 ptrCertOpenSystemStoreW = (PtrCertOpenSystemStoreW)GetProcAddress(hLib, L"CertOpenStore");
659 ptrCertFindCertificateInStore = (PtrCertFindCertificateInStore)GetProcAddress(hLib, L"CertFindCertificateInStore");
660 ptrCertCloseStore = (PtrCertCloseStore)GetProcAddress(hLib, L"CertCloseStore");
662 ptrCertOpenSystemStoreW = (PtrCertOpenSystemStoreW)GetProcAddress(hLib, "CertOpenSystemStoreW");
663 ptrCertFindCertificateInStore = (PtrCertFindCertificateInStore)GetProcAddress(hLib, "CertFindCertificateInStore");
664 ptrCertCloseStore = (PtrCertCloseStore)GetProcAddress(hLib, "CertCloseStore");
666 if (!ptrCertOpenSystemStoreW || !ptrCertFindCertificateInStore || !ptrCertCloseStore)
667 qWarning("could not resolve symbols in crypt32 library"); // should never happen
669 qWarning("could not load crypt32 library"); // should never happen
671 #elif defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
672 // check whether we can enable on-demand root-cert loading (i.e. check whether the sym links are there)
673 QList<QByteArray> dirs = unixRootCertDirectories();
674 QStringList symLinkFilter;
675 symLinkFilter << QLatin1String("[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f].[0-9]");
676 for (int a = 0; a < dirs.count(); ++a) {
677 QDirIterator iterator(QLatin1String(dirs.at(a)), symLinkFilter, QDir::Files);
678 if (iterator.hasNext()) {
679 s_loadRootCertsOnDemand = true;
684 #endif //QT_NO_LIBRARY
685 // if on-demand loading was not enabled, load the certs now
686 if (!s_loadRootCertsOnDemand)
687 setDefaultCaCertificates(systemCaCertificates());
689 //Enabled for fetching additional root certs from windows update on windows 6+
690 //This flag is set false by setDefaultCaCertificates() indicating the app uses
691 //its own cert bundle rather than the system one.
692 //Same logic that disables the unix on demand cert loading.
693 //Unlike unix, we do preload the certificates from the cert store.
694 if ((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_6_0)
695 s_loadRootCertsOnDemand = true;
702 Declared static in QSslSocketPrivate, makes sure the SSL libraries have
706 void QSslSocketPrivate::ensureInitialized()
711 ensureCiphersAndCertsLoaded();
714 long QSslSocketPrivate::sslLibraryVersionNumber()
719 QString QSslSocketPrivate::sslLibraryVersionString()
724 const char *versionString = q_SSLeay_version(SSLEAY_VERSION);
728 return QString::fromLatin1(versionString);
734 Declared static in QSslSocketPrivate, backend-dependent loading of
735 application-wide global ciphers.
737 void QSslSocketPrivate::resetDefaultCiphers()
739 SSL_CTX *myCtx = q_SSL_CTX_new(q_SSLv23_client_method());
740 SSL *mySsl = q_SSL_new(myCtx);
742 QList<QSslCipher> ciphers;
744 STACK_OF(SSL_CIPHER) *supportedCiphers = q_SSL_get_ciphers(mySsl);
745 for (int i = 0; i < q_sk_SSL_CIPHER_num(supportedCiphers); ++i) {
746 if (SSL_CIPHER *cipher = q_sk_SSL_CIPHER_value(supportedCiphers, i)) {
748 QSslCipher ciph = QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(cipher);
749 if (!ciph.isNull()) {
750 if (!ciph.name().toLower().startsWith(QLatin1String("adh")))
757 q_SSL_CTX_free(myCtx);
760 setDefaultSupportedCiphers(ciphers);
761 setDefaultCiphers(ciphers);
764 QList<QSslCertificate> QSslSocketPrivate::systemCaCertificates()
767 #ifdef QSSLSOCKET_DEBUG
771 QList<QSslCertificate> systemCerts;
772 #if defined(Q_OS_MAC) && !defined(Q_OS_IOS)
776 OSStatus SecCertificateGetData (
777 SecCertificateRef certificate,
781 if (ptrSecCertificateGetData) {
782 if (ptrSecTrustSettingsCopyCertificates)
783 status = ptrSecTrustSettingsCopyCertificates(kSecTrustSettingsDomainSystem, &cfCerts);
784 else if (ptrSecTrustCopyAnchorCertificates)
785 status = ptrSecTrustCopyAnchorCertificates(&cfCerts);
787 CFIndex size = CFArrayGetCount(cfCerts);
788 for (CFIndex i = 0; i < size; ++i) {
789 SecCertificateRef cfCert = (SecCertificateRef)CFArrayGetValueAtIndex(cfCerts, i);
791 CSSM_DATA_PTR dataPtr = &data;
792 if (ptrSecCertificateGetData(cfCert, dataPtr)) {
793 qWarning("error retrieving a CA certificate from the system store");
795 int len = data.Length;
796 char *rawData = reinterpret_cast<char *>(data.Data);
797 QByteArray rawCert(rawData, len);
798 systemCerts.append(QSslCertificate::fromData(rawCert, QSsl::Der));
804 // no detailed error handling here
805 qWarning("could not retrieve system CA certificates");
808 #elif defined(Q_OS_WIN)
809 if (ptrCertOpenSystemStoreW && ptrCertFindCertificateInStore && ptrCertCloseStore) {
810 HCERTSTORE hSystemStore;
811 #if defined(Q_OS_WINCE)
812 hSystemStore = ptrCertOpenSystemStoreW(CERT_STORE_PROV_SYSTEM_W,
815 CERT_STORE_NO_CRYPT_RELEASE_FLAG|CERT_SYSTEM_STORE_CURRENT_USER,
818 hSystemStore = ptrCertOpenSystemStoreW(0, L"ROOT");
821 PCCERT_CONTEXT pc = NULL;
823 pc = ptrCertFindCertificateInStore( hSystemStore, X509_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, pc);
826 QByteArray der((const char *)(pc->pbCertEncoded), static_cast<int>(pc->cbCertEncoded));
827 QSslCertificate cert(der, QSsl::Der);
828 systemCerts.append(cert);
830 ptrCertCloseStore(hSystemStore, 0);
833 #elif defined(Q_OS_UNIX)
834 QSet<QString> certFiles;
835 QList<QByteArray> directories = unixRootCertDirectories();
837 QStringList nameFilters;
838 nameFilters << QLatin1String("*.pem") << QLatin1String("*.crt");
839 currentDir.setNameFilters(nameFilters);
840 for (int a = 0; a < directories.count(); a++) {
841 currentDir.setPath(QLatin1String(directories.at(a)));
842 QDirIterator it(currentDir);
843 while(it.hasNext()) {
845 // use canonical path here to not load the same certificate twice if symlinked
846 certFiles.insert(it.fileInfo().canonicalFilePath());
849 QSetIterator<QString> it(certFiles);
850 while(it.hasNext()) {
851 systemCerts.append(QSslCertificate::fromPath(it.next()));
853 systemCerts.append(QSslCertificate::fromPath(QLatin1String("/etc/pki/tls/certs/ca-bundle.crt"), QSsl::Pem)); // Fedora, Mandriva
854 systemCerts.append(QSslCertificate::fromPath(QLatin1String("/usr/local/share/certs/ca-root-nss.crt"), QSsl::Pem)); // FreeBSD's ca_root_nss
856 #ifdef QSSLSOCKET_DEBUG
857 qDebug() << "systemCaCertificates retrieval time " << timer.elapsed() << "ms";
858 qDebug() << "imported " << systemCerts.count() << " certificates";
864 void QSslSocketBackendPrivate::startClientEncryption()
867 if (!initSslContext()) {
868 q->setErrorString(QSslSocket::tr("Unable to init SSL Context: %1").arg(getErrorsFromOpenSsl()));
869 q->setSocketError(QAbstractSocket::SslInternalError);
870 emit q->error(QAbstractSocket::SslInternalError);
874 // Start connecting. This will place outgoing data in the BIO, so we
875 // follow up with calling transmit().
880 void QSslSocketBackendPrivate::startServerEncryption()
883 if (!initSslContext()) {
884 q->setErrorString(QSslSocket::tr("Unable to init SSL Context: %1").arg(getErrorsFromOpenSsl()));
885 q->setSocketError(QAbstractSocket::SslInternalError);
886 emit q->error(QAbstractSocket::SslInternalError);
890 // Start connecting. This will place outgoing data in the BIO, so we
891 // follow up with calling transmit().
899 Transmits encrypted data between the BIOs and the socket.
901 void QSslSocketBackendPrivate::transmit()
905 // If we don't have any SSL context, don't bother transmitting.
911 transmitting = false;
913 // If the connection is secure, we can transfer data from the write
914 // buffer (in plain text) to the write BIO through SSL_write.
915 if (connectionEncrypted && !writeBuffer.isEmpty()) {
916 qint64 totalBytesWritten = 0;
917 int nextDataBlockSize;
918 while ((nextDataBlockSize = writeBuffer.nextDataBlockSize()) > 0) {
919 int writtenBytes = q_SSL_write(ssl, writeBuffer.readPointer(), nextDataBlockSize);
920 if (writtenBytes <= 0) {
921 // ### Better error handling.
922 q->setErrorString(QSslSocket::tr("Unable to write data: %1").arg(getErrorsFromOpenSsl()));
923 q->setSocketError(QAbstractSocket::SslInternalError);
924 emit q->error(QAbstractSocket::SslInternalError);
927 #ifdef QSSLSOCKET_DEBUG
928 qDebug() << "QSslSocketBackendPrivate::transmit: encrypted" << writtenBytes << "bytes";
930 writeBuffer.free(writtenBytes);
931 totalBytesWritten += writtenBytes;
933 if (writtenBytes < nextDataBlockSize) {
934 // break out of the writing loop and try again after we had read
940 if (totalBytesWritten > 0) {
941 // Don't emit bytesWritten() recursively.
942 if (!emittedBytesWritten) {
943 emittedBytesWritten = true;
944 emit q->bytesWritten(totalBytesWritten);
945 emittedBytesWritten = false;
950 // Check if we've got any data to be written to the socket.
951 QVarLengthArray<char, 4096> data;
953 while (plainSocket->isValid() && (pendingBytes = q_BIO_pending(writeBio)) > 0) {
954 // Read encrypted data from the write BIO into a buffer.
955 data.resize(pendingBytes);
956 int encryptedBytesRead = q_BIO_read(writeBio, data.data(), pendingBytes);
958 // Write encrypted data from the buffer to the socket.
959 qint64 actualWritten = plainSocket->write(data.constData(), encryptedBytesRead);
960 #ifdef QSSLSOCKET_DEBUG
961 qDebug() << "QSslSocketBackendPrivate::transmit: wrote" << encryptedBytesRead << "encrypted bytes to the socket" << actualWritten << "actual.";
963 if (actualWritten < 0) {
964 //plain socket write fails if it was in the pending close state.
965 q->setErrorString(plainSocket->errorString());
966 q->setSocketError(plainSocket->error());
967 emit q->error(plainSocket->error());
973 // Check if we've got any data to be read from the socket.
974 if (!connectionEncrypted || !readBufferMaxSize || buffer.size() < readBufferMaxSize)
975 while ((pendingBytes = plainSocket->bytesAvailable()) > 0) {
976 // Read encrypted data from the socket into a buffer.
977 data.resize(pendingBytes);
978 // just peek() here because q_BIO_write could write less data than expected
979 int encryptedBytesRead = plainSocket->peek(data.data(), pendingBytes);
981 #ifdef QSSLSOCKET_DEBUG
982 qDebug() << "QSslSocketBackendPrivate::transmit: read" << encryptedBytesRead << "encrypted bytes from the socket";
984 // Write encrypted data from the buffer into the read BIO.
985 int writtenToBio = q_BIO_write(readBio, data.constData(), encryptedBytesRead);
987 // do the actual read() here and throw away the results.
988 if (writtenToBio > 0) {
989 // ### TODO: make this cheaper by not making it memcpy. E.g. make it work with data=0x0 or make it work with seek
990 plainSocket->read(data.data(), writtenToBio);
992 // ### Better error handling.
993 q->setErrorString(QSslSocket::tr("Unable to decrypt data: %1").arg(getErrorsFromOpenSsl()));
994 q->setSocketError(QAbstractSocket::SslInternalError);
995 emit q->error(QAbstractSocket::SslInternalError);
1002 // If the connection isn't secured yet, this is the time to retry the
1003 // connect / accept.
1004 if (!connectionEncrypted) {
1005 #ifdef QSSLSOCKET_DEBUG
1006 qDebug() << "QSslSocketBackendPrivate::transmit: testing encryption";
1008 if (startHandshake()) {
1009 #ifdef QSSLSOCKET_DEBUG
1010 qDebug() << "QSslSocketBackendPrivate::transmit: encryption established";
1012 connectionEncrypted = true;
1013 transmitting = true;
1014 } else if (plainSocket->state() != QAbstractSocket::ConnectedState) {
1015 #ifdef QSSLSOCKET_DEBUG
1016 qDebug() << "QSslSocketBackendPrivate::transmit: connection lost";
1019 } else if (paused) {
1020 // just wait until the user continues
1023 #ifdef QSSLSOCKET_DEBUG
1024 qDebug() << "QSslSocketBackendPrivate::transmit: encryption not done yet";
1029 // If the request is small and the remote host closes the transmission
1030 // after sending, there's a chance that startHandshake() will already
1031 // have triggered a shutdown.
1035 // We always read everything from the SSL decryption buffers, even if
1036 // we have a readBufferMaxSize. There's no point in leaving data there
1037 // just so that readBuffer.size() == readBufferMaxSize.
1040 ::memset(data.data(), 0, data.size());
1042 // Don't use SSL_pending(). It's very unreliable.
1043 if ((readBytes = q_SSL_read(ssl, data.data(), data.size())) > 0) {
1044 #ifdef QSSLSOCKET_DEBUG
1045 qDebug() << "QSslSocketBackendPrivate::transmit: decrypted" << readBytes << "bytes";
1047 char *ptr = buffer.reserve(readBytes);
1048 ::memcpy(ptr, data.data(), readBytes);
1050 if (readyReadEmittedPointer)
1051 *readyReadEmittedPointer = true;
1052 emit q->readyRead();
1053 transmitting = true;
1058 switch (q_SSL_get_error(ssl, readBytes)) {
1059 case SSL_ERROR_WANT_READ:
1060 case SSL_ERROR_WANT_WRITE:
1063 case SSL_ERROR_ZERO_RETURN:
1064 // The remote host closed the connection.
1065 #ifdef QSSLSOCKET_DEBUG
1066 qDebug() << "QSslSocketBackendPrivate::transmit: remote disconnect";
1068 plainSocket->disconnectFromHost();
1070 case SSL_ERROR_SYSCALL: // some IO error
1071 case SSL_ERROR_SSL: // error in the SSL library
1072 // we do not know exactly what the error is, nor whether we can recover from it,
1073 // so just return to prevent an endless loop in the outer "while" statement
1074 q->setErrorString(QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
1075 q->setSocketError(QAbstractSocket::SslInternalError);
1076 emit q->error(QAbstractSocket::SslInternalError);
1079 // SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT: can only happen with a
1080 // BIO_s_connect() or BIO_s_accept(), which we do not call.
1081 // SSL_ERROR_WANT_X509_LOOKUP: can only happen with a
1082 // SSL_CTX_set_client_cert_cb(), which we do not call.
1083 // So this default case should never be triggered.
1084 q->setErrorString(QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
1085 q->setSocketError(QAbstractSocket::SslInternalError);
1086 emit q->error(QAbstractSocket::SslInternalError);
1089 } while (ssl && readBytes > 0);
1090 } while (ssl && ctx && transmitting);
1093 static QSslError _q_OpenSSL_to_QSslError(int errorCode, const QSslCertificate &cert)
1096 switch (errorCode) {
1098 // X509_V_OK is also reported if the peer had no certificate.
1100 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1101 error = QSslError(QSslError::UnableToGetIssuerCertificate, cert); break;
1102 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1103 error = QSslError(QSslError::UnableToDecryptCertificateSignature, cert); break;
1104 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1105 error = QSslError(QSslError::UnableToDecodeIssuerPublicKey, cert); break;
1106 case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1107 error = QSslError(QSslError::CertificateSignatureFailed, cert); break;
1108 case X509_V_ERR_CERT_NOT_YET_VALID:
1109 error = QSslError(QSslError::CertificateNotYetValid, cert); break;
1110 case X509_V_ERR_CERT_HAS_EXPIRED:
1111 error = QSslError(QSslError::CertificateExpired, cert); break;
1112 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1113 error = QSslError(QSslError::InvalidNotBeforeField, cert); break;
1114 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1115 error = QSslError(QSslError::InvalidNotAfterField, cert); break;
1116 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1117 error = QSslError(QSslError::SelfSignedCertificate, cert); break;
1118 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1119 error = QSslError(QSslError::SelfSignedCertificateInChain, cert); break;
1120 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1121 error = QSslError(QSslError::UnableToGetLocalIssuerCertificate, cert); break;
1122 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1123 error = QSslError(QSslError::UnableToVerifyFirstCertificate, cert); break;
1124 case X509_V_ERR_CERT_REVOKED:
1125 error = QSslError(QSslError::CertificateRevoked, cert); break;
1126 case X509_V_ERR_INVALID_CA:
1127 error = QSslError(QSslError::InvalidCaCertificate, cert); break;
1128 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1129 error = QSslError(QSslError::PathLengthExceeded, cert); break;
1130 case X509_V_ERR_INVALID_PURPOSE:
1131 error = QSslError(QSslError::InvalidPurpose, cert); break;
1132 case X509_V_ERR_CERT_UNTRUSTED:
1133 error = QSslError(QSslError::CertificateUntrusted, cert); break;
1134 case X509_V_ERR_CERT_REJECTED:
1135 error = QSslError(QSslError::CertificateRejected, cert); break;
1137 error = QSslError(QSslError::UnspecifiedError, cert); break;
1142 bool QSslSocketBackendPrivate::startHandshake()
1146 // Check if the connection has been established. Get all errors from the
1147 // verification stage.
1148 _q_sslErrorList()->mutex.lock();
1149 _q_sslErrorList()->errors.clear();
1150 int result = (mode == QSslSocket::SslClientMode) ? q_SSL_connect(ssl) : q_SSL_accept(ssl);
1152 const QList<QPair<int, int> > &lastErrors = _q_sslErrorList()->errors;
1153 for (int i = 0; i < lastErrors.size(); ++i) {
1154 const QPair<int, int> ¤tError = lastErrors.at(i);
1155 // Initialize the peer certificate chain in order to find which certificate caused this error
1156 if (configuration.peerCertificateChain.isEmpty())
1157 configuration.peerCertificateChain = STACKOFX509_to_QSslCertificates(q_SSL_get_peer_cert_chain(ssl));
1158 emit q->peerVerifyError(_q_OpenSSL_to_QSslError(currentError.first,
1159 configuration.peerCertificateChain.value(currentError.second)));
1160 if (q->state() != QAbstractSocket::ConnectedState)
1164 errorList << lastErrors;
1165 _q_sslErrorList()->mutex.unlock();
1167 // Connection aborted during handshake phase.
1168 if (q->state() != QAbstractSocket::ConnectedState)
1171 // Check if we're encrypted or not.
1173 switch (q_SSL_get_error(ssl, result)) {
1174 case SSL_ERROR_WANT_READ:
1175 case SSL_ERROR_WANT_WRITE:
1176 // The handshake is not yet complete.
1179 q->setErrorString(QSslSocket::tr("Error during SSL handshake: %1").arg(getErrorsFromOpenSsl()));
1180 q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
1181 #ifdef QSSLSOCKET_DEBUG
1182 qDebug() << "QSslSocketBackendPrivate::startHandshake: error!" << q->errorString();
1184 emit q->error(QAbstractSocket::SslHandshakeFailedError);
1190 // Store the peer certificate and chain. For clients, the peer certificate
1191 // chain includes the peer certificate; for servers, it doesn't. Both the
1192 // peer certificate and the chain may be empty if the peer didn't present
1194 if (configuration.peerCertificateChain.isEmpty())
1195 configuration.peerCertificateChain = STACKOFX509_to_QSslCertificates(q_SSL_get_peer_cert_chain(ssl));
1196 X509 *x509 = q_SSL_get_peer_certificate(ssl);
1197 configuration.peerCertificate = QSslCertificatePrivate::QSslCertificate_from_X509(x509);
1200 // Start translating errors.
1201 QList<QSslError> errors;
1203 // check the whole chain for blacklisting (including root, as we check for subjectInfo and issuer)
1204 foreach (const QSslCertificate &cert, configuration.peerCertificateChain) {
1205 if (QSslCertificatePrivate::isBlacklisted(cert)) {
1206 QSslError error(QSslError::CertificateBlacklisted, cert);
1208 emit q->peerVerifyError(error);
1209 if (q->state() != QAbstractSocket::ConnectedState)
1214 bool doVerifyPeer = configuration.peerVerifyMode == QSslSocket::VerifyPeer
1215 || (configuration.peerVerifyMode == QSslSocket::AutoVerifyPeer
1216 && mode == QSslSocket::SslClientMode);
1218 // Check the peer certificate itself. First try the subject's common name
1219 // (CN) as a wildcard, then try all alternate subject name DNS entries the
1221 if (!configuration.peerCertificate.isNull()) {
1222 // but only if we're a client connecting to a server
1223 // if we're the server, don't check CN
1224 if (mode == QSslSocket::SslClientMode) {
1225 QString peerName = (verificationPeerName.isEmpty () ? q->peerName() : verificationPeerName);
1227 if (!isMatchingHostname(configuration.peerCertificate, peerName)) {
1228 // No matches in common names or alternate names.
1229 QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate);
1231 emit q->peerVerifyError(error);
1232 if (q->state() != QAbstractSocket::ConnectedState)
1237 // No peer certificate presented. Report as error if the socket
1240 QSslError error(QSslError::NoPeerCertificate);
1242 emit q->peerVerifyError(error);
1243 if (q->state() != QAbstractSocket::ConnectedState)
1248 // Translate errors from the error list into QSslErrors.
1249 for (int i = 0; i < errorList.size(); ++i) {
1250 const QPair<int, int> &errorAndDepth = errorList.at(i);
1251 int err = errorAndDepth.first;
1252 int depth = errorAndDepth.second;
1253 errors << _q_OpenSSL_to_QSslError(err, configuration.peerCertificateChain.value(depth));
1256 if (!errors.isEmpty()) {
1260 //Skip this if not using system CAs, or if the SSL errors are configured in advance to be ignorable
1262 && s_loadRootCertsOnDemand
1263 && allowRootCertOnDemandLoading
1264 && !verifyErrorsHaveBeenIgnored()) {
1265 //Windows desktop versions starting from vista ship with minimal set of roots
1266 //and download on demand from the windows update server CA roots that are
1268 //However, this is only transparent if using WinINET - we have to trigger it
1270 QSslCertificate certToFetch;
1271 bool fetchCertificate = true;
1272 for (int i=0; i< sslErrors.count(); i++) {
1273 switch (sslErrors.at(i).error()) {
1274 case QSslError::UnableToGetLocalIssuerCertificate: // site presented intermediate cert, but root is unknown
1275 case QSslError::SelfSignedCertificateInChain: // site presented a complete chain, but root is unknown
1276 certToFetch = sslErrors.at(i).certificate();
1278 case QSslError::SelfSignedCertificate:
1279 case QSslError::CertificateBlacklisted:
1280 //With these errors, we know it will be untrusted so save time by not asking windows
1281 fetchCertificate = false;
1284 #ifdef QSSLSOCKET_DEBUG
1285 qDebug() << sslErrors.at(i).errorString();
1290 if (fetchCertificate && !certToFetch.isNull()) {
1291 fetchCaRootForCert(certToFetch);
1297 if (!checkSslErrors())
1303 continueHandshake();
1307 bool QSslSocketBackendPrivate::checkSslErrors()
1310 if (sslErrors.isEmpty())
1313 emit q->sslErrors(sslErrors);
1315 bool doVerifyPeer = configuration.peerVerifyMode == QSslSocket::VerifyPeer
1316 || (configuration.peerVerifyMode == QSslSocket::AutoVerifyPeer
1317 && mode == QSslSocket::SslClientMode);
1318 bool doEmitSslError = !verifyErrorsHaveBeenIgnored();
1319 // check whether we need to emit an SSL handshake error
1320 if (doVerifyPeer && doEmitSslError) {
1321 if (q->pauseMode() & QAbstractSocket::PauseOnSslErrors) {
1322 pauseSocketNotifiers(q);
1325 q->setErrorString(sslErrors.first().errorString());
1326 q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
1327 emit q->error(QAbstractSocket::SslHandshakeFailedError);
1328 plainSocket->disconnectFromHost();
1337 void QSslSocketBackendPrivate::fetchCaRootForCert(const QSslCertificate &cert)
1340 //The root certificate is downloaded from windows update, which blocks for 15 seconds in the worst case
1341 //so the request is done in a worker thread.
1342 QWindowsCaRootFetcher *fetcher = new QWindowsCaRootFetcher(cert, mode);
1343 QObject::connect(fetcher, SIGNAL(finished(QSslCertificate,QSslCertificate)), q, SLOT(_q_caRootLoaded(QSslCertificate,QSslCertificate)), Qt::QueuedConnection);
1344 QMetaObject::invokeMethod(fetcher, "start", Qt::QueuedConnection);
1345 pauseSocketNotifiers(q);
1349 //This is the callback from QWindowsCaRootFetcher, trustedRoot will be invalid (default constructed) if it failed.
1350 void QSslSocketBackendPrivate::_q_caRootLoaded(QSslCertificate cert, QSslCertificate trustedRoot)
1353 if (!trustedRoot.isNull() && !trustedRoot.isBlacklisted()) {
1354 if (s_loadRootCertsOnDemand) {
1355 //Add the new root cert to default cert list for use by future sockets
1356 QSslSocket::addDefaultCaCertificate(trustedRoot);
1358 //Add the new root cert to this socket for future connections
1359 q->addCaCertificate(trustedRoot);
1360 //Remove the broken chain ssl errors (as chain is verified by windows)
1361 for (int i=sslErrors.count() - 1; i >= 0; --i) {
1362 if (sslErrors.at(i).certificate() == cert) {
1363 switch (sslErrors.at(i).error()) {
1364 case QSslError::UnableToGetLocalIssuerCertificate:
1365 case QSslError::CertificateUntrusted:
1366 case QSslError::UnableToVerifyFirstCertificate:
1367 case QSslError::SelfSignedCertificateInChain:
1368 // error can be ignored if OS says the chain is trusted
1369 sslErrors.removeAt(i);
1372 // error cannot be ignored
1378 // Continue with remaining errors
1380 plainSocket->resume();
1382 if (checkSslErrors())
1383 continueHandshake();
1386 class QWindowsCaRootFetcherThread : public QThread
1389 QWindowsCaRootFetcherThread()
1391 qRegisterMetaType<QSslCertificate>();
1392 setObjectName(QStringLiteral("QWindowsCaRootFetcher"));
1395 ~QWindowsCaRootFetcherThread()
1398 wait(15500); // worst case, a running request can block for 15 seconds
1402 Q_GLOBAL_STATIC(QWindowsCaRootFetcherThread, windowsCaRootFetcherThread);
1404 QWindowsCaRootFetcher::QWindowsCaRootFetcher(const QSslCertificate &certificate, QSslSocket::SslMode sslMode)
1405 : cert(certificate), mode(sslMode)
1407 moveToThread(windowsCaRootFetcherThread());
1410 QWindowsCaRootFetcher::~QWindowsCaRootFetcher()
1414 void QWindowsCaRootFetcher::start()
1416 QByteArray der = cert.toDer();
1417 PCCERT_CONTEXT wincert = CertCreateCertificateContext(X509_ASN_ENCODING, (const BYTE *)der.constData(), der.length());
1419 #ifdef QSSLSOCKET_DEBUG
1420 qDebug("QWindowsCaRootFetcher failed to convert certificate to windows form");
1422 emit finished(cert, QSslCertificate());
1427 CERT_CHAIN_PARA parameters;
1428 memset(¶meters, 0, sizeof(parameters));
1429 parameters.cbSize = sizeof(parameters);
1430 // set key usage constraint
1431 parameters.RequestedUsage.dwType = USAGE_MATCH_TYPE_AND;
1432 parameters.RequestedUsage.Usage.cUsageIdentifier = 1;
1433 LPSTR oid = (LPSTR)(mode == QSslSocket::SslClientMode ? szOID_PKIX_KP_SERVER_AUTH : szOID_PKIX_KP_CLIENT_AUTH);
1434 parameters.RequestedUsage.Usage.rgpszUsageIdentifier = &oid;
1436 #ifdef QSSLSOCKET_DEBUG
1437 QElapsedTimer stopwatch;
1440 PCCERT_CHAIN_CONTEXT chain;
1441 BOOL result = CertGetCertificateChain(
1444 0, //current date/time
1447 0, //default dwFlags
1450 #ifdef QSSLSOCKET_DEBUG
1451 qDebug() << "QWindowsCaRootFetcher" << stopwatch.elapsed() << "ms to get chain";
1454 QSslCertificate trustedRoot;
1456 #ifdef QSSLSOCKET_DEBUG
1457 qDebug() << "QWindowsCaRootFetcher - examining windows chains";
1458 if (chain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR)
1459 qDebug() << " - TRUSTED";
1461 qDebug() << " - NOT TRUSTED" << chain->TrustStatus.dwErrorStatus;
1462 if (chain->TrustStatus.dwInfoStatus & CERT_TRUST_IS_SELF_SIGNED)
1463 qDebug() << " - SELF SIGNED";
1464 qDebug() << "QSslSocketBackendPrivate::fetchCaRootForCert - dumping simple chains";
1465 for (unsigned int i = 0; i < chain->cChain; i++) {
1466 if (chain->rgpChain[i]->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR)
1467 qDebug() << " - TRUSTED SIMPLE CHAIN" << i;
1469 qDebug() << " - UNTRUSTED SIMPLE CHAIN" << i << "reason:" << chain->rgpChain[i]->TrustStatus.dwErrorStatus;
1470 for (unsigned int j = 0; j < chain->rgpChain[i]->cElement; j++) {
1471 QSslCertificate foundCert(QByteArray((const char *)chain->rgpChain[i]->rgpElement[j]->pCertContext->pbCertEncoded
1472 , chain->rgpChain[i]->rgpElement[j]->pCertContext->cbCertEncoded), QSsl::Der);
1473 qDebug() << " - " << foundCert;
1476 qDebug() << " - and" << chain->cLowerQualityChainContext << "low quality chains"; //expect 0, we haven't asked for them
1479 //based on http://msdn.microsoft.com/en-us/library/windows/desktop/aa377182%28v=vs.85%29.aspx
1480 //about the final chain rgpChain[cChain-1] which must begin with a trusted root to be valid
1481 if (chain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR
1482 && chain->cChain > 0) {
1483 const PCERT_SIMPLE_CHAIN finalChain = chain->rgpChain[chain->cChain - 1];
1484 // http://msdn.microsoft.com/en-us/library/windows/desktop/aa377544%28v=vs.85%29.aspx
1485 // rgpElement[0] is the end certificate chain element. rgpElement[cElement-1] is the self-signed "root" certificate element.
1486 if (finalChain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR
1487 && finalChain->cElement > 0) {
1488 trustedRoot = QSslCertificate(QByteArray((const char *)finalChain->rgpElement[finalChain->cElement - 1]->pCertContext->pbCertEncoded
1489 , finalChain->rgpElement[finalChain->cElement - 1]->pCertContext->cbCertEncoded), QSsl::Der);
1492 CertFreeCertificateChain(chain);
1494 CertFreeCertificateContext(wincert);
1496 emit finished(cert, trustedRoot);
1501 void QSslSocketBackendPrivate::disconnectFromHost()
1504 q_SSL_shutdown(ssl);
1507 plainSocket->disconnectFromHost();
1510 void QSslSocketBackendPrivate::disconnected()
1512 if (plainSocket->bytesAvailable() <= 0)
1513 destroySslContext();
1514 //if there is still buffered data in the plain socket, don't destroy the ssl context yet.
1515 //it will be destroyed when the socket is deleted.
1518 QSslCipher QSslSocketBackendPrivate::sessionCipher() const
1521 return QSslCipher();
1522 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
1523 // FIXME This is fairly evil, but needed to keep source level compatibility
1524 // with the OpenSSL 0.9.x implementation at maximum -- some other functions
1525 // don't take a const SSL_CIPHER* when they should
1526 SSL_CIPHER *sessionCipher = const_cast<SSL_CIPHER *>(q_SSL_get_current_cipher(ssl));
1528 SSL_CIPHER *sessionCipher = q_SSL_get_current_cipher(ssl);
1530 return sessionCipher ? QSslCipher_from_SSL_CIPHER(sessionCipher) : QSslCipher();
1533 void QSslSocketBackendPrivate::continueHandshake()
1536 // if we have a max read buffer size, reset the plain socket's to match
1537 if (readBufferMaxSize)
1538 plainSocket->setReadBufferSize(readBufferMaxSize);
1540 connectionEncrypted = true;
1541 emit q->encrypted();
1542 if (autoStartHandshake && pendingClose) {
1543 pendingClose = false;
1544 q->disconnectFromHost();
1548 QList<QSslCertificate> QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates(STACK_OF(X509) *x509)
1550 ensureInitialized();
1551 QList<QSslCertificate> certificates;
1552 for (int i = 0; i < q_sk_X509_num(x509); ++i) {
1553 if (X509 *entry = q_sk_X509_value(x509, i))
1554 certificates << QSslCertificatePrivate::QSslCertificate_from_X509(entry);
1556 return certificates;
1559 QString QSslSocketBackendPrivate::getErrorsFromOpenSsl()
1561 QString errorString;
1562 unsigned long errNum;
1563 while((errNum = q_ERR_get_error())) {
1564 if (! errorString.isEmpty())
1565 errorString.append(QLatin1String(", "));
1566 const char *error = q_ERR_error_string(errNum, NULL);
1567 errorString.append(QString::fromLatin1(error)); // error is ascii according to man ERR_error_string
1572 bool QSslSocketBackendPrivate::isMatchingHostname(const QSslCertificate &cert, const QString &peerName)
1574 QStringList commonNameList = cert.subjectInfo(QSslCertificate::CommonName);
1576 foreach (const QString &commonName, commonNameList) {
1577 if (isMatchingHostname(commonName.toLower(), peerName.toLower())) {
1582 foreach (const QString &altName, cert.subjectAlternativeNames().values(QSsl::DnsEntry)) {
1583 if (isMatchingHostname(altName.toLower(), peerName.toLower())) {
1591 bool QSslSocketBackendPrivate::isMatchingHostname(const QString &cn, const QString &hostname)
1593 int wildcard = cn.indexOf(QLatin1Char('*'));
1595 // Check this is a wildcard cert, if not then just compare the strings
1597 return cn == hostname;
1599 int firstCnDot = cn.indexOf(QLatin1Char('.'));
1600 int secondCnDot = cn.indexOf(QLatin1Char('.'), firstCnDot+1);
1602 // Check at least 3 components
1603 if ((-1 == secondCnDot) || (secondCnDot+1 >= cn.length()))
1606 // Check * is last character of 1st component (ie. there's a following .)
1607 if (wildcard+1 != firstCnDot)
1610 // Check only one star
1611 if (cn.lastIndexOf(QLatin1Char('*')) != wildcard)
1614 // Check characters preceding * (if any) match
1615 if (wildcard && (hostname.leftRef(wildcard) != cn.leftRef(wildcard)))
1618 // Check characters following first . match
1619 if (hostname.midRef(hostname.indexOf(QLatin1Char('.'))) != cn.midRef(firstCnDot))
1622 // Check if the hostname is an IP address, if so then wildcards are not allowed
1623 QHostAddress addr(hostname);
1627 // Ok, I guess this was a wildcard CN and the hostname matches.
1631 QList<QSslError> QSslSocketBackendPrivate::verify(QList<QSslCertificate> certificateChain, const QString &hostName)
1633 QList<QSslError> errors;
1634 if (certificateChain.count() <= 0) {
1635 errors << QSslError(QSslError::UnspecifiedError);
1639 // Setup the store with the default CA certificates
1640 X509_STORE *certStore = q_X509_STORE_new();
1642 qWarning() << "Unable to create certificate store";
1643 errors << QSslError(QSslError::UnspecifiedError);
1647 if (s_loadRootCertsOnDemand) {
1648 setDefaultCaCertificates(defaultCaCertificates() + systemCaCertificates());
1651 QList<QSslCertificate> expiredCerts;
1653 foreach (const QSslCertificate &caCertificate, QSslSocket::defaultCaCertificates()) {
1654 // add expired certs later, so that the
1655 // valid ones are used before the expired ones
1656 if (caCertificate.expiryDate() < QDateTime::currentDateTime()) {
1657 expiredCerts.append(caCertificate);
1659 q_X509_STORE_add_cert(certStore, reinterpret_cast<X509 *>(caCertificate.handle()));
1663 bool addExpiredCerts = true;
1664 #if defined(Q_OS_MAC) && (MAC_OS_X_VERSION_MAX_ALLOWED == MAC_OS_X_VERSION_10_5)
1665 //On Leopard SSL does not work if we add the expired certificates.
1666 if (QSysInfo::MacintoshVersion == QSysInfo::MV_10_5)
1667 addExpiredCerts = false;
1669 // now add the expired certs
1670 if (addExpiredCerts) {
1671 foreach (const QSslCertificate &caCertificate, expiredCerts) {
1672 q_X509_STORE_add_cert(certStore, reinterpret_cast<X509 *>(caCertificate.handle()));
1676 QMutexLocker sslErrorListMutexLocker(&_q_sslErrorList()->mutex);
1678 // Register a custom callback to get all verification errors.
1679 X509_STORE_set_verify_cb_func(certStore, q_X509Callback);
1681 // Build the chain of intermediate certificates
1682 STACK_OF(X509) *intermediates = 0;
1683 if (certificateChain.length() > 1) {
1684 intermediates = (STACK_OF(X509) *) q_sk_new_null();
1686 if (!intermediates) {
1687 q_X509_STORE_free(certStore);
1688 errors << QSslError(QSslError::UnspecifiedError);
1693 foreach (const QSslCertificate &cert, certificateChain) {
1698 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
1699 q_sk_push( (_STACK *)intermediates, reinterpret_cast<X509 *>(cert.handle()));
1701 q_sk_push( (STACK *)intermediates, reinterpret_cast<X509 *>(cert.handle()));
1706 X509_STORE_CTX *storeContext = q_X509_STORE_CTX_new();
1707 if (!storeContext) {
1708 q_X509_STORE_free(certStore);
1709 errors << QSslError(QSslError::UnspecifiedError);
1713 if (!q_X509_STORE_CTX_init(storeContext, certStore, reinterpret_cast<X509 *>(certificateChain[0].handle()), intermediates)) {
1714 q_X509_STORE_CTX_free(storeContext);
1715 q_X509_STORE_free(certStore);
1716 errors << QSslError(QSslError::UnspecifiedError);
1720 // Now we can actually perform the verification of the chain we have built.
1721 // We ignore the result of this function since we process errors via the
1723 (void) q_X509_verify_cert(storeContext);
1725 q_X509_STORE_CTX_free(storeContext);
1726 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
1727 q_sk_free( (_STACK *) intermediates);
1729 q_sk_free( (STACK *) intermediates);
1732 // Now process the errors
1733 const QList<QPair<int, int> > errorList = _q_sslErrorList()->errors;
1734 _q_sslErrorList()->errors.clear();
1736 sslErrorListMutexLocker.unlock();
1738 // Translate the errors
1739 if (QSslCertificatePrivate::isBlacklisted(certificateChain[0])) {
1740 QSslError error(QSslError::CertificateBlacklisted, certificateChain[0]);
1744 // Check the certificate name against the hostname if one was specified
1745 if ((!hostName.isEmpty()) && (!isMatchingHostname(certificateChain[0], hostName))) {
1746 // No matches in common names or alternate names.
1747 QSslError error(QSslError::HostNameMismatch, certificateChain[0]);
1751 // Translate errors from the error list into QSslErrors.
1752 for (int i = 0; i < errorList.size(); ++i) {
1753 const QPair<int, int> &errorAndDepth = errorList.at(i);
1754 int err = errorAndDepth.first;
1755 int depth = errorAndDepth.second;
1756 errors << _q_OpenSSL_to_QSslError(err, certificateChain.value(depth));
1759 q_X509_STORE_free(certStore);