1
/****************************************************************************
3
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4
** All rights reserved.
5
** Contact: Nokia Corporation (qt-info@nokia.com)
7
** This file is part of the QtNetwork module of the Qt Toolkit.
9
** $QT_BEGIN_LICENSE:LGPL$
10
** GNU Lesser General Public License Usage
11
** This file may be used under the terms of the GNU Lesser General Public
12
** License version 2.1 as published by the Free Software Foundation and
13
** appearing in the file LICENSE.LGPL included in the packaging of this
14
** file. Please review the following information to ensure the GNU Lesser
15
** General Public License version 2.1 requirements will be met:
16
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18
** In addition, as a special exception, Nokia gives you certain additional
19
** rights. These rights are described in the Nokia Qt LGPL Exception
20
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22
** GNU General Public License Usage
23
** Alternatively, this file may be used under the terms of the GNU General
24
** Public License version 3.0 as published by the Free Software Foundation
25
** and appearing in the file LICENSE.GPL included in the packaging of this
26
** file. Please review the following information to ensure the GNU General
27
** Public License version 3.0 requirements will be met:
28
** http://www.gnu.org/copyleft/gpl.html.
31
** Alternatively, this file may be used in accordance with the terms and
32
** 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
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;
74
#elif defined(Q_OS_SYMBIAN)
78
#include <QtCore/private/qcore_symbian_p.h>
81
bool QSslSocketPrivate::s_libraryLoaded = false;
82
bool QSslSocketPrivate::s_loadedCiphersAndCerts = 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()
181
QSslCipher QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(SSL_CIPHER *cipher)
186
QString descriptionOneLine = QString::fromLatin1(q_SSL_CIPHER_description(cipher, buf, sizeof(buf)));
188
QStringList descriptionList = descriptionOneLine.split(QLatin1String(" "), QString::SkipEmptyParts);
189
if (descriptionList.size() > 5) {
191
ciph.d->isNull = false;
192
ciph.d->name = descriptionList.at(0);
194
QString protoString = descriptionList.at(1);
195
ciph.d->protocolString = protoString;
196
ciph.d->protocol = QSsl::UnknownProtocol;
197
if (protoString == QLatin1String("SSLv3"))
198
ciph.d->protocol = QSsl::SslV3;
199
else if (protoString == QLatin1String("SSLv2"))
200
ciph.d->protocol = QSsl::SslV2;
201
else if (protoString == QLatin1String("TLSv1"))
202
ciph.d->protocol = QSsl::TlsV1;
204
if (descriptionList.at(2).startsWith(QLatin1String("Kx=")))
205
ciph.d->keyExchangeMethod = descriptionList.at(2).mid(3);
206
if (descriptionList.at(3).startsWith(QLatin1String("Au=")))
207
ciph.d->authenticationMethod = descriptionList.at(3).mid(3);
208
if (descriptionList.at(4).startsWith(QLatin1String("Enc=")))
209
ciph.d->encryptionMethod = descriptionList.at(4).mid(4);
210
ciph.d->exportable = (descriptionList.size() > 6 && descriptionList.at(6) == QLatin1String("export"));
212
ciph.d->bits = cipher->strength_bits;
213
ciph.d->supportedBits = cipher->alg_bits;
219
// ### This list is shared between all threads, and protected by a
220
// mutex. Investigate using thread local storage instead.
224
QList<QPair<int, int> > errors;
226
Q_GLOBAL_STATIC(QSslErrorList, _q_sslErrorList)
227
static int q_X509Callback(int ok, X509_STORE_CTX *ctx)
230
// Store the error and at which depth the error was detected.
231
_q_sslErrorList()->errors << qMakePair<int, int>(ctx->error, ctx->error_depth);
233
// Always return OK to allow verification to continue. We're handle the
234
// errors gracefully after collecting all errors, after verification has
239
bool QSslSocketBackendPrivate::initSslContext()
243
// Create and initialize SSL context. Accept SSLv2, SSLv3 and TLSv1.
244
bool client = (mode == QSslSocket::SslClientMode);
246
bool reinitialized = false;
248
switch (configuration.protocol) {
250
ctx = q_SSL_CTX_new(client ? q_SSLv2_client_method() : q_SSLv2_server_method());
253
ctx = q_SSL_CTX_new(client ? q_SSLv3_client_method() : q_SSLv3_server_method());
255
case QSsl::AnyProtocol:
257
ctx = q_SSL_CTX_new(client ? q_SSLv23_client_method() : q_SSLv23_server_method());
260
ctx = q_SSL_CTX_new(client ? q_TLSv1_client_method() : q_TLSv1_server_method());
264
// After stopping Flash 10 the SSL library looses its ciphers. Try re-adding them
265
// by re-initializing the library.
266
if (!reinitialized) {
267
reinitialized = true;
268
if (q_SSL_library_init() == 1)
272
// ### Bad error code
273
q->setErrorString(QSslSocket::tr("Error creating SSL context (%1)").arg(getErrorsFromOpenSsl()));
274
q->setSocketError(QAbstractSocket::UnknownSocketError);
275
emit q->error(QAbstractSocket::UnknownSocketError);
279
// Enable all bug workarounds.
280
q_SSL_CTX_set_options(ctx, SSL_OP_ALL);
282
// Initialize ciphers
283
QByteArray cipherString;
285
QList<QSslCipher> ciphers = configuration.ciphers;
286
if (ciphers.isEmpty())
287
ciphers = defaultCiphers();
288
foreach (const QSslCipher &cipher, ciphers) {
292
cipherString.append(':');
293
cipherString.append(cipher.name().toLatin1());
296
if (!q_SSL_CTX_set_cipher_list(ctx, cipherString.data())) {
297
// ### Bad error code
298
q->setErrorString(QSslSocket::tr("Invalid or empty cipher list (%1)").arg(getErrorsFromOpenSsl()));
299
q->setSocketError(QAbstractSocket::UnknownSocketError);
300
emit q->error(QAbstractSocket::UnknownSocketError);
304
// Add all our CAs to this store.
305
QList<QSslCertificate> expiredCerts;
306
foreach (const QSslCertificate &caCertificate, q->caCertificates()) {
307
// add expired certs later, so that the
308
// valid ones are used before the expired ones
309
if (! caCertificate.isValid()) {
310
expiredCerts.append(caCertificate);
312
q_X509_STORE_add_cert(ctx->cert_store, (X509 *)caCertificate.handle());
316
bool addExpiredCerts = true;
317
#if defined(Q_OS_MAC) && (MAC_OS_X_VERSION_MAX_ALLOWED == MAC_OS_X_VERSION_10_5)
318
//On Leopard SSL does not work if we add the expired certificates.
319
if (QSysInfo::MacintoshVersion == QSysInfo::MV_10_5)
320
addExpiredCerts = false;
322
// now add the expired certs
323
if (addExpiredCerts) {
324
foreach (const QSslCertificate &caCertificate, expiredCerts) {
325
q_X509_STORE_add_cert(ctx->cert_store, (X509 *)caCertificate.handle());
329
// Register a custom callback to get all verification errors.
330
X509_STORE_set_verify_cb_func(ctx->cert_store, q_X509Callback);
332
if (!configuration.localCertificate.isNull()) {
333
// Require a private key as well.
334
if (configuration.privateKey.isNull()) {
335
q->setErrorString(QSslSocket::tr("Cannot provide a certificate with no key, %1").arg(getErrorsFromOpenSsl()));
336
emit q->error(QAbstractSocket::UnknownSocketError);
341
if (!q_SSL_CTX_use_certificate(ctx, (X509 *)configuration.localCertificate.handle())) {
342
q->setErrorString(QSslSocket::tr("Error loading local certificate, %1").arg(getErrorsFromOpenSsl()));
343
emit q->error(QAbstractSocket::UnknownSocketError);
348
pkey = q_EVP_PKEY_new();
349
// before we were using EVP_PKEY_assign_R* functions and did not use EVP_PKEY_free.
350
// this lead to a memory leak. Now we use the *_set1_* functions which do not
351
// take ownership of the RSA/DSA key instance because the QSslKey already has ownership.
352
if (configuration.privateKey.algorithm() == QSsl::Rsa)
353
q_EVP_PKEY_set1_RSA(pkey, (RSA *)configuration.privateKey.handle());
355
q_EVP_PKEY_set1_DSA(pkey, (DSA *)configuration.privateKey.handle());
356
if (!q_SSL_CTX_use_PrivateKey(ctx, pkey)) {
357
q->setErrorString(QSslSocket::tr("Error loading private key, %1").arg(getErrorsFromOpenSsl()));
358
emit q->error(QAbstractSocket::UnknownSocketError);
362
// Check if the certificate matches the private key.
363
if (!q_SSL_CTX_check_private_key(ctx)) {
364
q->setErrorString(QSslSocket::tr("Private key does not certify public key, %1").arg(getErrorsFromOpenSsl()));
365
emit q->error(QAbstractSocket::UnknownSocketError);
370
// Initialize peer verification.
371
if (configuration.peerVerifyMode == QSslSocket::VerifyNone) {
372
q_SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
374
q_SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, q_X509Callback);
377
// Set verification depth.
378
if (configuration.peerVerifyDepth != 0)
379
q_SSL_CTX_set_verify_depth(ctx, configuration.peerVerifyDepth);
381
// Create and initialize SSL session
382
if (!(ssl = q_SSL_new(ctx))) {
383
// ### Bad error code
384
q->setErrorString(QSslSocket::tr("Error creating SSL session, %1").arg(getErrorsFromOpenSsl()));
385
q->setSocketError(QAbstractSocket::UnknownSocketError);
386
emit q->error(QAbstractSocket::UnknownSocketError);
390
// Clear the session.
394
// Initialize memory BIOs for encryption and decryption.
395
readBio = q_BIO_new(q_BIO_s_mem());
396
writeBio = q_BIO_new(q_BIO_s_mem());
397
if (!readBio || !writeBio) {
398
// ### Bad error code
399
q->setErrorString(QSslSocket::tr("Error creating SSL session: %1").arg(getErrorsFromOpenSsl()));
400
q->setSocketError(QAbstractSocket::UnknownSocketError);
401
emit q->error(QAbstractSocket::UnknownSocketError);
406
q_SSL_set_bio(ssl, readBio, writeBio);
408
if (mode == QSslSocket::SslClientMode)
409
q_SSL_set_connect_state(ssl);
411
q_SSL_set_accept_state(ssl);
419
void QSslSocketPrivate::deinitialize()
421
q_CRYPTO_set_id_callback(0);
422
q_CRYPTO_set_locking_callback(0);
428
Does the minimum amount of initialization to determine whether SSL
432
bool QSslSocketPrivate::supportsSsl()
434
return ensureLibraryLoaded();
437
bool QSslSocketPrivate::ensureLibraryLoaded()
439
if (!q_resolveOpenSslSymbols())
442
// Check if the library itself needs to be initialized.
443
QMutexLocker locker(openssl_locks()->initLock());
444
if (!s_libraryLoaded) {
445
s_libraryLoaded = true;
447
// Initialize OpenSSL.
448
q_CRYPTO_set_id_callback(id_function);
449
q_CRYPTO_set_locking_callback(locking_function);
450
if (q_SSL_library_init() != 1)
452
q_SSL_load_error_strings();
453
q_OpenSSL_add_all_algorithms();
455
// Initialize OpenSSL's random seed.
456
if (!q_RAND_status()) {
465
if (attempts < 500) {
467
struct timespec ts = {0, 33333333};
472
randomish.msec = attempts;
474
randomish.stack = (void *)&randomish;
475
randomish.msec = QTime::currentTime().msec();
476
randomish.sec = QTime::currentTime().second();
477
q_RAND_seed((const char *)&randomish, sizeof(randomish));
478
} while (!q_RAND_status() && --attempts);
486
void QSslSocketPrivate::ensureCiphersAndCertsLoaded()
488
QMutexLocker locker(openssl_locks()->initLock());
489
if (s_loadedCiphersAndCerts)
491
s_loadedCiphersAndCerts = true;
493
resetDefaultCiphers();
495
//load symbols needed to receive certificates from system store
496
#if defined(Q_OS_MAC)
497
QLibrary securityLib("/System/Library/Frameworks/Security.framework/Versions/Current/Security");
498
if (securityLib.load()) {
499
ptrSecCertificateGetData = (PtrSecCertificateGetData) securityLib.resolve("SecCertificateGetData");
500
if (!ptrSecCertificateGetData)
501
qWarning("could not resolve symbols in security library"); // should never happen
503
ptrSecTrustSettingsCopyCertificates = (PtrSecTrustSettingsCopyCertificates) securityLib.resolve("SecTrustSettingsCopyCertificates");
504
if (!ptrSecTrustSettingsCopyCertificates) { // method was introduced in Leopard, use legacy method if it's not there
505
ptrSecTrustCopyAnchorCertificates = (PtrSecTrustCopyAnchorCertificates) securityLib.resolve("SecTrustCopyAnchorCertificates");
506
if (!ptrSecTrustCopyAnchorCertificates)
507
qWarning("could not resolve symbols in security library"); // should never happen
510
qWarning("could not load security library");
512
#elif defined(Q_OS_WIN)
513
HINSTANCE hLib = LoadLibraryW(L"Crypt32");
515
#if defined(Q_OS_WINCE)
516
ptrCertOpenSystemStoreW = (PtrCertOpenSystemStoreW)GetProcAddress(hLib, L"CertOpenStore");
517
ptrCertFindCertificateInStore = (PtrCertFindCertificateInStore)GetProcAddress(hLib, L"CertFindCertificateInStore");
518
ptrCertCloseStore = (PtrCertCloseStore)GetProcAddress(hLib, L"CertCloseStore");
520
ptrCertOpenSystemStoreW = (PtrCertOpenSystemStoreW)GetProcAddress(hLib, "CertOpenSystemStoreW");
521
ptrCertFindCertificateInStore = (PtrCertFindCertificateInStore)GetProcAddress(hLib, "CertFindCertificateInStore");
522
ptrCertCloseStore = (PtrCertCloseStore)GetProcAddress(hLib, "CertCloseStore");
524
if (!ptrCertOpenSystemStoreW || !ptrCertFindCertificateInStore || !ptrCertCloseStore)
525
qWarning("could not resolve symbols in crypt32 library"); // should never happen
527
qWarning("could not load crypt32 library"); // should never happen
530
setDefaultCaCertificates(systemCaCertificates());
536
Declared static in QSslSocketPrivate, makes sure the SSL libraries have
540
void QSslSocketPrivate::ensureInitialized()
545
ensureCiphersAndCertsLoaded();
551
Declared static in QSslSocketPrivate, backend-dependent loading of
552
application-wide global ciphers.
554
void QSslSocketPrivate::resetDefaultCiphers()
556
SSL_CTX *myCtx = q_SSL_CTX_new(q_SSLv23_client_method());
557
SSL *mySsl = q_SSL_new(myCtx);
559
QList<QSslCipher> ciphers;
561
STACK_OF(SSL_CIPHER) *supportedCiphers = q_SSL_get_ciphers(mySsl);
562
for (int i = 0; i < q_sk_SSL_CIPHER_num(supportedCiphers); ++i) {
563
if (SSL_CIPHER *cipher = q_sk_SSL_CIPHER_value(supportedCiphers, i)) {
565
QSslCipher ciph = QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(cipher);
566
if (!ciph.isNull()) {
567
if (!ciph.name().toLower().startsWith(QLatin1String("adh")))
574
q_SSL_CTX_free(myCtx);
577
setDefaultSupportedCiphers(ciphers);
578
setDefaultCiphers(ciphers);
581
#if defined(Q_OS_SYMBIAN)
583
CSymbianCertificateRetriever::CSymbianCertificateRetriever() : CActive(CActive::EPriorityStandard),
584
iCertificatePtr(0,0,0), iSequenceError(KErrNone)
588
CSymbianCertificateRetriever::~CSymbianCertificateRetriever()
593
CSymbianCertificateRetriever* CSymbianCertificateRetriever::NewL()
595
CSymbianCertificateRetriever* self = new (ELeave) CSymbianCertificateRetriever();
596
CleanupStack::PushL(self);
602
int CSymbianCertificateRetriever::GetCertificates(QList<QByteArray> &certificates)
604
iCertificates = &certificates;
606
TRequestStatus status;
607
iThread.Logon(status);
609
User::WaitForRequest(status);
610
if (iThread.ExitType() == EExitKill)
613
return status.Int(); // Logon() completes with the thread's exit value
616
void CSymbianCertificateRetriever::doThreadEntryL()
618
CActiveScheduler* activeScheduler = new (ELeave) CActiveScheduler;
619
CleanupStack::PushL(activeScheduler);
620
CActiveScheduler::Install(activeScheduler);
622
CActiveScheduler::Add(this);
624
// These aren't deleted in the destructor so leaving the to CS is ok
625
iCertStore = CUnifiedCertStore::NewLC(qt_s60GetRFs(), EFalse);
626
iCertFilter = CCertAttributeFilter::NewLC();
628
// only interested in CA certs
629
iCertFilter->SetOwnerType(ECACertificate);
630
// only interested in X.509 format (we don't support WAP formats)
631
iCertFilter->SetFormat(EX509Certificate);
633
// Kick off the sequence by initializing the cert store
634
iState = Initializing;
635
iCertStore->Initialize(iStatus);
638
CActiveScheduler::Start();
640
// Sequence complete, clean up
642
// These MUST be cleaned up before the installed CActiveScheduler is destroyed and can't be left to the
643
// destructor of CSymbianCertificateRetriever. Otherwise the destructor of CActiveScheduler will get
646
CleanupStack::PopAndDestroy(3); // activeScheduler, iCertStore, iCertFilter
650
TInt CSymbianCertificateRetriever::ThreadEntryPoint(TAny* aParams)
652
User::SetCritical(User::EProcessCritical);
653
CTrapCleanup* cleanupStack = CTrapCleanup::New();
655
CSymbianCertificateRetriever* self = (CSymbianCertificateRetriever*) aParams;
656
TRAPD(err, self->doThreadEntryL());
659
// doThreadEntryL() can leave only before the retrieval sequence is started
663
return self->iSequenceError; // return any error that occurred during the retrieval
666
void CSymbianCertificateRetriever::ConstructL()
670
QString name(QLatin1String("CertWorkerThread-%1"));
671
//recently closed thread names remain in use for a while until all handles have been closed
672
//including users of RUndertaker
674
err = iThread.Create(qt_QString2TPtrC(name.arg(i++)),
675
CSymbianCertificateRetriever::ThreadEntryPoint, 16384, NULL, this);
676
} while (err == KErrAlreadyExists);
677
User::LeaveIfError(err);
680
void CSymbianCertificateRetriever::DoCancel()
684
iCertStore->CancelInitialize();
687
iCertStore->CancelList();
689
case RetrievingCertificates:
690
iCertStore->CancelGetCert();
695
TInt CSymbianCertificateRetriever::RunError(TInt aError)
697
// If something goes wrong in the sequence, abort the sequence
698
iSequenceError = aError; // this gets reported to the client in the TRequestStatus
699
CActiveScheduler::Stop();
703
void CSymbianCertificateRetriever::GetCertificateL()
705
if (iCurrentCertIndex < iCertInfos.Count()) {
706
CCTCertInfo* certInfo = iCertInfos[iCurrentCertIndex++];
707
iCertificateData = QByteArray();
708
QT_TRYCATCH_LEAVING(iCertificateData.resize(certInfo->Size()));
709
iCertificatePtr.Set((TUint8*)iCertificateData.data(), 0, iCertificateData.size());
710
#ifdef QSSLSOCKET_DEBUG
711
qDebug() << "getting " << qt_TDesC2QString(certInfo->Label()) << " size=" << certInfo->Size();
712
qDebug() << "format=" << certInfo->CertificateFormat();
713
qDebug() << "ownertype=" << certInfo->CertificateOwnerType();
714
qDebug() << "type=" << hex << certInfo->Type().iUid;
716
iCertStore->Retrieve(*certInfo, iCertificatePtr, iStatus);
717
iState = RetrievingCertificates;
720
//reached end of list
721
CActiveScheduler::Stop();
725
void CSymbianCertificateRetriever::RunL()
727
#ifdef QSSLSOCKET_DEBUG
728
qDebug() << "CSymbianCertificateRetriever::RunL status " << iStatus.Int() << " count " << iCertInfos.Count() << " index " << iCurrentCertIndex;
732
User::LeaveIfError(iStatus.Int()); // initialise fail means pointless to continue
734
iCertStore->List(iCertInfos, *iCertFilter, iStatus);
739
User::LeaveIfError(iStatus.Int()); // listing fail means pointless to continue
740
iCurrentCertIndex = 0;
744
case RetrievingCertificates:
745
if (iStatus.Int() == KErrNone)
746
iCertificates->append(iCertificateData);
748
qWarning() << "CSymbianCertificateRetriever: failed to retrieve a certificate, error " << iStatus.Int();
753
#endif // defined(Q_OS_SYMBIAN)
755
QList<QSslCertificate> QSslSocketPrivate::systemCaCertificates()
758
#ifdef QSSLSOCKET_DEBUG
762
QList<QSslCertificate> systemCerts;
763
#if defined(Q_OS_MAC)
767
OSStatus SecCertificateGetData (
768
SecCertificateRef certificate,
772
if (ptrSecCertificateGetData) {
773
if (ptrSecTrustSettingsCopyCertificates)
774
status = ptrSecTrustSettingsCopyCertificates(kSecTrustSettingsDomainSystem, &cfCerts);
775
else if (ptrSecTrustCopyAnchorCertificates)
776
status = ptrSecTrustCopyAnchorCertificates(&cfCerts);
778
CFIndex size = CFArrayGetCount(cfCerts);
779
for (CFIndex i = 0; i < size; ++i) {
780
SecCertificateRef cfCert = (SecCertificateRef)CFArrayGetValueAtIndex(cfCerts, i);
782
CSSM_DATA_PTR dataPtr = &data;
783
if (ptrSecCertificateGetData(cfCert, dataPtr)) {
784
qWarning("error retrieving a CA certificate from the system store");
786
int len = data.Length;
787
char *rawData = reinterpret_cast<char *>(data.Data);
788
QByteArray rawCert(rawData, len);
789
systemCerts.append(QSslCertificate::fromData(rawCert, QSsl::Der));
795
// no detailed error handling here
796
qWarning("could not retrieve system CA certificates");
799
#elif defined(Q_OS_WIN)
800
if (ptrCertOpenSystemStoreW && ptrCertFindCertificateInStore && ptrCertCloseStore) {
801
HCERTSTORE hSystemStore;
802
#if defined(Q_OS_WINCE)
803
hSystemStore = ptrCertOpenSystemStoreW(CERT_STORE_PROV_SYSTEM_W,
806
CERT_STORE_NO_CRYPT_RELEASE_FLAG|CERT_SYSTEM_STORE_CURRENT_USER,
809
hSystemStore = ptrCertOpenSystemStoreW(0, L"ROOT");
812
PCCERT_CONTEXT pc = NULL;
814
pc = ptrCertFindCertificateInStore( hSystemStore, X509_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, pc);
817
QByteArray der((const char *)(pc->pbCertEncoded), static_cast<int>(pc->cbCertEncoded));
818
QSslCertificate cert(der, QSsl::Der);
819
systemCerts.append(cert);
821
ptrCertCloseStore(hSystemStore, 0);
824
#elif defined(Q_OS_UNIX) && !defined(Q_OS_SYMBIAN)
825
QSet<QString> certFiles;
826
QList<QByteArray> directories;
827
directories << "/etc/ssl/certs/"; // (K)ubuntu, OpenSUSE, Mandriva, MeeGo ...
828
directories << "/usr/lib/ssl/certs/"; // Gentoo, Mandrake
829
directories << "/usr/share/ssl/"; // Centos, Redhat, SuSE
830
directories << "/usr/local/ssl/"; // Normal OpenSSL Tarball
831
directories << "/var/ssl/certs/"; // AIX
832
directories << "/usr/local/ssl/certs/"; // Solaris
833
directories << "/opt/openssl/certs/"; // HP-UX
836
QStringList nameFilters;
837
nameFilters << QLatin1String("*.pem") << QLatin1String("*.crt");
838
currentDir.setNameFilters(nameFilters);
839
for (int a = 0; a < directories.count(); a++) {
840
currentDir.setPath(QLatin1String(directories.at(a)));
841
QDirIterator it(currentDir);
842
while(it.hasNext()) {
844
// use canonical path here to not load the same certificate twice if symlinked
845
certFiles.insert(it.fileInfo().canonicalFilePath());
848
QSetIterator<QString> it(certFiles);
849
while(it.hasNext()) {
850
systemCerts.append(QSslCertificate::fromPath(it.next()));
852
systemCerts.append(QSslCertificate::fromPath(QLatin1String("/etc/pki/tls/certs/ca-bundle.crt"), QSsl::Pem)); // Fedora, Mandriva
853
systemCerts.append(QSslCertificate::fromPath(QLatin1String("/usr/local/share/certs/ca-root-nss.crt"), QSsl::Pem)); // FreeBSD's ca_root_nss
855
#elif defined(Q_OS_SYMBIAN)
856
QList<QByteArray> certs;
857
QScopedPointer<CSymbianCertificateRetriever> retriever(CSymbianCertificateRetriever::NewL());
859
retriever->GetCertificates(certs);
860
foreach (const QByteArray &encodedCert, certs) {
861
QSslCertificate cert(encodedCert, QSsl::Der);
862
if (!cert.isNull()) {
863
#ifdef QSSLSOCKET_DEBUG
864
qDebug() << "imported certificate: " << cert.issuerInfo(QSslCertificate::CommonName);
866
systemCerts.append(cert);
870
#ifdef QSSLSOCKET_DEBUG
871
qDebug() << "systemCaCertificates retrieval time " << timer.elapsed() << "ms";
872
qDebug() << "imported " << systemCerts.count() << " certificates";
878
void QSslSocketBackendPrivate::startClientEncryption()
880
if (!initSslContext()) {
881
// ### report error: internal OpenSSL failure
885
// Start connecting. This will place outgoing data in the BIO, so we
886
// follow up with calling transmit().
891
void QSslSocketBackendPrivate::startServerEncryption()
893
if (!initSslContext()) {
894
// ### report error: internal OpenSSL failure
898
// Start connecting. This will place outgoing data in the BIO, so we
899
// follow up with calling transmit().
907
Transmits encrypted data between the BIOs and the socket.
909
void QSslSocketBackendPrivate::transmit()
913
// If we don't have any SSL context, don't bother transmitting.
919
transmitting = false;
921
// If the connection is secure, we can transfer data from the write
922
// buffer (in plain text) to the write BIO through SSL_write.
923
if (connectionEncrypted && !writeBuffer.isEmpty()) {
924
qint64 totalBytesWritten = 0;
925
int nextDataBlockSize;
926
while ((nextDataBlockSize = writeBuffer.nextDataBlockSize()) > 0) {
927
int writtenBytes = q_SSL_write(ssl, writeBuffer.readPointer(), nextDataBlockSize);
928
if (writtenBytes <= 0) {
929
// ### Better error handling.
930
q->setErrorString(QSslSocket::tr("Unable to write data: %1").arg(getErrorsFromOpenSsl()));
931
q->setSocketError(QAbstractSocket::UnknownSocketError);
932
emit q->error(QAbstractSocket::UnknownSocketError);
935
#ifdef QSSLSOCKET_DEBUG
936
qDebug() << "QSslSocketBackendPrivate::transmit: encrypted" << writtenBytes << "bytes";
938
writeBuffer.free(writtenBytes);
939
totalBytesWritten += writtenBytes;
941
if (writtenBytes < nextDataBlockSize) {
942
// break out of the writing loop and try again after we had read
948
if (totalBytesWritten > 0) {
949
// Don't emit bytesWritten() recursively.
950
if (!emittedBytesWritten) {
951
emittedBytesWritten = true;
952
emit q->bytesWritten(totalBytesWritten);
953
emittedBytesWritten = false;
958
// Check if we've got any data to be written to the socket.
959
QVarLengthArray<char, 4096> data;
961
while (plainSocket->isValid() && (pendingBytes = q_BIO_pending(writeBio)) > 0) {
962
// Read encrypted data from the write BIO into a buffer.
963
data.resize(pendingBytes);
964
int encryptedBytesRead = q_BIO_read(writeBio, data.data(), pendingBytes);
966
// Write encrypted data from the buffer to the socket.
967
plainSocket->write(data.constData(), encryptedBytesRead);
968
#ifdef QSSLSOCKET_DEBUG
969
qDebug() << "QSslSocketBackendPrivate::transmit: wrote" << encryptedBytesRead << "encrypted bytes to the socket";
974
// Check if we've got any data to be read from the socket.
975
if (!connectionEncrypted || !readBufferMaxSize || readBuffer.size() < readBufferMaxSize)
976
while ((pendingBytes = plainSocket->bytesAvailable()) > 0) {
977
// Read encrypted data from the socket into a buffer.
978
data.resize(pendingBytes);
979
// just peek() here because q_BIO_write could write less data than expected
980
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::UnknownSocketError);
995
emit q->error(QAbstractSocket::UnknownSocketError);
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";
1020
#ifdef QSSLSOCKET_DEBUG
1021
qDebug() << "QSslSocketBackendPrivate::transmit: encryption not done yet";
1026
// If the request is small and the remote host closes the transmission
1027
// after sending, there's a chance that startHandshake() will already
1028
// have triggered a shutdown.
1032
// We always read everything from the SSL decryption buffers, even if
1033
// we have a readBufferMaxSize. There's no point in leaving data there
1034
// just so that readBuffer.size() == readBufferMaxSize.
1037
::memset(data.data(), 0, data.size());
1039
// Don't use SSL_pending(). It's very unreliable.
1040
if ((readBytes = q_SSL_read(ssl, data.data(), data.size())) > 0) {
1041
#ifdef QSSLSOCKET_DEBUG
1042
qDebug() << "QSslSocketBackendPrivate::transmit: decrypted" << readBytes << "bytes";
1044
char *ptr = readBuffer.reserve(readBytes);
1045
::memcpy(ptr, data.data(), readBytes);
1047
if (readyReadEmittedPointer)
1048
*readyReadEmittedPointer = true;
1049
emit q->readyRead();
1050
transmitting = true;
1055
switch (q_SSL_get_error(ssl, readBytes)) {
1056
case SSL_ERROR_WANT_READ:
1057
case SSL_ERROR_WANT_WRITE:
1060
case SSL_ERROR_ZERO_RETURN:
1061
// The remote host closed the connection.
1062
#ifdef QSSLSOCKET_DEBUG
1063
qDebug() << "QSslSocketBackendPrivate::transmit: remote disconnect";
1065
plainSocket->disconnectFromHost();
1067
case SSL_ERROR_SYSCALL: // some IO error
1068
case SSL_ERROR_SSL: // error in the SSL library
1069
// we do not know exactly what the error is, nor whether we can recover from it,
1070
// so just return to prevent an endless loop in the outer "while" statement
1071
q->setErrorString(QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
1072
q->setSocketError(QAbstractSocket::UnknownSocketError);
1073
emit q->error(QAbstractSocket::UnknownSocketError);
1076
// SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT: can only happen with a
1077
// BIO_s_connect() or BIO_s_accept(), which we do not call.
1078
// SSL_ERROR_WANT_X509_LOOKUP: can only happen with a
1079
// SSL_CTX_set_client_cert_cb(), which we do not call.
1080
// So this default case should never be triggered.
1081
q->setErrorString(QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
1082
q->setSocketError(QAbstractSocket::UnknownSocketError);
1083
emit q->error(QAbstractSocket::UnknownSocketError);
1086
} while (ssl && readBytes > 0);
1087
} while (ssl && ctx && transmitting);
1090
static QSslError _q_OpenSSL_to_QSslError(int errorCode, const QSslCertificate &cert)
1093
switch (errorCode) {
1095
// X509_V_OK is also reported if the peer had no certificate.
1097
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1098
error = QSslError(QSslError::UnableToGetIssuerCertificate, cert); break;
1099
case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1100
error = QSslError(QSslError::UnableToDecryptCertificateSignature, cert); break;
1101
case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1102
error = QSslError(QSslError::UnableToDecodeIssuerPublicKey, cert); break;
1103
case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1104
error = QSslError(QSslError::CertificateSignatureFailed, cert); break;
1105
case X509_V_ERR_CERT_NOT_YET_VALID:
1106
error = QSslError(QSslError::CertificateNotYetValid, cert); break;
1107
case X509_V_ERR_CERT_HAS_EXPIRED:
1108
error = QSslError(QSslError::CertificateExpired, cert); break;
1109
case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1110
error = QSslError(QSslError::InvalidNotBeforeField, cert); break;
1111
case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1112
error = QSslError(QSslError::InvalidNotAfterField, cert); break;
1113
case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1114
error = QSslError(QSslError::SelfSignedCertificate, cert); break;
1115
case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1116
error = QSslError(QSslError::SelfSignedCertificateInChain, cert); break;
1117
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1118
error = QSslError(QSslError::UnableToGetLocalIssuerCertificate, cert); break;
1119
case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1120
error = QSslError(QSslError::UnableToVerifyFirstCertificate, cert); break;
1121
case X509_V_ERR_CERT_REVOKED:
1122
error = QSslError(QSslError::CertificateRevoked, cert); break;
1123
case X509_V_ERR_INVALID_CA:
1124
error = QSslError(QSslError::InvalidCaCertificate, cert); break;
1125
case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1126
error = QSslError(QSslError::PathLengthExceeded, cert); break;
1127
case X509_V_ERR_INVALID_PURPOSE:
1128
error = QSslError(QSslError::InvalidPurpose, cert); break;
1129
case X509_V_ERR_CERT_UNTRUSTED:
1130
error = QSslError(QSslError::CertificateUntrusted, cert); break;
1131
case X509_V_ERR_CERT_REJECTED:
1132
error = QSslError(QSslError::CertificateRejected, cert); break;
1134
error = QSslError(QSslError::UnspecifiedError, cert); break;
1139
bool QSslSocketBackendPrivate::startHandshake()
1143
// Check if the connection has been established. Get all errors from the
1144
// verification stage.
1145
_q_sslErrorList()->mutex.lock();
1146
_q_sslErrorList()->errors.clear();
1147
int result = (mode == QSslSocket::SslClientMode) ? q_SSL_connect(ssl) : q_SSL_accept(ssl);
1149
const QList<QPair<int, int> > &lastErrors = _q_sslErrorList()->errors;
1150
for (int i = 0; i < lastErrors.size(); ++i) {
1151
const QPair<int, int> ¤tError = lastErrors.at(i);
1152
// Initialize the peer certificate chain in order to find which certificate caused this error
1153
if (configuration.peerCertificateChain.isEmpty())
1154
configuration.peerCertificateChain = STACKOFX509_to_QSslCertificates(q_SSL_get_peer_cert_chain(ssl));
1155
emit q->peerVerifyError(_q_OpenSSL_to_QSslError(currentError.first,
1156
configuration.peerCertificateChain.value(currentError.second)));
1157
if (q->state() != QAbstractSocket::ConnectedState)
1161
errorList << lastErrors;
1162
_q_sslErrorList()->mutex.unlock();
1164
// Connection aborted during handshake phase.
1165
if (q->state() != QAbstractSocket::ConnectedState)
1168
// Check if we're encrypted or not.
1170
switch (q_SSL_get_error(ssl, result)) {
1171
case SSL_ERROR_WANT_READ:
1172
case SSL_ERROR_WANT_WRITE:
1173
// The handshake is not yet complete.
1176
q->setErrorString(QSslSocket::tr("Error during SSL handshake: %1").arg(getErrorsFromOpenSsl()));
1177
q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
1178
#ifdef QSSLSOCKET_DEBUG
1179
qDebug() << "QSslSocketBackendPrivate::startHandshake: error!" << q->errorString();
1181
emit q->error(QAbstractSocket::SslHandshakeFailedError);
1187
// Store the peer certificate and chain. For clients, the peer certificate
1188
// chain includes the peer certificate; for servers, it doesn't. Both the
1189
// peer certificate and the chain may be empty if the peer didn't present
1191
if (configuration.peerCertificateChain.isEmpty())
1192
configuration.peerCertificateChain = STACKOFX509_to_QSslCertificates(q_SSL_get_peer_cert_chain(ssl));
1193
X509 *x509 = q_SSL_get_peer_certificate(ssl);
1194
configuration.peerCertificate = QSslCertificatePrivate::QSslCertificate_from_X509(x509);
1196
if (QSslCertificatePrivate::isBlacklisted(configuration.peerCertificate)) {
1197
q->setErrorString(QSslSocket::tr("The peer certificate is blacklisted"));
1198
q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
1199
emit q->error(QAbstractSocket::SslHandshakeFailedError);
1200
plainSocket->disconnectFromHost();
1204
// Start translating errors.
1205
QList<QSslError> errors;
1206
bool doVerifyPeer = configuration.peerVerifyMode == QSslSocket::VerifyPeer
1207
|| (configuration.peerVerifyMode == QSslSocket::AutoVerifyPeer
1208
&& mode == QSslSocket::SslClientMode);
1210
// Check the peer certificate itself. First try the subject's common name
1211
// (CN) as a wildcard, then try all alternate subject name DNS entries the
1213
if (!configuration.peerCertificate.isNull()) {
1214
// but only if we're a client connecting to a server
1215
// if we're the server, don't check CN
1216
if (mode == QSslSocket::SslClientMode) {
1217
QString peerName = (verificationPeerName.isEmpty () ? q->peerName() : verificationPeerName);
1218
QString commonName = configuration.peerCertificate.subjectInfo(QSslCertificate::CommonName);
1220
if (!isMatchingHostname(commonName.toLower(), peerName.toLower())) {
1221
bool matched = false;
1222
foreach (const QString &altName, configuration.peerCertificate
1223
.alternateSubjectNames().values(QSsl::DnsEntry)) {
1224
if (isMatchingHostname(altName.toLower(), peerName.toLower())) {
1231
// No matches in common names or alternate names.
1232
QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate);
1234
emit q->peerVerifyError(error);
1235
if (q->state() != QAbstractSocket::ConnectedState)
1241
// No peer certificate presented. Report as error if the socket
1244
QSslError error(QSslError::NoPeerCertificate);
1246
emit q->peerVerifyError(error);
1247
if (q->state() != QAbstractSocket::ConnectedState)
1252
// Translate errors from the error list into QSslErrors.
1253
for (int i = 0; i < errorList.size(); ++i) {
1254
const QPair<int, int> &errorAndDepth = errorList.at(i);
1255
int err = errorAndDepth.first;
1256
int depth = errorAndDepth.second;
1257
errors << _q_OpenSSL_to_QSslError(err, configuration.peerCertificateChain.value(depth));
1260
if (!errors.isEmpty()) {
1262
emit q->sslErrors(errors);
1264
bool doEmitSslError;
1265
if (!ignoreErrorsList.empty()) {
1266
// check whether the errors we got are all in the list of expected errors
1267
// (applies only if the method QSslSocket::ignoreSslErrors(const QList<QSslError> &errors)
1269
doEmitSslError = false;
1270
for (int a = 0; a < errors.count(); a++) {
1271
if (!ignoreErrorsList.contains(errors.at(a))) {
1272
doEmitSslError = true;
1277
// if QSslSocket::ignoreSslErrors(const QList<QSslError> &errors) was not called and
1278
// we get an SSL error, emit a signal unless we ignored all errors (by calling
1279
// QSslSocket::ignoreSslErrors() )
1280
doEmitSslError = !ignoreAllSslErrors;
1282
// check whether we need to emit an SSL handshake error
1283
if (doVerifyPeer && doEmitSslError) {
1284
q->setErrorString(sslErrors.first().errorString());
1285
q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
1286
emit q->error(QAbstractSocket::SslHandshakeFailedError);
1287
plainSocket->disconnectFromHost();
1294
// if we have a max read buffer size, reset the plain socket's to 32k
1295
if (readBufferMaxSize)
1296
plainSocket->setReadBufferSize(32768);
1298
connectionEncrypted = true;
1299
emit q->encrypted();
1300
if (autoStartHandshake && pendingClose) {
1301
pendingClose = false;
1302
q->disconnectFromHost();
1307
void QSslSocketBackendPrivate::disconnectFromHost()
1310
q_SSL_shutdown(ssl);
1313
plainSocket->disconnectFromHost();
1316
void QSslSocketBackendPrivate::disconnected()
1323
q_SSL_CTX_free(ctx);
1327
q_EVP_PKEY_free(pkey);
1333
QSslCipher QSslSocketBackendPrivate::sessionCipher() const
1336
return QSslCipher();
1337
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
1338
// FIXME This is fairly evil, but needed to keep source level compatibility
1339
// with the OpenSSL 0.9.x implementation at maximum -- some other functions
1340
// don't take a const SSL_CIPHER* when they should
1341
SSL_CIPHER *sessionCipher = const_cast<SSL_CIPHER *>(q_SSL_get_current_cipher(ssl));
1343
SSL_CIPHER *sessionCipher = q_SSL_get_current_cipher(ssl);
1345
return sessionCipher ? QSslCipher_from_SSL_CIPHER(sessionCipher) : QSslCipher();
1348
QList<QSslCertificate> QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates(STACK_OF(X509) *x509)
1350
ensureInitialized();
1351
QList<QSslCertificate> certificates;
1352
for (int i = 0; i < q_sk_X509_num(x509); ++i) {
1353
if (X509 *entry = q_sk_X509_value(x509, i))
1354
certificates << QSslCertificatePrivate::QSslCertificate_from_X509(entry);
1356
return certificates;
1359
QString QSslSocketBackendPrivate::getErrorsFromOpenSsl()
1361
QString errorString;
1362
unsigned long errNum;
1363
while((errNum = q_ERR_get_error())) {
1364
if (! errorString.isEmpty())
1365
errorString.append(QLatin1String(", "));
1366
const char *error = q_ERR_error_string(errNum, NULL);
1367
errorString.append(QString::fromAscii(error)); // error is ascii according to man ERR_error_string
1372
bool QSslSocketBackendPrivate::isMatchingHostname(const QString &cn, const QString &hostname)
1374
int wildcard = cn.indexOf(QLatin1Char('*'));
1376
// Check this is a wildcard cert, if not then just compare the strings
1378
return cn == hostname;
1380
int firstCnDot = cn.indexOf(QLatin1Char('.'));
1381
int secondCnDot = cn.indexOf(QLatin1Char('.'), firstCnDot+1);
1383
// Check at least 3 components
1384
if ((-1 == secondCnDot) || (secondCnDot+1 >= cn.length()))
1387
// Check * is last character of 1st component (ie. there's a following .)
1388
if (wildcard+1 != firstCnDot)
1391
// Check only one star
1392
if (cn.lastIndexOf(QLatin1Char('*')) != wildcard)
1395
// Check characters preceding * (if any) match
1396
if (wildcard && (hostname.leftRef(wildcard) != cn.leftRef(wildcard)))
1399
// Check characters following first . match
1400
if (hostname.midRef(hostname.indexOf(QLatin1Char('.'))) != cn.midRef(firstCnDot))
1403
// Check if the hostname is an IP address, if so then wildcards are not allowed
1404
QHostAddress addr(hostname);
1408
// Ok, I guess this was a wildcard CN and the hostname matches.