1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
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
64 Q_DECLARE_METATYPE(QSslCertificate);
69 #if defined(Q_OS_MAC) && !defined(Q_OS_IOS)
70 #define kSecTrustSettingsDomainSystem 2 // so we do not need to include the header file
71 PtrSecCertificateGetData QSslSocketPrivate::ptrSecCertificateGetData = 0;
72 PtrSecTrustSettingsCopyCertificates QSslSocketPrivate::ptrSecTrustSettingsCopyCertificates = 0;
73 PtrSecTrustCopyAnchorCertificates QSslSocketPrivate::ptrSecTrustCopyAnchorCertificates = 0;
74 #elif defined(Q_OS_WIN)
75 PtrCertOpenSystemStoreW QSslSocketPrivate::ptrCertOpenSystemStoreW = 0;
76 PtrCertFindCertificateInStore QSslSocketPrivate::ptrCertFindCertificateInStore = 0;
77 PtrCertCloseStore QSslSocketPrivate::ptrCertCloseStore = 0;
80 bool QSslSocketPrivate::s_libraryLoaded = false;
81 bool QSslSocketPrivate::s_loadedCiphersAndCerts = false;
82 bool QSslSocketPrivate::s_loadRootCertsOnDemand = false;
86 From OpenSSL's thread(3) manual page:
88 OpenSSL can safely be used in multi-threaded applications provided that at
89 least two callback functions are set.
91 locking_function(int mode, int n, const char *file, int line) is needed to
92 perform locking on shared data structures. (Note that OpenSSL uses a
93 number of global data structures that will be implicitly shared
94 when-whenever ever multiple threads use OpenSSL.) Multi-threaded
95 applications will crash at random if it is not set. ...
97 id_function(void) is a function that returns a thread ID. It is not
98 needed on Windows nor on platforms where getpid() returns a different
99 ID for each thread (most notably Linux)
104 inline QOpenSslLocks()
105 : initLocker(QMutex::Recursive),
106 locksLocker(QMutex::Recursive)
108 QMutexLocker locker(&locksLocker);
109 int numLocks = q_CRYPTO_num_locks();
110 locks = new QMutex *[numLocks];
111 memset(locks, 0, numLocks * sizeof(QMutex *));
113 inline ~QOpenSslLocks()
115 QMutexLocker locker(&locksLocker);
116 for (int i = 0; i < q_CRYPTO_num_locks(); ++i)
120 QSslSocketPrivate::deinitialize();
122 inline QMutex *lock(int num)
124 QMutexLocker locker(&locksLocker);
125 QMutex *tmp = locks[num];
127 tmp = locks[num] = new QMutex(QMutex::Recursive);
146 Q_GLOBAL_STATIC(QOpenSslLocks, openssl_locks)
149 static void locking_function(int mode, int lockNumber, const char *, int)
151 QMutex *mutex = openssl_locks()->lock(lockNumber);
154 if (mode & CRYPTO_LOCK)
159 static unsigned long id_function()
161 return (quintptr)QThread::currentThreadId();
165 QSslSocketBackendPrivate::QSslSocketBackendPrivate()
173 // Calls SSL_library_init().
177 QSslSocketBackendPrivate::~QSslSocketBackendPrivate()
182 QSslCipher QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(SSL_CIPHER *cipher)
187 QString descriptionOneLine = QString::fromLatin1(q_SSL_CIPHER_description(cipher, buf, sizeof(buf)));
189 QStringList descriptionList = descriptionOneLine.split(QLatin1String(" "), QString::SkipEmptyParts);
190 if (descriptionList.size() > 5) {
192 ciph.d->isNull = false;
193 ciph.d->name = descriptionList.at(0);
195 QString protoString = descriptionList.at(1);
196 ciph.d->protocolString = protoString;
197 ciph.d->protocol = QSsl::UnknownProtocol;
198 if (protoString == QLatin1String("SSLv3"))
199 ciph.d->protocol = QSsl::SslV3;
200 else if (protoString == QLatin1String("SSLv2"))
201 ciph.d->protocol = QSsl::SslV2;
202 else if (protoString == QLatin1String("TLSv1"))
203 ciph.d->protocol = QSsl::TlsV1_0;
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>(ctx->error, ctx->error_depth);
233 #ifdef QSSLSOCKET_DEBUG
234 qDebug() << "verification error: dumping bad certificate";
235 qDebug() << QSslCertificatePrivate::QSslCertificate_from_X509(ctx->current_cert).toPem();
236 qDebug() << "dumping chain";
237 foreach (QSslCertificate cert, QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates(ctx->chain)) {
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());
327 // After stopping Flash 10 the SSL library looses its ciphers. Try re-adding them
328 // by re-initializing the library.
329 if (!reinitialized) {
330 reinitialized = true;
331 if (q_SSL_library_init() == 1)
335 q->setErrorString(QSslSocket::tr("Error creating SSL context (%1)").arg(getErrorsFromOpenSsl()));
336 q->setSocketError(QAbstractSocket::SslInternalError);
337 emit q->error(QAbstractSocket::SslInternalError);
341 // Enable bug workarounds.
342 long options = setupOpenSslOptions(configuration.protocol, configuration.sslOptions);
343 q_SSL_CTX_set_options(ctx, options);
345 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
346 // Tell OpenSSL to release memory early
347 // http://www.openssl.org/docs/ssl/SSL_CTX_set_mode.html
348 if (q_SSLeay() >= 0x10000000L)
349 q_SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
352 // Initialize ciphers
353 QByteArray cipherString;
355 QList<QSslCipher> ciphers = configuration.ciphers;
356 if (ciphers.isEmpty())
357 ciphers = defaultCiphers();
358 foreach (const QSslCipher &cipher, ciphers) {
362 cipherString.append(':');
363 cipherString.append(cipher.name().toLatin1());
366 if (!q_SSL_CTX_set_cipher_list(ctx, cipherString.data())) {
367 q->setErrorString(QSslSocket::tr("Invalid or empty cipher list (%1)").arg(getErrorsFromOpenSsl()));
368 q->setSocketError(QAbstractSocket::SslInvalidUserDataError);
369 emit q->error(QAbstractSocket::SslInvalidUserDataError);
373 // Add all our CAs to this store.
374 QList<QSslCertificate> expiredCerts;
375 foreach (const QSslCertificate &caCertificate, q->caCertificates()) {
376 // add expired certs later, so that the
377 // valid ones are used before the expired ones
378 if (caCertificate.expiryDate() < QDateTime::currentDateTime()) {
379 expiredCerts.append(caCertificate);
381 q_X509_STORE_add_cert(ctx->cert_store, reinterpret_cast<X509 *>(caCertificate.handle()));
385 bool addExpiredCerts = true;
386 #if defined(Q_OS_MAC) && (MAC_OS_X_VERSION_MAX_ALLOWED == MAC_OS_X_VERSION_10_5)
387 //On Leopard SSL does not work if we add the expired certificates.
388 if (QSysInfo::MacintoshVersion == QSysInfo::MV_10_5)
389 addExpiredCerts = false;
391 // now add the expired certs
392 if (addExpiredCerts) {
393 foreach (const QSslCertificate &caCertificate, expiredCerts) {
394 q_X509_STORE_add_cert(ctx->cert_store, reinterpret_cast<X509 *>(caCertificate.handle()));
398 if (s_loadRootCertsOnDemand && allowRootCertOnDemandLoading) {
399 // tell OpenSSL the directories where to look up the root certs on demand
400 QList<QByteArray> unixDirs = unixRootCertDirectories();
401 for (int a = 0; a < unixDirs.count(); ++a)
402 q_SSL_CTX_load_verify_locations(ctx, 0, unixDirs.at(a).constData());
405 // Register a custom callback to get all verification errors.
406 X509_STORE_set_verify_cb_func(ctx->cert_store, q_X509Callback);
408 if (!configuration.localCertificate.isNull()) {
409 // Require a private key as well.
410 if (configuration.privateKey.isNull()) {
411 q->setErrorString(QSslSocket::tr("Cannot provide a certificate with no key, %1").arg(getErrorsFromOpenSsl()));
412 q->setSocketError(QAbstractSocket::SslInvalidUserDataError);
413 emit q->error(QAbstractSocket::SslInvalidUserDataError);
418 if (!q_SSL_CTX_use_certificate(ctx, reinterpret_cast<X509 *>(configuration.localCertificate.handle()))) {
419 q->setErrorString(QSslSocket::tr("Error loading local certificate, %1").arg(getErrorsFromOpenSsl()));
420 q->setSocketError(QAbstractSocket::SslInternalError);
421 emit q->error(QAbstractSocket::SslInternalError);
425 if (configuration.privateKey.algorithm() == QSsl::Opaque) {
426 pkey = reinterpret_cast<EVP_PKEY *>(configuration.privateKey.handle());
429 pkey = q_EVP_PKEY_new();
430 // before we were using EVP_PKEY_assign_R* functions and did not use EVP_PKEY_free.
431 // this lead to a memory leak. Now we use the *_set1_* functions which do not
432 // take ownership of the RSA/DSA key instance because the QSslKey already has ownership.
433 if (configuration.privateKey.algorithm() == QSsl::Rsa)
434 q_EVP_PKEY_set1_RSA(pkey, reinterpret_cast<RSA *>(configuration.privateKey.handle()));
436 q_EVP_PKEY_set1_DSA(pkey, reinterpret_cast<DSA *>(configuration.privateKey.handle()));
439 if (!q_SSL_CTX_use_PrivateKey(ctx, pkey)) {
440 q->setErrorString(QSslSocket::tr("Error loading private key, %1").arg(getErrorsFromOpenSsl()));
441 q->setSocketError(QAbstractSocket::SslInternalError);
442 emit q->error(QAbstractSocket::SslInternalError);
445 if (configuration.privateKey.algorithm() == QSsl::Opaque)
446 pkey = 0; // Don't free the private key, it belongs to QSslKey
448 // Check if the certificate matches the private key.
449 if (!q_SSL_CTX_check_private_key(ctx)) {
450 q->setErrorString(QSslSocket::tr("Private key does not certify public key, %1").arg(getErrorsFromOpenSsl()));
451 q->setSocketError(QAbstractSocket::SslInvalidUserDataError);
452 emit q->error(QAbstractSocket::SslInvalidUserDataError);
457 // Initialize peer verification.
458 if (configuration.peerVerifyMode == QSslSocket::VerifyNone) {
459 q_SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
461 q_SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, q_X509Callback);
464 // Set verification depth.
465 if (configuration.peerVerifyDepth != 0)
466 q_SSL_CTX_set_verify_depth(ctx, configuration.peerVerifyDepth);
468 // Create and initialize SSL session
469 if (!(ssl = q_SSL_new(ctx))) {
470 // ### Bad error code
471 q->setErrorString(QSslSocket::tr("Error creating SSL session, %1").arg(getErrorsFromOpenSsl()));
472 q->setSocketError(QAbstractSocket::SslInternalError);
473 emit q->error(QAbstractSocket::SslInternalError);
477 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
478 if ((configuration.protocol == QSsl::TlsV1SslV3 ||
479 configuration.protocol == QSsl::TlsV1_0 ||
480 configuration.protocol == QSsl::SecureProtocols ||
481 configuration.protocol == QSsl::AnyProtocol) &&
482 client && q_SSLeay() >= 0x00090806fL) {
483 // Set server hostname on TLS extension. RFC4366 section 3.1 requires it in ACE format.
484 QString tlsHostName = verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName;
485 if (tlsHostName.isEmpty())
486 tlsHostName = hostName;
487 QByteArray ace = QUrl::toAce(tlsHostName);
488 // only send the SNI header if the URL is valid and not an IP
490 && !QHostAddress().setAddress(tlsHostName)
491 && !(configuration.sslOptions & QSsl::SslOptionDisableServerNameIndication)) {
492 if (!q_SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, ace.data()))
493 qWarning("could not set SSL_CTRL_SET_TLSEXT_HOSTNAME, Server Name Indication disabled");
498 // Clear the session.
502 // Initialize memory BIOs for encryption and decryption.
503 readBio = q_BIO_new(q_BIO_s_mem());
504 writeBio = q_BIO_new(q_BIO_s_mem());
505 if (!readBio || !writeBio) {
506 q->setErrorString(QSslSocket::tr("Error creating SSL session: %1").arg(getErrorsFromOpenSsl()));
507 q->setSocketError(QAbstractSocket::SslInternalError);
508 emit q->error(QAbstractSocket::SslInternalError);
513 q_SSL_set_bio(ssl, readBio, writeBio);
515 if (mode == QSslSocket::SslClientMode)
516 q_SSL_set_connect_state(ssl);
518 q_SSL_set_accept_state(ssl);
523 void QSslSocketBackendPrivate::destroySslContext()
534 q_EVP_PKEY_free(pkey);
542 void QSslSocketPrivate::deinitialize()
544 q_CRYPTO_set_id_callback(0);
545 q_CRYPTO_set_locking_callback(0);
546 q_ERR_free_strings();
552 Does the minimum amount of initialization to determine whether SSL
556 bool QSslSocketPrivate::supportsSsl()
558 return ensureLibraryLoaded();
561 bool QSslSocketPrivate::ensureLibraryLoaded()
563 if (!q_resolveOpenSslSymbols())
566 // Check if the library itself needs to be initialized.
567 QMutexLocker locker(openssl_locks()->initLock());
569 if (!s_libraryLoaded) {
570 s_libraryLoaded = true;
572 // Initialize OpenSSL.
573 q_CRYPTO_set_id_callback(id_function);
574 q_CRYPTO_set_locking_callback(locking_function);
575 if (q_SSL_library_init() != 1)
577 q_SSL_load_error_strings();
578 q_OpenSSL_add_all_algorithms();
580 // Initialize OpenSSL's random seed.
581 if (!q_RAND_status()) {
590 if (attempts < 500) {
592 struct timespec ts = {0, 33333333};
597 randomish.msec = attempts;
599 randomish.stack = (void *)&randomish;
600 randomish.msec = QTime::currentTime().msec();
601 randomish.sec = QTime::currentTime().second();
602 q_RAND_seed((const char *)&randomish, sizeof(randomish));
603 } while (!q_RAND_status() && --attempts);
611 void QSslSocketPrivate::ensureCiphersAndCertsLoaded()
613 QMutexLocker locker(openssl_locks()->initLock());
614 if (s_loadedCiphersAndCerts)
616 s_loadedCiphersAndCerts = true;
618 resetDefaultCiphers();
620 //load symbols needed to receive certificates from system store
621 #if defined(Q_OS_MAC) && !defined(Q_OS_IOS)
622 QLibrary securityLib("/System/Library/Frameworks/Security.framework/Versions/Current/Security");
623 if (securityLib.load()) {
624 ptrSecCertificateGetData = (PtrSecCertificateGetData) securityLib.resolve("SecCertificateGetData");
625 if (!ptrSecCertificateGetData)
626 qWarning("could not resolve symbols in security library"); // should never happen
628 ptrSecTrustSettingsCopyCertificates = (PtrSecTrustSettingsCopyCertificates) securityLib.resolve("SecTrustSettingsCopyCertificates");
629 if (!ptrSecTrustSettingsCopyCertificates) { // method was introduced in Leopard, use legacy method if it's not there
630 ptrSecTrustCopyAnchorCertificates = (PtrSecTrustCopyAnchorCertificates) securityLib.resolve("SecTrustCopyAnchorCertificates");
631 if (!ptrSecTrustCopyAnchorCertificates)
632 qWarning("could not resolve symbols in security library"); // should never happen
635 qWarning("could not load security library");
637 #elif defined(Q_OS_WIN)
638 HINSTANCE hLib = LoadLibraryW(L"Crypt32");
640 #if defined(Q_OS_WINCE)
641 ptrCertOpenSystemStoreW = (PtrCertOpenSystemStoreW)GetProcAddress(hLib, L"CertOpenStore");
642 ptrCertFindCertificateInStore = (PtrCertFindCertificateInStore)GetProcAddress(hLib, L"CertFindCertificateInStore");
643 ptrCertCloseStore = (PtrCertCloseStore)GetProcAddress(hLib, L"CertCloseStore");
645 ptrCertOpenSystemStoreW = (PtrCertOpenSystemStoreW)GetProcAddress(hLib, "CertOpenSystemStoreW");
646 ptrCertFindCertificateInStore = (PtrCertFindCertificateInStore)GetProcAddress(hLib, "CertFindCertificateInStore");
647 ptrCertCloseStore = (PtrCertCloseStore)GetProcAddress(hLib, "CertCloseStore");
649 if (!ptrCertOpenSystemStoreW || !ptrCertFindCertificateInStore || !ptrCertCloseStore)
650 qWarning("could not resolve symbols in crypt32 library"); // should never happen
652 qWarning("could not load crypt32 library"); // should never happen
654 #elif defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
655 // check whether we can enable on-demand root-cert loading (i.e. check whether the sym links are there)
656 QList<QByteArray> dirs = unixRootCertDirectories();
657 QStringList symLinkFilter;
658 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]");
659 for (int a = 0; a < dirs.count(); ++a) {
660 QDirIterator iterator(QLatin1String(dirs.at(a)), symLinkFilter, QDir::Files);
661 if (iterator.hasNext()) {
662 s_loadRootCertsOnDemand = true;
667 // if on-demand loading was not enabled, load the certs now
668 if (!s_loadRootCertsOnDemand)
669 setDefaultCaCertificates(systemCaCertificates());
671 //Enabled for fetching additional root certs from windows update on windows 6+
672 //This flag is set false by setDefaultCaCertificates() indicating the app uses
673 //its own cert bundle rather than the system one.
674 //Same logic that disables the unix on demand cert loading.
675 //Unlike unix, we do preload the certificates from the cert store.
676 if ((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_6_0)
677 s_loadRootCertsOnDemand = true;
684 Declared static in QSslSocketPrivate, makes sure the SSL libraries have
688 void QSslSocketPrivate::ensureInitialized()
693 ensureCiphersAndCertsLoaded();
696 long QSslSocketPrivate::sslLibraryVersionNumber()
701 QString QSslSocketPrivate::sslLibraryVersionString()
706 const char *versionString = q_SSLeay_version(SSLEAY_VERSION);
710 return QString::fromLatin1(versionString);
716 Declared static in QSslSocketPrivate, backend-dependent loading of
717 application-wide global ciphers.
719 void QSslSocketPrivate::resetDefaultCiphers()
721 SSL_CTX *myCtx = q_SSL_CTX_new(q_SSLv23_client_method());
722 SSL *mySsl = q_SSL_new(myCtx);
724 QList<QSslCipher> ciphers;
726 STACK_OF(SSL_CIPHER) *supportedCiphers = q_SSL_get_ciphers(mySsl);
727 for (int i = 0; i < q_sk_SSL_CIPHER_num(supportedCiphers); ++i) {
728 if (SSL_CIPHER *cipher = q_sk_SSL_CIPHER_value(supportedCiphers, i)) {
730 QSslCipher ciph = QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(cipher);
731 if (!ciph.isNull()) {
732 if (!ciph.name().toLower().startsWith(QLatin1String("adh")))
739 q_SSL_CTX_free(myCtx);
742 setDefaultSupportedCiphers(ciphers);
743 setDefaultCiphers(ciphers);
746 QList<QSslCertificate> QSslSocketPrivate::systemCaCertificates()
749 #ifdef QSSLSOCKET_DEBUG
753 QList<QSslCertificate> systemCerts;
754 #if defined(Q_OS_MAC) && !defined(Q_OS_IOS)
758 OSStatus SecCertificateGetData (
759 SecCertificateRef certificate,
763 if (ptrSecCertificateGetData) {
764 if (ptrSecTrustSettingsCopyCertificates)
765 status = ptrSecTrustSettingsCopyCertificates(kSecTrustSettingsDomainSystem, &cfCerts);
766 else if (ptrSecTrustCopyAnchorCertificates)
767 status = ptrSecTrustCopyAnchorCertificates(&cfCerts);
769 CFIndex size = CFArrayGetCount(cfCerts);
770 for (CFIndex i = 0; i < size; ++i) {
771 SecCertificateRef cfCert = (SecCertificateRef)CFArrayGetValueAtIndex(cfCerts, i);
773 CSSM_DATA_PTR dataPtr = &data;
774 if (ptrSecCertificateGetData(cfCert, dataPtr)) {
775 qWarning("error retrieving a CA certificate from the system store");
777 int len = data.Length;
778 char *rawData = reinterpret_cast<char *>(data.Data);
779 QByteArray rawCert(rawData, len);
780 systemCerts.append(QSslCertificate::fromData(rawCert, QSsl::Der));
786 // no detailed error handling here
787 qWarning("could not retrieve system CA certificates");
790 #elif defined(Q_OS_WIN)
791 if (ptrCertOpenSystemStoreW && ptrCertFindCertificateInStore && ptrCertCloseStore) {
792 HCERTSTORE hSystemStore;
793 #if defined(Q_OS_WINCE)
794 hSystemStore = ptrCertOpenSystemStoreW(CERT_STORE_PROV_SYSTEM_W,
797 CERT_STORE_NO_CRYPT_RELEASE_FLAG|CERT_SYSTEM_STORE_CURRENT_USER,
800 hSystemStore = ptrCertOpenSystemStoreW(0, L"ROOT");
803 PCCERT_CONTEXT pc = NULL;
805 pc = ptrCertFindCertificateInStore( hSystemStore, X509_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, pc);
808 QByteArray der((const char *)(pc->pbCertEncoded), static_cast<int>(pc->cbCertEncoded));
809 QSslCertificate cert(der, QSsl::Der);
810 systemCerts.append(cert);
812 ptrCertCloseStore(hSystemStore, 0);
815 #elif defined(Q_OS_UNIX)
816 QSet<QString> certFiles;
817 QList<QByteArray> directories = unixRootCertDirectories();
819 QStringList nameFilters;
820 nameFilters << QLatin1String("*.pem") << QLatin1String("*.crt");
821 currentDir.setNameFilters(nameFilters);
822 for (int a = 0; a < directories.count(); a++) {
823 currentDir.setPath(QLatin1String(directories.at(a)));
824 QDirIterator it(currentDir);
825 while(it.hasNext()) {
827 // use canonical path here to not load the same certificate twice if symlinked
828 certFiles.insert(it.fileInfo().canonicalFilePath());
831 QSetIterator<QString> it(certFiles);
832 while(it.hasNext()) {
833 systemCerts.append(QSslCertificate::fromPath(it.next()));
835 systemCerts.append(QSslCertificate::fromPath(QLatin1String("/etc/pki/tls/certs/ca-bundle.crt"), QSsl::Pem)); // Fedora, Mandriva
836 systemCerts.append(QSslCertificate::fromPath(QLatin1String("/usr/local/share/certs/ca-root-nss.crt"), QSsl::Pem)); // FreeBSD's ca_root_nss
838 #ifdef QSSLSOCKET_DEBUG
839 qDebug() << "systemCaCertificates retrieval time " << timer.elapsed() << "ms";
840 qDebug() << "imported " << systemCerts.count() << " certificates";
846 void QSslSocketBackendPrivate::startClientEncryption()
849 if (!initSslContext()) {
850 q->setErrorString(QSslSocket::tr("Unable to init Ssl Context: %1").arg(getErrorsFromOpenSsl()));
851 q->setSocketError(QAbstractSocket::SslInternalError);
852 emit q->error(QAbstractSocket::SslInternalError);
856 // Start connecting. This will place outgoing data in the BIO, so we
857 // follow up with calling transmit().
862 void QSslSocketBackendPrivate::startServerEncryption()
865 if (!initSslContext()) {
866 q->setErrorString(QSslSocket::tr("Unable to init Ssl Context: %1").arg(getErrorsFromOpenSsl()));
867 q->setSocketError(QAbstractSocket::SslInternalError);
868 emit q->error(QAbstractSocket::SslInternalError);
872 // Start connecting. This will place outgoing data in the BIO, so we
873 // follow up with calling transmit().
881 Transmits encrypted data between the BIOs and the socket.
883 void QSslSocketBackendPrivate::transmit()
887 // If we don't have any SSL context, don't bother transmitting.
893 transmitting = false;
895 // If the connection is secure, we can transfer data from the write
896 // buffer (in plain text) to the write BIO through SSL_write.
897 if (connectionEncrypted && !writeBuffer.isEmpty()) {
898 qint64 totalBytesWritten = 0;
899 int nextDataBlockSize;
900 while ((nextDataBlockSize = writeBuffer.nextDataBlockSize()) > 0) {
901 int writtenBytes = q_SSL_write(ssl, writeBuffer.readPointer(), nextDataBlockSize);
902 if (writtenBytes <= 0) {
903 // ### Better error handling.
904 q->setErrorString(QSslSocket::tr("Unable to write data: %1").arg(getErrorsFromOpenSsl()));
905 q->setSocketError(QAbstractSocket::SslInternalError);
906 emit q->error(QAbstractSocket::SslInternalError);
909 #ifdef QSSLSOCKET_DEBUG
910 qDebug() << "QSslSocketBackendPrivate::transmit: encrypted" << writtenBytes << "bytes";
912 writeBuffer.free(writtenBytes);
913 totalBytesWritten += writtenBytes;
915 if (writtenBytes < nextDataBlockSize) {
916 // break out of the writing loop and try again after we had read
922 if (totalBytesWritten > 0) {
923 // Don't emit bytesWritten() recursively.
924 if (!emittedBytesWritten) {
925 emittedBytesWritten = true;
926 emit q->bytesWritten(totalBytesWritten);
927 emittedBytesWritten = false;
932 // Check if we've got any data to be written to the socket.
933 QVarLengthArray<char, 4096> data;
935 while (plainSocket->isValid() && (pendingBytes = q_BIO_pending(writeBio)) > 0) {
936 // Read encrypted data from the write BIO into a buffer.
937 data.resize(pendingBytes);
938 int encryptedBytesRead = q_BIO_read(writeBio, data.data(), pendingBytes);
940 // Write encrypted data from the buffer to the socket.
941 qint64 actualWritten = plainSocket->write(data.constData(), encryptedBytesRead);
942 #ifdef QSSLSOCKET_DEBUG
943 qDebug() << "QSslSocketBackendPrivate::transmit: wrote" << encryptedBytesRead << "encrypted bytes to the socket" << actualWritten << "actual.";
945 if (actualWritten < 0) {
946 //plain socket write fails if it was in the pending close state.
947 q->setErrorString(plainSocket->errorString());
948 q->setSocketError(plainSocket->error());
949 emit q->error(plainSocket->error());
955 // Check if we've got any data to be read from the socket.
956 if (!connectionEncrypted || !readBufferMaxSize || readBuffer.size() < readBufferMaxSize)
957 while ((pendingBytes = plainSocket->bytesAvailable()) > 0) {
958 // Read encrypted data from the socket into a buffer.
959 data.resize(pendingBytes);
960 // just peek() here because q_BIO_write could write less data than expected
961 int encryptedBytesRead = plainSocket->peek(data.data(), pendingBytes);
962 #ifdef QSSLSOCKET_DEBUG
963 qDebug() << "QSslSocketBackendPrivate::transmit: read" << encryptedBytesRead << "encrypted bytes from the socket";
965 // Write encrypted data from the buffer into the read BIO.
966 int writtenToBio = q_BIO_write(readBio, data.constData(), encryptedBytesRead);
968 // do the actual read() here and throw away the results.
969 if (writtenToBio > 0) {
970 // ### TODO: make this cheaper by not making it memcpy. E.g. make it work with data=0x0 or make it work with seek
971 plainSocket->read(data.data(), writtenToBio);
973 // ### Better error handling.
974 q->setErrorString(QSslSocket::tr("Unable to decrypt data: %1").arg(getErrorsFromOpenSsl()));
975 q->setSocketError(QAbstractSocket::SslInternalError);
976 emit q->error(QAbstractSocket::SslInternalError);
983 // If the connection isn't secured yet, this is the time to retry the
985 if (!connectionEncrypted) {
986 #ifdef QSSLSOCKET_DEBUG
987 qDebug() << "QSslSocketBackendPrivate::transmit: testing encryption";
989 if (startHandshake()) {
990 #ifdef QSSLSOCKET_DEBUG
991 qDebug() << "QSslSocketBackendPrivate::transmit: encryption established";
993 connectionEncrypted = true;
995 } else if (plainSocket->state() != QAbstractSocket::ConnectedState) {
996 #ifdef QSSLSOCKET_DEBUG
997 qDebug() << "QSslSocketBackendPrivate::transmit: connection lost";
1000 } else if (paused) {
1001 // just wait until the user continues
1004 #ifdef QSSLSOCKET_DEBUG
1005 qDebug() << "QSslSocketBackendPrivate::transmit: encryption not done yet";
1010 // If the request is small and the remote host closes the transmission
1011 // after sending, there's a chance that startHandshake() will already
1012 // have triggered a shutdown.
1016 // We always read everything from the SSL decryption buffers, even if
1017 // we have a readBufferMaxSize. There's no point in leaving data there
1018 // just so that readBuffer.size() == readBufferMaxSize.
1021 ::memset(data.data(), 0, data.size());
1023 // Don't use SSL_pending(). It's very unreliable.
1024 if ((readBytes = q_SSL_read(ssl, data.data(), data.size())) > 0) {
1025 #ifdef QSSLSOCKET_DEBUG
1026 qDebug() << "QSslSocketBackendPrivate::transmit: decrypted" << readBytes << "bytes";
1028 char *ptr = readBuffer.reserve(readBytes);
1029 ::memcpy(ptr, data.data(), readBytes);
1031 if (readyReadEmittedPointer)
1032 *readyReadEmittedPointer = true;
1033 emit q->readyRead();
1034 transmitting = true;
1039 switch (q_SSL_get_error(ssl, readBytes)) {
1040 case SSL_ERROR_WANT_READ:
1041 case SSL_ERROR_WANT_WRITE:
1044 case SSL_ERROR_ZERO_RETURN:
1045 // The remote host closed the connection.
1046 #ifdef QSSLSOCKET_DEBUG
1047 qDebug() << "QSslSocketBackendPrivate::transmit: remote disconnect";
1049 plainSocket->disconnectFromHost();
1051 case SSL_ERROR_SYSCALL: // some IO error
1052 case SSL_ERROR_SSL: // error in the SSL library
1053 // we do not know exactly what the error is, nor whether we can recover from it,
1054 // so just return to prevent an endless loop in the outer "while" statement
1055 q->setErrorString(QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
1056 q->setSocketError(QAbstractSocket::SslInternalError);
1057 emit q->error(QAbstractSocket::SslInternalError);
1060 // SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT: can only happen with a
1061 // BIO_s_connect() or BIO_s_accept(), which we do not call.
1062 // SSL_ERROR_WANT_X509_LOOKUP: can only happen with a
1063 // SSL_CTX_set_client_cert_cb(), which we do not call.
1064 // So this default case should never be triggered.
1065 q->setErrorString(QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
1066 q->setSocketError(QAbstractSocket::SslInternalError);
1067 emit q->error(QAbstractSocket::SslInternalError);
1070 } while (ssl && readBytes > 0);
1071 } while (ssl && ctx && transmitting);
1074 static QSslError _q_OpenSSL_to_QSslError(int errorCode, const QSslCertificate &cert)
1077 switch (errorCode) {
1079 // X509_V_OK is also reported if the peer had no certificate.
1081 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1082 error = QSslError(QSslError::UnableToGetIssuerCertificate, cert); break;
1083 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1084 error = QSslError(QSslError::UnableToDecryptCertificateSignature, cert); break;
1085 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1086 error = QSslError(QSslError::UnableToDecodeIssuerPublicKey, cert); break;
1087 case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1088 error = QSslError(QSslError::CertificateSignatureFailed, cert); break;
1089 case X509_V_ERR_CERT_NOT_YET_VALID:
1090 error = QSslError(QSslError::CertificateNotYetValid, cert); break;
1091 case X509_V_ERR_CERT_HAS_EXPIRED:
1092 error = QSslError(QSslError::CertificateExpired, cert); break;
1093 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1094 error = QSslError(QSslError::InvalidNotBeforeField, cert); break;
1095 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1096 error = QSslError(QSslError::InvalidNotAfterField, cert); break;
1097 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1098 error = QSslError(QSslError::SelfSignedCertificate, cert); break;
1099 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1100 error = QSslError(QSslError::SelfSignedCertificateInChain, cert); break;
1101 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1102 error = QSslError(QSslError::UnableToGetLocalIssuerCertificate, cert); break;
1103 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1104 error = QSslError(QSslError::UnableToVerifyFirstCertificate, cert); break;
1105 case X509_V_ERR_CERT_REVOKED:
1106 error = QSslError(QSslError::CertificateRevoked, cert); break;
1107 case X509_V_ERR_INVALID_CA:
1108 error = QSslError(QSslError::InvalidCaCertificate, cert); break;
1109 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1110 error = QSslError(QSslError::PathLengthExceeded, cert); break;
1111 case X509_V_ERR_INVALID_PURPOSE:
1112 error = QSslError(QSslError::InvalidPurpose, cert); break;
1113 case X509_V_ERR_CERT_UNTRUSTED:
1114 error = QSslError(QSslError::CertificateUntrusted, cert); break;
1115 case X509_V_ERR_CERT_REJECTED:
1116 error = QSslError(QSslError::CertificateRejected, cert); break;
1118 error = QSslError(QSslError::UnspecifiedError, cert); break;
1123 bool QSslSocketBackendPrivate::startHandshake()
1127 // Check if the connection has been established. Get all errors from the
1128 // verification stage.
1129 _q_sslErrorList()->mutex.lock();
1130 _q_sslErrorList()->errors.clear();
1131 int result = (mode == QSslSocket::SslClientMode) ? q_SSL_connect(ssl) : q_SSL_accept(ssl);
1133 const QList<QPair<int, int> > &lastErrors = _q_sslErrorList()->errors;
1134 for (int i = 0; i < lastErrors.size(); ++i) {
1135 const QPair<int, int> ¤tError = lastErrors.at(i);
1136 // Initialize the peer certificate chain in order to find which certificate caused this error
1137 if (configuration.peerCertificateChain.isEmpty())
1138 configuration.peerCertificateChain = STACKOFX509_to_QSslCertificates(q_SSL_get_peer_cert_chain(ssl));
1139 emit q->peerVerifyError(_q_OpenSSL_to_QSslError(currentError.first,
1140 configuration.peerCertificateChain.value(currentError.second)));
1141 if (q->state() != QAbstractSocket::ConnectedState)
1145 errorList << lastErrors;
1146 _q_sslErrorList()->mutex.unlock();
1148 // Connection aborted during handshake phase.
1149 if (q->state() != QAbstractSocket::ConnectedState)
1152 // Check if we're encrypted or not.
1154 switch (q_SSL_get_error(ssl, result)) {
1155 case SSL_ERROR_WANT_READ:
1156 case SSL_ERROR_WANT_WRITE:
1157 // The handshake is not yet complete.
1160 q->setErrorString(QSslSocket::tr("Error during SSL handshake: %1").arg(getErrorsFromOpenSsl()));
1161 q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
1162 #ifdef QSSLSOCKET_DEBUG
1163 qDebug() << "QSslSocketBackendPrivate::startHandshake: error!" << q->errorString();
1165 emit q->error(QAbstractSocket::SslHandshakeFailedError);
1171 // Store the peer certificate and chain. For clients, the peer certificate
1172 // chain includes the peer certificate; for servers, it doesn't. Both the
1173 // peer certificate and the chain may be empty if the peer didn't present
1175 if (configuration.peerCertificateChain.isEmpty())
1176 configuration.peerCertificateChain = STACKOFX509_to_QSslCertificates(q_SSL_get_peer_cert_chain(ssl));
1177 X509 *x509 = q_SSL_get_peer_certificate(ssl);
1178 configuration.peerCertificate = QSslCertificatePrivate::QSslCertificate_from_X509(x509);
1181 // Start translating errors.
1182 QList<QSslError> errors;
1184 // check the whole chain for blacklisting (including root, as we check for subjectInfo and issuer)
1185 foreach (const QSslCertificate &cert, configuration.peerCertificateChain) {
1186 if (QSslCertificatePrivate::isBlacklisted(cert)) {
1187 QSslError error(QSslError::CertificateBlacklisted, cert);
1189 emit q->peerVerifyError(error);
1190 if (q->state() != QAbstractSocket::ConnectedState)
1195 bool doVerifyPeer = configuration.peerVerifyMode == QSslSocket::VerifyPeer
1196 || (configuration.peerVerifyMode == QSslSocket::AutoVerifyPeer
1197 && mode == QSslSocket::SslClientMode);
1199 // Check the peer certificate itself. First try the subject's common name
1200 // (CN) as a wildcard, then try all alternate subject name DNS entries the
1202 if (!configuration.peerCertificate.isNull()) {
1203 // but only if we're a client connecting to a server
1204 // if we're the server, don't check CN
1205 if (mode == QSslSocket::SslClientMode) {
1206 QString peerName = (verificationPeerName.isEmpty () ? q->peerName() : verificationPeerName);
1208 if (!isMatchingHostname(configuration.peerCertificate, peerName)) {
1209 // No matches in common names or alternate names.
1210 QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate);
1212 emit q->peerVerifyError(error);
1213 if (q->state() != QAbstractSocket::ConnectedState)
1218 // No peer certificate presented. Report as error if the socket
1221 QSslError error(QSslError::NoPeerCertificate);
1223 emit q->peerVerifyError(error);
1224 if (q->state() != QAbstractSocket::ConnectedState)
1229 // Translate errors from the error list into QSslErrors.
1230 for (int i = 0; i < errorList.size(); ++i) {
1231 const QPair<int, int> &errorAndDepth = errorList.at(i);
1232 int err = errorAndDepth.first;
1233 int depth = errorAndDepth.second;
1234 errors << _q_OpenSSL_to_QSslError(err, configuration.peerCertificateChain.value(depth));
1237 if (!errors.isEmpty()) {
1241 //Skip this if not using system CAs, or if the SSL errors are configured in advance to be ignorable
1243 && s_loadRootCertsOnDemand
1244 && allowRootCertOnDemandLoading
1245 && !verifyErrorsHaveBeenIgnored()) {
1246 //Windows desktop versions starting from vista ship with minimal set of roots
1247 //and download on demand from the windows update server CA roots that are
1249 //However, this is only transparent if using WinINET - we have to trigger it
1251 QSslCertificate certToFetch;
1252 bool fetchCertificate = true;
1253 for (int i=0; i< sslErrors.count(); i++) {
1254 switch (sslErrors.at(i).error()) {
1255 case QSslError::UnableToGetLocalIssuerCertificate:
1256 certToFetch = sslErrors.at(i).certificate();
1258 case QSslError::SelfSignedCertificate:
1259 case QSslError::CertificateBlacklisted:
1260 //With these errors, we know it will be untrusted so save time by not asking windows
1261 fetchCertificate = false;
1264 #ifdef QSSLSOCKET_DEBUG
1265 qDebug() << sslErrors.at(i).errorString();
1270 if (fetchCertificate && !certToFetch.isNull()) {
1271 fetchCaRootForCert(certToFetch);
1277 if (!checkSslErrors())
1283 continueHandshake();
1287 bool QSslSocketBackendPrivate::checkSslErrors()
1290 if (sslErrors.isEmpty())
1293 emit q->sslErrors(sslErrors);
1295 bool doVerifyPeer = configuration.peerVerifyMode == QSslSocket::VerifyPeer
1296 || (configuration.peerVerifyMode == QSslSocket::AutoVerifyPeer
1297 && mode == QSslSocket::SslClientMode);
1298 bool doEmitSslError = !verifyErrorsHaveBeenIgnored();
1299 // check whether we need to emit an SSL handshake error
1300 if (doVerifyPeer && doEmitSslError) {
1301 if (q->pauseMode() & QAbstractSocket::PauseOnNotify) {
1302 pauseSocketNotifiers(q);
1305 q->setErrorString(sslErrors.first().errorString());
1306 q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
1307 emit q->error(QAbstractSocket::SslHandshakeFailedError);
1308 plainSocket->disconnectFromHost();
1317 void QSslSocketBackendPrivate::fetchCaRootForCert(const QSslCertificate &cert)
1320 //The root certificate is downloaded from windows update, which blocks for 15 seconds in the worst case
1321 //so the request is done in a worker thread.
1322 QWindowsCaRootFetcher *fetcher = new QWindowsCaRootFetcher(cert, mode);
1323 QObject::connect(fetcher, SIGNAL(finished(QSslCertificate,QSslCertificate)), q, SLOT(_q_caRootLoaded(QSslCertificate,QSslCertificate)), Qt::QueuedConnection);
1324 QMetaObject::invokeMethod(fetcher, "start", Qt::QueuedConnection);
1325 pauseSocketNotifiers(q);
1329 //This is the callback from QWindowsCaRootFetcher, trustedRoot will be invalid (default constructed) if it failed.
1330 void QSslSocketBackendPrivate::_q_caRootLoaded(QSslCertificate cert, QSslCertificate trustedRoot)
1333 if (trustedRoot.isValid()) {
1334 if (s_loadRootCertsOnDemand) {
1335 //Add the new root cert to default cert list for use by future sockets
1336 QSslSocket::addDefaultCaCertificate(trustedRoot);
1338 //Add the new root cert to this socket for future connections
1339 q->addCaCertificate(trustedRoot);
1340 //Remove the broken chain ssl errors (as chain is verified by windows)
1341 for (int i=sslErrors.count() - 1; i >= 0; --i) {
1342 if (sslErrors.at(i).certificate() == cert) {
1343 switch (sslErrors.at(i).error()) {
1344 case QSslError::UnableToGetLocalIssuerCertificate:
1345 case QSslError::CertificateUntrusted:
1346 case QSslError::UnableToVerifyFirstCertificate:
1347 // error can be ignored if OS says the chain is trusted
1348 sslErrors.removeAt(i);
1351 // error cannot be ignored
1357 // Continue with remaining errors
1359 plainSocket->resume();
1361 if (checkSslErrors())
1362 continueHandshake();
1365 class QWindowsCaRootFetcherThread : public QThread
1368 QWindowsCaRootFetcherThread()
1370 qRegisterMetaType<QSslCertificate>();
1371 setObjectName(QStringLiteral("QWindowsCaRootFetcher"));
1374 ~QWindowsCaRootFetcherThread()
1377 wait(15500); // worst case, a running request can block for 15 seconds
1381 Q_GLOBAL_STATIC(QWindowsCaRootFetcherThread, windowsCaRootFetcherThread);
1383 QWindowsCaRootFetcher::QWindowsCaRootFetcher(const QSslCertificate &certificate, QSslSocket::SslMode sslMode)
1384 : cert(certificate), mode(sslMode)
1386 moveToThread(windowsCaRootFetcherThread());
1389 QWindowsCaRootFetcher::~QWindowsCaRootFetcher()
1393 void QWindowsCaRootFetcher::start()
1395 QByteArray der = cert.toDer();
1396 PCCERT_CONTEXT wincert = CertCreateCertificateContext(X509_ASN_ENCODING, (const BYTE *)der.constData(), der.length());
1398 #ifdef QSSLSOCKET_DEBUG
1399 qDebug("QWindowsCaRootFetcher failed to convert certificate to windows form");
1401 emit finished(cert, QSslCertificate());
1406 CERT_CHAIN_PARA parameters;
1407 memset(¶meters, 0, sizeof(parameters));
1408 parameters.cbSize = sizeof(parameters);
1409 // set key usage constraint
1410 parameters.RequestedUsage.dwType = USAGE_MATCH_TYPE_AND;
1411 parameters.RequestedUsage.Usage.cUsageIdentifier = 1;
1412 LPSTR oid = (LPSTR)(mode == QSslSocket::SslClientMode ? szOID_PKIX_KP_SERVER_AUTH : szOID_PKIX_KP_CLIENT_AUTH);
1413 parameters.RequestedUsage.Usage.rgpszUsageIdentifier = &oid;
1415 #ifdef QSSLSOCKET_DEBUG
1416 QElapsedTimer stopwatch;
1419 PCCERT_CHAIN_CONTEXT chain;
1420 BOOL result = CertGetCertificateChain(
1423 0, //current date/time
1426 0, //default dwFlags
1429 #ifdef QSSLSOCKET_DEBUG
1430 qDebug() << "QWindowsCaRootFetcher" << stopwatch.elapsed() << "ms to get chain";
1433 QSslCertificate trustedRoot;
1435 #ifdef QSSLSOCKET_DEBUG
1436 qDebug() << "QWindowsCaRootFetcher - examining windows chains";
1437 if (chain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR)
1438 qDebug() << " - TRUSTED";
1440 qDebug() << " - NOT TRUSTED" << chain->TrustStatus.dwErrorStatus;
1441 if (chain->TrustStatus.dwInfoStatus & CERT_TRUST_IS_SELF_SIGNED)
1442 qDebug() << " - SELF SIGNED";
1443 qDebug() << "QSslSocketBackendPrivate::fetchCaRootForCert - dumping simple chains";
1444 for (unsigned int i = 0; i < chain->cChain; i++) {
1445 if (chain->rgpChain[i]->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR)
1446 qDebug() << " - TRUSTED SIMPLE CHAIN" << i;
1448 qDebug() << " - UNTRUSTED SIMPLE CHAIN" << i << "reason:" << chain->rgpChain[i]->TrustStatus.dwErrorStatus;
1449 for (unsigned int j = 0; j < chain->rgpChain[i]->cElement; j++) {
1450 QSslCertificate foundCert(QByteArray((const char *)chain->rgpChain[i]->rgpElement[j]->pCertContext->pbCertEncoded
1451 , chain->rgpChain[i]->rgpElement[j]->pCertContext->cbCertEncoded), QSsl::Der);
1452 qDebug() << " - " << foundCert;
1455 qDebug() << " - and" << chain->cLowerQualityChainContext << "low quality chains"; //expect 0, we haven't asked for them
1458 //based on http://msdn.microsoft.com/en-us/library/windows/desktop/aa377182%28v=vs.85%29.aspx
1459 //about the final chain rgpChain[cChain-1] which must begin with a trusted root to be valid
1460 if (chain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR
1461 && chain->cChain > 0) {
1462 const PCERT_SIMPLE_CHAIN finalChain = chain->rgpChain[chain->cChain - 1];
1463 // http://msdn.microsoft.com/en-us/library/windows/desktop/aa377544%28v=vs.85%29.aspx
1464 // rgpElement[0] is the end certificate chain element. rgpElement[cElement-1] is the self-signed "root" certificate element.
1465 if (finalChain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR
1466 && finalChain->cElement > 0) {
1467 trustedRoot = QSslCertificate(QByteArray((const char *)finalChain->rgpElement[finalChain->cElement - 1]->pCertContext->pbCertEncoded
1468 , finalChain->rgpElement[finalChain->cElement - 1]->pCertContext->cbCertEncoded), QSsl::Der);
1471 CertFreeCertificateChain(chain);
1473 CertFreeCertificateContext(wincert);
1475 emit finished(cert, trustedRoot);
1480 void QSslSocketBackendPrivate::disconnectFromHost()
1483 q_SSL_shutdown(ssl);
1486 plainSocket->disconnectFromHost();
1489 void QSslSocketBackendPrivate::disconnected()
1491 if (plainSocket->bytesAvailable() <= 0)
1492 destroySslContext();
1493 //if there is still buffered data in the plain socket, don't destroy the ssl context yet.
1494 //it will be destroyed when the socket is deleted.
1497 QSslCipher QSslSocketBackendPrivate::sessionCipher() const
1500 return QSslCipher();
1501 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
1502 // FIXME This is fairly evil, but needed to keep source level compatibility
1503 // with the OpenSSL 0.9.x implementation at maximum -- some other functions
1504 // don't take a const SSL_CIPHER* when they should
1505 SSL_CIPHER *sessionCipher = const_cast<SSL_CIPHER *>(q_SSL_get_current_cipher(ssl));
1507 SSL_CIPHER *sessionCipher = q_SSL_get_current_cipher(ssl);
1509 return sessionCipher ? QSslCipher_from_SSL_CIPHER(sessionCipher) : QSslCipher();
1512 void QSslSocketBackendPrivate::continueHandshake()
1515 // if we have a max read buffer size, reset the plain socket's to match
1516 if (readBufferMaxSize)
1517 plainSocket->setReadBufferSize(readBufferMaxSize);
1519 connectionEncrypted = true;
1520 emit q->encrypted();
1521 if (autoStartHandshake && pendingClose) {
1522 pendingClose = false;
1523 q->disconnectFromHost();
1527 QList<QSslCertificate> QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates(STACK_OF(X509) *x509)
1529 ensureInitialized();
1530 QList<QSslCertificate> certificates;
1531 for (int i = 0; i < q_sk_X509_num(x509); ++i) {
1532 if (X509 *entry = q_sk_X509_value(x509, i))
1533 certificates << QSslCertificatePrivate::QSslCertificate_from_X509(entry);
1535 return certificates;
1538 QString QSslSocketBackendPrivate::getErrorsFromOpenSsl()
1540 QString errorString;
1541 unsigned long errNum;
1542 while((errNum = q_ERR_get_error())) {
1543 if (! errorString.isEmpty())
1544 errorString.append(QLatin1String(", "));
1545 const char *error = q_ERR_error_string(errNum, NULL);
1546 errorString.append(QString::fromAscii(error)); // error is ascii according to man ERR_error_string
1551 bool QSslSocketBackendPrivate::isMatchingHostname(const QSslCertificate &cert, const QString &peerName)
1553 QStringList commonNameList = cert.subjectInfo(QSslCertificate::CommonName);
1555 foreach (const QString &commonName, commonNameList) {
1556 if (isMatchingHostname(commonName.toLower(), peerName.toLower())) {
1561 foreach (const QString &altName, cert.subjectAlternativeNames().values(QSsl::DnsEntry)) {
1562 if (isMatchingHostname(altName.toLower(), peerName.toLower())) {
1570 bool QSslSocketBackendPrivate::isMatchingHostname(const QString &cn, const QString &hostname)
1572 int wildcard = cn.indexOf(QLatin1Char('*'));
1574 // Check this is a wildcard cert, if not then just compare the strings
1576 return cn == hostname;
1578 int firstCnDot = cn.indexOf(QLatin1Char('.'));
1579 int secondCnDot = cn.indexOf(QLatin1Char('.'), firstCnDot+1);
1581 // Check at least 3 components
1582 if ((-1 == secondCnDot) || (secondCnDot+1 >= cn.length()))
1585 // Check * is last character of 1st component (ie. there's a following .)
1586 if (wildcard+1 != firstCnDot)
1589 // Check only one star
1590 if (cn.lastIndexOf(QLatin1Char('*')) != wildcard)
1593 // Check characters preceding * (if any) match
1594 if (wildcard && (hostname.leftRef(wildcard) != cn.leftRef(wildcard)))
1597 // Check characters following first . match
1598 if (hostname.midRef(hostname.indexOf(QLatin1Char('.'))) != cn.midRef(firstCnDot))
1601 // Check if the hostname is an IP address, if so then wildcards are not allowed
1602 QHostAddress addr(hostname);
1606 // Ok, I guess this was a wildcard CN and the hostname matches.
1610 QList<QSslError> QSslSocketBackendPrivate::verify(QList<QSslCertificate> certificateChain, const QString &hostName)
1612 QList<QSslError> errors;
1613 if (certificateChain.count() <= 0) {
1614 errors << QSslError(QSslError::UnspecifiedError);
1618 // Setup the store with the default CA certificates
1619 X509_STORE *certStore = q_X509_STORE_new();
1621 qWarning() << "Unable to create certificate store";
1622 errors << QSslError(QSslError::UnspecifiedError);
1626 if (s_loadRootCertsOnDemand) {
1627 setDefaultCaCertificates(defaultCaCertificates() + systemCaCertificates());
1630 QList<QSslCertificate> expiredCerts;
1632 foreach (const QSslCertificate &caCertificate, QSslSocket::defaultCaCertificates()) {
1633 // add expired certs later, so that the
1634 // valid ones are used before the expired ones
1635 if (caCertificate.expiryDate() < QDateTime::currentDateTime()) {
1636 expiredCerts.append(caCertificate);
1638 q_X509_STORE_add_cert(certStore, reinterpret_cast<X509 *>(caCertificate.handle()));
1642 bool addExpiredCerts = true;
1643 #if defined(Q_OS_MAC) && (MAC_OS_X_VERSION_MAX_ALLOWED == MAC_OS_X_VERSION_10_5)
1644 //On Leopard SSL does not work if we add the expired certificates.
1645 if (QSysInfo::MacintoshVersion == QSysInfo::MV_10_5)
1646 addExpiredCerts = false;
1648 // now add the expired certs
1649 if (addExpiredCerts) {
1650 foreach (const QSslCertificate &caCertificate, expiredCerts) {
1651 q_X509_STORE_add_cert(certStore, reinterpret_cast<X509 *>(caCertificate.handle()));
1655 QMutexLocker sslErrorListMutexLocker(&_q_sslErrorList()->mutex);
1657 // Register a custom callback to get all verification errors.
1658 X509_STORE_set_verify_cb_func(certStore, q_X509Callback);
1660 // Build the chain of intermediate certificates
1661 STACK_OF(X509) *intermediates = 0;
1662 if (certificateChain.length() > 1) {
1663 intermediates = (STACK_OF(X509) *) q_sk_new_null();
1665 if (!intermediates) {
1666 q_X509_STORE_free(certStore);
1667 errors << QSslError(QSslError::UnspecifiedError);
1672 foreach (const QSslCertificate &cert, certificateChain) {
1677 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
1678 q_sk_push( (_STACK *)intermediates, reinterpret_cast<X509 *>(cert.handle()));
1680 q_sk_push( (STACK *)intermediates, reinterpret_cast<X509 *>(cert.handle()));
1685 X509_STORE_CTX *storeContext = q_X509_STORE_CTX_new();
1686 if (!storeContext) {
1687 q_X509_STORE_free(certStore);
1688 errors << QSslError(QSslError::UnspecifiedError);
1692 if (!q_X509_STORE_CTX_init(storeContext, certStore, reinterpret_cast<X509 *>(certificateChain[0].handle()), intermediates)) {
1693 q_X509_STORE_CTX_free(storeContext);
1694 q_X509_STORE_free(certStore);
1695 errors << QSslError(QSslError::UnspecifiedError);
1699 // Now we can actually perform the verification of the chain we have built.
1700 // We ignore the result of this function since we process errors via the
1702 (void) q_X509_verify_cert(storeContext);
1704 q_X509_STORE_CTX_free(storeContext);
1705 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
1706 q_sk_free( (_STACK *) intermediates);
1708 q_sk_free( (STACK *) intermediates);
1711 // Now process the errors
1712 const QList<QPair<int, int> > errorList = _q_sslErrorList()->errors;
1713 _q_sslErrorList()->errors.clear();
1715 sslErrorListMutexLocker.unlock();
1717 // Translate the errors
1718 if (QSslCertificatePrivate::isBlacklisted(certificateChain[0])) {
1719 QSslError error(QSslError::CertificateBlacklisted, certificateChain[0]);
1723 // Check the certificate name against the hostname if one was specified
1724 if ((!hostName.isEmpty()) && (!isMatchingHostname(certificateChain[0], hostName))) {
1725 // No matches in common names or alternate names.
1726 QSslError error(QSslError::HostNameMismatch, certificateChain[0]);
1730 // Translate errors from the error list into QSslErrors.
1731 for (int i = 0; i < errorList.size(); ++i) {
1732 const QPair<int, int> &errorAndDepth = errorList.at(i);
1733 int err = errorAndDepth.first;
1734 int depth = errorAndDepth.second;
1735 errors << _q_OpenSSL_to_QSslError(err, certificateChain.value(depth));
1738 q_X509_STORE_free(certStore);