source: trunk/src/network/ssl/qsslsocket_openssl.cpp@ 1168

Last change on this file since 1168 was 1115, checked in by Dmitry A. Kuminov, 12 years ago

network: Use system locations for loading cert files in SSL mode.

This requires cert files to be present in /@unixroot/etc/ssl/certs/ or in
%ETC%/ssl/certs/.

File size: 51.6 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtNetwork module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42//#define QSSLSOCKET_DEBUG
43
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"
49
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
62
63QT_BEGIN_NAMESPACE
64
65#if defined(Q_OS_MAC)
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)
75#include <e32base.h>
76#include <e32std.h>
77#include <e32debug.h>
78#include <QtCore/private/qcore_symbian_p.h>
79#endif
80
81bool QSslSocketPrivate::s_libraryLoaded = false;
82bool QSslSocketPrivate::s_loadedCiphersAndCerts = false;
83
84/* \internal
85
86 From OpenSSL's thread(3) manual page:
87
88 OpenSSL can safely be used in multi-threaded applications provided that at
89 least two callback functions are set.
90
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. ...
96 ...
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)
100*/
101class QOpenSslLocks
102{
103public:
104 inline QOpenSslLocks()
105 : initLocker(QMutex::Recursive),
106 locksLocker(QMutex::Recursive)
107 {
108 QMutexLocker locker(&locksLocker);
109 int numLocks = q_CRYPTO_num_locks();
110 locks = new QMutex *[numLocks];
111 memset(locks, 0, numLocks * sizeof(QMutex *));
112 }
113 inline ~QOpenSslLocks()
114 {
115 QMutexLocker locker(&locksLocker);
116 for (int i = 0; i < q_CRYPTO_num_locks(); ++i)
117 delete locks[i];
118 delete [] locks;
119
120 QSslSocketPrivate::deinitialize();
121 }
122 inline QMutex *lock(int num)
123 {
124 QMutexLocker locker(&locksLocker);
125 QMutex *tmp = locks[num];
126 if (!tmp)
127 tmp = locks[num] = new QMutex(QMutex::Recursive);
128 return tmp;
129 }
130
131 QMutex *globalLock()
132 {
133 return &locksLocker;
134 }
135
136 QMutex *initLock()
137 {
138 return &initLocker;
139 }
140
141private:
142 QMutex initLocker;
143 QMutex locksLocker;
144 QMutex **locks;
145};
146Q_GLOBAL_STATIC(QOpenSslLocks, openssl_locks)
147
148extern "C" {
149static void locking_function(int mode, int lockNumber, const char *, int)
150{
151 QMutex *mutex = openssl_locks()->lock(lockNumber);
152
153 // Lock or unlock it
154 if (mode & CRYPTO_LOCK)
155 mutex->lock();
156 else
157 mutex->unlock();
158}
159static unsigned long id_function()
160{
161 return (quintptr)QThread::currentThreadId();
162}
163} // extern "C"
164
165QSslSocketBackendPrivate::QSslSocketBackendPrivate()
166 : ssl(0),
167 ctx(0),
168 pkey(0),
169 readBio(0),
170 writeBio(0),
171 session(0)
172{
173 // Calls SSL_library_init().
174 ensureInitialized();
175}
176
177QSslSocketBackendPrivate::~QSslSocketBackendPrivate()
178{
179}
180
181QSslCipher QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(SSL_CIPHER *cipher)
182{
183 QSslCipher ciph;
184
185 char buf [256];
186 QString descriptionOneLine = QString::fromLatin1(q_SSL_CIPHER_description(cipher, buf, sizeof(buf)));
187
188 QStringList descriptionList = descriptionOneLine.split(QLatin1String(" "), QString::SkipEmptyParts);
189 if (descriptionList.size() > 5) {
190 // ### crude code.
191 ciph.d->isNull = false;
192 ciph.d->name = descriptionList.at(0);
193
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;
203
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"));
211
212 ciph.d->bits = cipher->strength_bits;
213 ciph.d->supportedBits = cipher->alg_bits;
214
215 }
216 return ciph;
217}
218
219// ### This list is shared between all threads, and protected by a
220// mutex. Investigate using thread local storage instead.
221struct QSslErrorList
222{
223 QMutex mutex;
224 QList<QPair<int, int> > errors;
225};
226Q_GLOBAL_STATIC(QSslErrorList, _q_sslErrorList)
227static int q_X509Callback(int ok, X509_STORE_CTX *ctx)
228{
229 if (!ok) {
230 // Store the error and at which depth the error was detected.
231 _q_sslErrorList()->errors << qMakePair<int, int>(ctx->error, ctx->error_depth);
232 }
233 // Always return OK to allow verification to continue. We're handle the
234 // errors gracefully after collecting all errors, after verification has
235 // completed.
236 return 1;
237}
238
239bool QSslSocketBackendPrivate::initSslContext()
240{
241 Q_Q(QSslSocket);
242
243 // Create and initialize SSL context. Accept SSLv2, SSLv3 and TLSv1.
244 bool client = (mode == QSslSocket::SslClientMode);
245
246 bool reinitialized = false;
247init_context:
248 switch (configuration.protocol) {
249 case QSsl::SslV2:
250 ctx = q_SSL_CTX_new(client ? q_SSLv2_client_method() : q_SSLv2_server_method());
251 break;
252 case QSsl::SslV3:
253 ctx = q_SSL_CTX_new(client ? q_SSLv3_client_method() : q_SSLv3_server_method());
254 break;
255 case QSsl::AnyProtocol:
256 default:
257 ctx = q_SSL_CTX_new(client ? q_SSLv23_client_method() : q_SSLv23_server_method());
258 break;
259 case QSsl::TlsV1:
260 ctx = q_SSL_CTX_new(client ? q_TLSv1_client_method() : q_TLSv1_server_method());
261 break;
262 }
263 if (!ctx) {
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)
269 goto init_context;
270 }
271
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);
276 return false;
277 }
278
279 // Enable all bug workarounds.
280 q_SSL_CTX_set_options(ctx, SSL_OP_ALL);
281
282 // Initialize ciphers
283 QByteArray cipherString;
284 int first = true;
285 QList<QSslCipher> ciphers = configuration.ciphers;
286 if (ciphers.isEmpty())
287 ciphers = defaultCiphers();
288 foreach (const QSslCipher &cipher, ciphers) {
289 if (first)
290 first = false;
291 else
292 cipherString.append(':');
293 cipherString.append(cipher.name().toLatin1());
294 }
295
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);
301 return false;
302 }
303
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);
311 } else {
312 q_X509_STORE_add_cert(ctx->cert_store, (X509 *)caCertificate.handle());
313 }
314 }
315 // now add the expired certs
316 foreach (const QSslCertificate &caCertificate, expiredCerts) {
317 q_X509_STORE_add_cert(ctx->cert_store, (X509 *)caCertificate.handle());
318 }
319
320 // Register a custom callback to get all verification errors.
321 X509_STORE_set_verify_cb_func(ctx->cert_store, q_X509Callback);
322
323 if (!configuration.localCertificate.isNull()) {
324 // Require a private key as well.
325 if (configuration.privateKey.isNull()) {
326 q->setErrorString(QSslSocket::tr("Cannot provide a certificate with no key, %1").arg(getErrorsFromOpenSsl()));
327 emit q->error(QAbstractSocket::UnknownSocketError);
328 return false;
329 }
330
331 // Load certificate
332 if (!q_SSL_CTX_use_certificate(ctx, (X509 *)configuration.localCertificate.handle())) {
333 q->setErrorString(QSslSocket::tr("Error loading local certificate, %1").arg(getErrorsFromOpenSsl()));
334 emit q->error(QAbstractSocket::UnknownSocketError);
335 return false;
336 }
337
338 // Load private key
339 pkey = q_EVP_PKEY_new();
340 // before we were using EVP_PKEY_assign_R* functions and did not use EVP_PKEY_free.
341 // this lead to a memory leak. Now we use the *_set1_* functions which do not
342 // take ownership of the RSA/DSA key instance because the QSslKey already has ownership.
343 if (configuration.privateKey.algorithm() == QSsl::Rsa)
344 q_EVP_PKEY_set1_RSA(pkey, (RSA *)configuration.privateKey.handle());
345 else
346 q_EVP_PKEY_set1_DSA(pkey, (DSA *)configuration.privateKey.handle());
347 if (!q_SSL_CTX_use_PrivateKey(ctx, pkey)) {
348 q->setErrorString(QSslSocket::tr("Error loading private key, %1").arg(getErrorsFromOpenSsl()));
349 emit q->error(QAbstractSocket::UnknownSocketError);
350 return false;
351 }
352
353 // Check if the certificate matches the private key.
354 if (!q_SSL_CTX_check_private_key(ctx)) {
355 q->setErrorString(QSslSocket::tr("Private key does not certify public key, %1").arg(getErrorsFromOpenSsl()));
356 emit q->error(QAbstractSocket::UnknownSocketError);
357 return false;
358 }
359 }
360
361 // Initialize peer verification.
362 if (configuration.peerVerifyMode == QSslSocket::VerifyNone) {
363 q_SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
364 } else {
365 q_SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, q_X509Callback);
366 }
367
368 // Set verification depth.
369 if (configuration.peerVerifyDepth != 0)
370 q_SSL_CTX_set_verify_depth(ctx, configuration.peerVerifyDepth);
371
372 // Create and initialize SSL session
373 if (!(ssl = q_SSL_new(ctx))) {
374 // ### Bad error code
375 q->setErrorString(QSslSocket::tr("Error creating SSL session, %1").arg(getErrorsFromOpenSsl()));
376 q->setSocketError(QAbstractSocket::UnknownSocketError);
377 emit q->error(QAbstractSocket::UnknownSocketError);
378 return false;
379 }
380
381 // Clear the session.
382 q_SSL_clear(ssl);
383 errorList.clear();
384
385 // Initialize memory BIOs for encryption and decryption.
386 readBio = q_BIO_new(q_BIO_s_mem());
387 writeBio = q_BIO_new(q_BIO_s_mem());
388 if (!readBio || !writeBio) {
389 // ### Bad error code
390 q->setErrorString(QSslSocket::tr("Error creating SSL session: %1").arg(getErrorsFromOpenSsl()));
391 q->setSocketError(QAbstractSocket::UnknownSocketError);
392 emit q->error(QAbstractSocket::UnknownSocketError);
393 return false;
394 }
395
396 // Assign the bios.
397 q_SSL_set_bio(ssl, readBio, writeBio);
398
399 if (mode == QSslSocket::SslClientMode)
400 q_SSL_set_connect_state(ssl);
401 else
402 q_SSL_set_accept_state(ssl);
403
404 return true;
405}
406
407/*!
408 \internal
409*/
410void QSslSocketPrivate::deinitialize()
411{
412 q_CRYPTO_set_id_callback(0);
413 q_CRYPTO_set_locking_callback(0);
414}
415
416/*!
417 \internal
418
419 Does the minimum amount of initialization to determine whether SSL
420 is supported or not.
421*/
422
423bool QSslSocketPrivate::supportsSsl()
424{
425 return ensureLibraryLoaded();
426}
427
428bool QSslSocketPrivate::ensureLibraryLoaded()
429{
430 if (!q_resolveOpenSslSymbols())
431 return false;
432
433 // Check if the library itself needs to be initialized.
434 QMutexLocker locker(openssl_locks()->initLock());
435 if (!s_libraryLoaded) {
436 s_libraryLoaded = true;
437
438 // Initialize OpenSSL.
439 q_CRYPTO_set_id_callback(id_function);
440 q_CRYPTO_set_locking_callback(locking_function);
441 if (q_SSL_library_init() != 1)
442 return false;
443 q_SSL_load_error_strings();
444 q_OpenSSL_add_all_algorithms();
445
446 // Initialize OpenSSL's random seed.
447 if (!q_RAND_status()) {
448 struct {
449 int msec;
450 int sec;
451 void *stack;
452 } randomish;
453
454 int attempts = 500;
455 do {
456 if (attempts < 500) {
457#if defined(Q_OS_UNIX) || defined(Q_OS_OS2)
458 struct timespec ts = {0, 33333333};
459 nanosleep(&ts, 0);
460#else
461 Sleep(3);
462#endif
463 randomish.msec = attempts;
464 }
465 randomish.stack = (void *)&randomish;
466 randomish.msec = QTime::currentTime().msec();
467 randomish.sec = QTime::currentTime().second();
468 q_RAND_seed((const char *)&randomish, sizeof(randomish));
469 } while (!q_RAND_status() && --attempts);
470 if (!attempts)
471 return false;
472 }
473 }
474 return true;
475}
476
477void QSslSocketPrivate::ensureCiphersAndCertsLoaded()
478{
479 QMutexLocker locker(openssl_locks()->initLock());
480 if (s_loadedCiphersAndCerts)
481 return;
482 s_loadedCiphersAndCerts = true;
483
484 resetDefaultCiphers();
485
486 //load symbols needed to receive certificates from system store
487#if defined(Q_OS_MAC)
488 QLibrary securityLib("/System/Library/Frameworks/Security.framework/Versions/Current/Security");
489 if (securityLib.load()) {
490 ptrSecCertificateGetData = (PtrSecCertificateGetData) securityLib.resolve("SecCertificateGetData");
491 if (!ptrSecCertificateGetData)
492 qWarning("could not resolve symbols in security library"); // should never happen
493
494 ptrSecTrustSettingsCopyCertificates = (PtrSecTrustSettingsCopyCertificates) securityLib.resolve("SecTrustSettingsCopyCertificates");
495 if (!ptrSecTrustSettingsCopyCertificates) { // method was introduced in Leopard, use legacy method if it's not there
496 ptrSecTrustCopyAnchorCertificates = (PtrSecTrustCopyAnchorCertificates) securityLib.resolve("SecTrustCopyAnchorCertificates");
497 if (!ptrSecTrustCopyAnchorCertificates)
498 qWarning("could not resolve symbols in security library"); // should never happen
499 }
500 } else {
501 qWarning("could not load security library");
502 }
503#elif defined(Q_OS_WIN)
504 HINSTANCE hLib = LoadLibraryW(L"Crypt32");
505 if (hLib) {
506#if defined(Q_OS_WINCE)
507 ptrCertOpenSystemStoreW = (PtrCertOpenSystemStoreW)GetProcAddress(hLib, L"CertOpenStore");
508 ptrCertFindCertificateInStore = (PtrCertFindCertificateInStore)GetProcAddress(hLib, L"CertFindCertificateInStore");
509 ptrCertCloseStore = (PtrCertCloseStore)GetProcAddress(hLib, L"CertCloseStore");
510#else
511 ptrCertOpenSystemStoreW = (PtrCertOpenSystemStoreW)GetProcAddress(hLib, "CertOpenSystemStoreW");
512 ptrCertFindCertificateInStore = (PtrCertFindCertificateInStore)GetProcAddress(hLib, "CertFindCertificateInStore");
513 ptrCertCloseStore = (PtrCertCloseStore)GetProcAddress(hLib, "CertCloseStore");
514#endif
515 if (!ptrCertOpenSystemStoreW || !ptrCertFindCertificateInStore || !ptrCertCloseStore)
516 qWarning("could not resolve symbols in crypt32 library"); // should never happen
517 } else {
518 qWarning("could not load crypt32 library"); // should never happen
519 }
520#endif
521 setDefaultCaCertificates(systemCaCertificates());
522}
523
524/*!
525 \internal
526
527 Declared static in QSslSocketPrivate, makes sure the SSL libraries have
528 been initialized.
529*/
530
531void QSslSocketPrivate::ensureInitialized()
532{
533 if (!supportsSsl())
534 return;
535
536 ensureCiphersAndCertsLoaded();
537}
538
539/*!
540 \internal
541
542 Declared static in QSslSocketPrivate, backend-dependent loading of
543 application-wide global ciphers.
544*/
545void QSslSocketPrivate::resetDefaultCiphers()
546{
547 SSL_CTX *myCtx = q_SSL_CTX_new(q_SSLv23_client_method());
548 SSL *mySsl = q_SSL_new(myCtx);
549
550 QList<QSslCipher> ciphers;
551
552 STACK_OF(SSL_CIPHER) *supportedCiphers = q_SSL_get_ciphers(mySsl);
553 for (int i = 0; i < q_sk_SSL_CIPHER_num(supportedCiphers); ++i) {
554 if (SSL_CIPHER *cipher = q_sk_SSL_CIPHER_value(supportedCiphers, i)) {
555 if (cipher->valid) {
556 QSslCipher ciph = QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(cipher);
557 if (!ciph.isNull()) {
558 if (!ciph.name().toLower().startsWith(QLatin1String("adh")))
559 ciphers << ciph;
560 }
561 }
562 }
563 }
564
565 q_SSL_CTX_free(myCtx);
566 q_SSL_free(mySsl);
567
568 setDefaultSupportedCiphers(ciphers);
569 setDefaultCiphers(ciphers);
570}
571
572#if defined(Q_OS_SYMBIAN)
573
574CSymbianCertificateRetriever::CSymbianCertificateRetriever() : CActive(CActive::EPriorityStandard),
575 iCertificatePtr(0,0,0), iSequenceError(KErrNone)
576{
577}
578
579CSymbianCertificateRetriever::~CSymbianCertificateRetriever()
580{
581 iThread.Close();
582}
583
584CSymbianCertificateRetriever* CSymbianCertificateRetriever::NewL()
585{
586 CSymbianCertificateRetriever* self = new (ELeave) CSymbianCertificateRetriever();
587 CleanupStack::PushL(self);
588 self->ConstructL();
589 CleanupStack::Pop();
590 return self;
591}
592
593int CSymbianCertificateRetriever::GetCertificates(QList<QByteArray> &certificates)
594{
595 iCertificates = &certificates;
596
597 TRequestStatus status;
598 iThread.Logon(status);
599 iThread.Resume();
600 User::WaitForRequest(status);
601 if (iThread.ExitType() == EExitKill)
602 return KErrDied;
603 else
604 return status.Int(); // Logon() completes with the thread's exit value
605}
606
607void CSymbianCertificateRetriever::doThreadEntryL()
608{
609 CActiveScheduler* activeScheduler = new (ELeave) CActiveScheduler;
610 CleanupStack::PushL(activeScheduler);
611 CActiveScheduler::Install(activeScheduler);
612
613 CActiveScheduler::Add(this);
614
615 // These aren't deleted in the destructor so leaving the to CS is ok
616 iCertStore = CUnifiedCertStore::NewLC(qt_s60GetRFs(), EFalse);
617 iCertFilter = CCertAttributeFilter::NewLC();
618
619 // only interested in CA certs
620 iCertFilter->SetOwnerType(ECACertificate);
621 // only interested in X.509 format (we don't support WAP formats)
622 iCertFilter->SetFormat(EX509Certificate);
623
624 // Kick off the sequence by initializing the cert store
625 iState = Initializing;
626 iCertStore->Initialize(iStatus);
627 SetActive();
628
629 CActiveScheduler::Start();
630
631 // Sequence complete, clean up
632
633 // These MUST be cleaned up before the installed CActiveScheduler is destroyed and can't be left to the
634 // destructor of CSymbianCertificateRetriever. Otherwise the destructor of CActiveScheduler will get
635 // stuck.
636 iCertInfos.Close();
637 CleanupStack::PopAndDestroy(3); // activeScheduler, iCertStore, iCertFilter
638}
639
640
641TInt CSymbianCertificateRetriever::ThreadEntryPoint(TAny* aParams)
642{
643 User::SetCritical(User::EProcessCritical);
644 CTrapCleanup* cleanupStack = CTrapCleanup::New();
645
646 CSymbianCertificateRetriever* self = (CSymbianCertificateRetriever*) aParams;
647 TRAPD(err, self->doThreadEntryL());
648 delete cleanupStack;
649
650 // doThreadEntryL() can leave only before the retrieval sequence is started
651 if (err)
652 return err;
653 else
654 return self->iSequenceError; // return any error that occurred during the retrieval
655}
656
657void CSymbianCertificateRetriever::ConstructL()
658{
659 TInt err;
660 int i=0;
661 QString name(QLatin1String("CertWorkerThread-%1"));
662 //recently closed thread names remain in use for a while until all handles have been closed
663 //including users of RUndertaker
664 do {
665 err = iThread.Create(qt_QString2TPtrC(name.arg(i++)),
666 CSymbianCertificateRetriever::ThreadEntryPoint, 16384, NULL, this);
667 } while (err == KErrAlreadyExists);
668 User::LeaveIfError(err);
669}
670
671void CSymbianCertificateRetriever::DoCancel()
672{
673 switch(iState) {
674 case Initializing:
675 iCertStore->CancelInitialize();
676 break;
677 case Listing:
678 iCertStore->CancelList();
679 break;
680 case RetrievingCertificates:
681 iCertStore->CancelGetCert();
682 break;
683 }
684}
685
686TInt CSymbianCertificateRetriever::RunError(TInt aError)
687{
688 // If something goes wrong in the sequence, abort the sequence
689 iSequenceError = aError; // this gets reported to the client in the TRequestStatus
690 CActiveScheduler::Stop();
691 return KErrNone;
692}
693
694void CSymbianCertificateRetriever::GetCertificateL()
695{
696 if (iCurrentCertIndex < iCertInfos.Count()) {
697 CCTCertInfo* certInfo = iCertInfos[iCurrentCertIndex++];
698 iCertificateData = QByteArray();
699 QT_TRYCATCH_LEAVING(iCertificateData.resize(certInfo->Size()));
700 iCertificatePtr.Set((TUint8*)iCertificateData.data(), 0, iCertificateData.size());
701#ifdef QSSLSOCKET_DEBUG
702 qDebug() << "getting " << qt_TDesC2QString(certInfo->Label()) << " size=" << certInfo->Size();
703 qDebug() << "format=" << certInfo->CertificateFormat();
704 qDebug() << "ownertype=" << certInfo->CertificateOwnerType();
705 qDebug() << "type=" << hex << certInfo->Type().iUid;
706#endif
707 iCertStore->Retrieve(*certInfo, iCertificatePtr, iStatus);
708 iState = RetrievingCertificates;
709 SetActive();
710 } else {
711 //reached end of list
712 CActiveScheduler::Stop();
713 }
714}
715
716void CSymbianCertificateRetriever::RunL()
717{
718#ifdef QSSLSOCKET_DEBUG
719 qDebug() << "CSymbianCertificateRetriever::RunL status " << iStatus.Int() << " count " << iCertInfos.Count() << " index " << iCurrentCertIndex;
720#endif
721 switch (iState) {
722 case Initializing:
723 User::LeaveIfError(iStatus.Int()); // initialise fail means pointless to continue
724 iState = Listing;
725 iCertStore->List(iCertInfos, *iCertFilter, iStatus);
726 SetActive();
727 break;
728
729 case Listing:
730 User::LeaveIfError(iStatus.Int()); // listing fail means pointless to continue
731 iCurrentCertIndex = 0;
732 GetCertificateL();
733 break;
734
735 case RetrievingCertificates:
736 if (iStatus.Int() == KErrNone)
737 iCertificates->append(iCertificateData);
738 else
739 qWarning() << "CSymbianCertificateRetriever: failed to retrieve a certificate, error " << iStatus.Int();
740 GetCertificateL();
741 break;
742 }
743}
744#endif // defined(Q_OS_SYMBIAN)
745
746QList<QSslCertificate> QSslSocketPrivate::systemCaCertificates()
747{
748 ensureInitialized();
749#ifdef QSSLSOCKET_DEBUG
750 QElapsedTimer timer;
751 timer.start();
752#endif
753 QList<QSslCertificate> systemCerts;
754#if defined(Q_OS_MAC)
755 CFArrayRef cfCerts;
756 OSStatus status = 1;
757
758 OSStatus SecCertificateGetData (
759 SecCertificateRef certificate,
760 CSSM_DATA_PTR data
761 );
762
763 if (ptrSecCertificateGetData) {
764 if (ptrSecTrustSettingsCopyCertificates)
765 status = ptrSecTrustSettingsCopyCertificates(kSecTrustSettingsDomainSystem, &cfCerts);
766 else if (ptrSecTrustCopyAnchorCertificates)
767 status = ptrSecTrustCopyAnchorCertificates(&cfCerts);
768 if (!status) {
769 CFIndex size = CFArrayGetCount(cfCerts);
770 for (CFIndex i = 0; i < size; ++i) {
771 SecCertificateRef cfCert = (SecCertificateRef)CFArrayGetValueAtIndex(cfCerts, i);
772 CSSM_DATA data;
773 CSSM_DATA_PTR dataPtr = &data;
774 if (ptrSecCertificateGetData(cfCert, dataPtr)) {
775 qWarning("error retrieving a CA certificate from the system store");
776 } else {
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));
781 }
782 }
783 }
784 else {
785 // no detailed error handling here
786 qWarning("could not retrieve system CA certificates");
787 }
788 }
789#elif defined(Q_OS_WIN)
790 if (ptrCertOpenSystemStoreW && ptrCertFindCertificateInStore && ptrCertCloseStore) {
791 HCERTSTORE hSystemStore;
792#if defined(Q_OS_WINCE)
793 hSystemStore = ptrCertOpenSystemStoreW(CERT_STORE_PROV_SYSTEM_W,
794 0,
795 0,
796 CERT_STORE_NO_CRYPT_RELEASE_FLAG|CERT_SYSTEM_STORE_CURRENT_USER,
797 L"ROOT");
798#else
799 hSystemStore = ptrCertOpenSystemStoreW(0, L"ROOT");
800#endif
801 if(hSystemStore) {
802 PCCERT_CONTEXT pc = NULL;
803 while(1) {
804 pc = ptrCertFindCertificateInStore( hSystemStore, X509_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, pc);
805 if(!pc)
806 break;
807 QByteArray der((const char *)(pc->pbCertEncoded), static_cast<int>(pc->cbCertEncoded));
808 QSslCertificate cert(der, QSsl::Der);
809 systemCerts.append(cert);
810 }
811 ptrCertCloseStore(hSystemStore, 0);
812 }
813 }
814#elif (defined(Q_OS_UNIX) && !defined(Q_OS_SYMBIAN)) || defined(Q_OS_OS2)
815 QSet<QString> certFiles;
816 QList<QByteArray> directories;
817#if !defined(Q_OS_OS2)
818 directories << "/etc/ssl/certs/"; // (K)ubuntu, OpenSUSE, Mandriva, MeeGo ...
819 directories << "/usr/lib/ssl/certs/"; // Gentoo, Mandrake
820 directories << "/usr/share/ssl/"; // Centos, Redhat, SuSE
821 directories << "/usr/local/ssl/"; // Normal OpenSSL Tarball
822 directories << "/var/ssl/certs/"; // AIX
823 directories << "/usr/local/ssl/certs/"; // Solaris
824 directories << "/opt/openssl/certs/"; // HP-UX
825#else
826 directories << "/@unixroot/etc/ssl/certs/";
827 QByteArray etc = qgetenv("ETC");
828 if (!etc.isEmpty())
829 directories << etc.append("/ssl/certs/");
830#endif
831
832 QDir currentDir;
833 QStringList nameFilters;
834 nameFilters << QLatin1String("*.pem") << QLatin1String("*.crt");
835 currentDir.setNameFilters(nameFilters);
836 for (int a = 0; a < directories.count(); a++) {
837 currentDir.setPath(QFile::decodeName(directories.at(a)));
838 QDirIterator it(currentDir);
839 while(it.hasNext()) {
840 it.next();
841 // use canonical path here to not load the same certificate twice if symlinked
842 certFiles.insert(it.fileInfo().canonicalFilePath());
843 }
844 }
845 QSetIterator<QString> it(certFiles);
846 while(it.hasNext()) {
847 systemCerts.append(QSslCertificate::fromPath(it.next()));
848 }
849#if !defined(Q_OS_OS2)
850 systemCerts.append(QSslCertificate::fromPath(QLatin1String("/etc/pki/tls/certs/ca-bundle.crt"), QSsl::Pem)); // Fedora, Mandriva
851 systemCerts.append(QSslCertificate::fromPath(QLatin1String("/usr/local/share/certs/ca-root-nss.crt"), QSsl::Pem)); // FreeBSD's ca_root_nss
852#else
853 systemCerts.append(QSslCertificate::fromPath(QLatin1String("/@unixroot/etc/pki/tls/certs/ca-bundle.crt"), QSsl::Pem));
854#endif
855
856#elif defined(Q_OS_SYMBIAN)
857 QList<QByteArray> certs;
858 QScopedPointer<CSymbianCertificateRetriever> retriever(CSymbianCertificateRetriever::NewL());
859
860 retriever->GetCertificates(certs);
861 foreach (const QByteArray &encodedCert, certs) {
862 QSslCertificate cert(encodedCert, QSsl::Der);
863 if (!cert.isNull()) {
864#ifdef QSSLSOCKET_DEBUG
865 qDebug() << "imported certificate: " << cert.issuerInfo(QSslCertificate::CommonName);
866#endif
867 systemCerts.append(cert);
868 }
869 }
870#endif
871#ifdef QSSLSOCKET_DEBUG
872 qDebug() << "systemCaCertificates retrieval time " << timer.elapsed() << "ms";
873 qDebug() << "imported " << systemCerts.count() << " certificates";
874#endif
875
876 return systemCerts;
877}
878
879void QSslSocketBackendPrivate::startClientEncryption()
880{
881 if (!initSslContext()) {
882 // ### report error: internal OpenSSL failure
883 return;
884 }
885
886 // Start connecting. This will place outgoing data in the BIO, so we
887 // follow up with calling transmit().
888 startHandshake();
889 transmit();
890}
891
892void QSslSocketBackendPrivate::startServerEncryption()
893{
894 if (!initSslContext()) {
895 // ### report error: internal OpenSSL failure
896 return;
897 }
898
899 // Start connecting. This will place outgoing data in the BIO, so we
900 // follow up with calling transmit().
901 startHandshake();
902 transmit();
903}
904
905/*!
906 \internal
907
908 Transmits encrypted data between the BIOs and the socket.
909*/
910void QSslSocketBackendPrivate::transmit()
911{
912 Q_Q(QSslSocket);
913
914 // If we don't have any SSL context, don't bother transmitting.
915 if (!ssl)
916 return;
917
918 bool transmitting;
919 do {
920 transmitting = false;
921
922 // If the connection is secure, we can transfer data from the write
923 // buffer (in plain text) to the write BIO through SSL_write.
924 if (connectionEncrypted && !writeBuffer.isEmpty()) {
925 qint64 totalBytesWritten = 0;
926 int nextDataBlockSize;
927 while ((nextDataBlockSize = writeBuffer.nextDataBlockSize()) > 0) {
928 int writtenBytes = q_SSL_write(ssl, writeBuffer.readPointer(), nextDataBlockSize);
929 if (writtenBytes <= 0) {
930 // ### Better error handling.
931 q->setErrorString(QSslSocket::tr("Unable to write data: %1").arg(getErrorsFromOpenSsl()));
932 q->setSocketError(QAbstractSocket::UnknownSocketError);
933 emit q->error(QAbstractSocket::UnknownSocketError);
934 return;
935 }
936#ifdef QSSLSOCKET_DEBUG
937 qDebug() << "QSslSocketBackendPrivate::transmit: encrypted" << writtenBytes << "bytes";
938#endif
939 writeBuffer.free(writtenBytes);
940 totalBytesWritten += writtenBytes;
941
942 if (writtenBytes < nextDataBlockSize) {
943 // break out of the writing loop and try again after we had read
944 transmitting = true;
945 break;
946 }
947 }
948
949 if (totalBytesWritten > 0) {
950 // Don't emit bytesWritten() recursively.
951 if (!emittedBytesWritten) {
952 emittedBytesWritten = true;
953 emit q->bytesWritten(totalBytesWritten);
954 emittedBytesWritten = false;
955 }
956 }
957 }
958
959 // Check if we've got any data to be written to the socket.
960 QVarLengthArray<char, 4096> data;
961 int pendingBytes;
962 while (plainSocket->isValid() && (pendingBytes = q_BIO_pending(writeBio)) > 0) {
963 // Read encrypted data from the write BIO into a buffer.
964 data.resize(pendingBytes);
965 int encryptedBytesRead = q_BIO_read(writeBio, data.data(), pendingBytes);
966
967 // Write encrypted data from the buffer to the socket.
968 plainSocket->write(data.constData(), encryptedBytesRead);
969#ifdef QSSLSOCKET_DEBUG
970 qDebug() << "QSslSocketBackendPrivate::transmit: wrote" << encryptedBytesRead << "encrypted bytes to the socket";
971#endif
972 transmitting = true;
973 }
974
975 // Check if we've got any data to be read from the socket.
976 if (!connectionEncrypted || !readBufferMaxSize || readBuffer.size() < readBufferMaxSize)
977 while ((pendingBytes = plainSocket->bytesAvailable()) > 0) {
978 // Read encrypted data from the socket into a buffer.
979 data.resize(pendingBytes);
980 // just peek() here because q_BIO_write could write less data than expected
981 int encryptedBytesRead = plainSocket->peek(data.data(), pendingBytes);
982#ifdef QSSLSOCKET_DEBUG
983 qDebug() << "QSslSocketBackendPrivate::transmit: read" << encryptedBytesRead << "encrypted bytes from the socket";
984#endif
985 // Write encrypted data from the buffer into the read BIO.
986 int writtenToBio = q_BIO_write(readBio, data.constData(), encryptedBytesRead);
987
988 // do the actual read() here and throw away the results.
989 if (writtenToBio > 0) {
990 // ### TODO: make this cheaper by not making it memcpy. E.g. make it work with data=0x0 or make it work with seek
991 plainSocket->read(data.data(), writtenToBio);
992 } else {
993 // ### Better error handling.
994 q->setErrorString(QSslSocket::tr("Unable to decrypt data: %1").arg(getErrorsFromOpenSsl()));
995 q->setSocketError(QAbstractSocket::UnknownSocketError);
996 emit q->error(QAbstractSocket::UnknownSocketError);
997 return;
998 }
999
1000 transmitting = true;
1001 }
1002
1003 // If the connection isn't secured yet, this is the time to retry the
1004 // connect / accept.
1005 if (!connectionEncrypted) {
1006#ifdef QSSLSOCKET_DEBUG
1007 qDebug() << "QSslSocketBackendPrivate::transmit: testing encryption";
1008#endif
1009 if (startHandshake()) {
1010#ifdef QSSLSOCKET_DEBUG
1011 qDebug() << "QSslSocketBackendPrivate::transmit: encryption established";
1012#endif
1013 connectionEncrypted = true;
1014 transmitting = true;
1015 } else if (plainSocket->state() != QAbstractSocket::ConnectedState) {
1016#ifdef QSSLSOCKET_DEBUG
1017 qDebug() << "QSslSocketBackendPrivate::transmit: connection lost";
1018#endif
1019 break;
1020 } else {
1021#ifdef QSSLSOCKET_DEBUG
1022 qDebug() << "QSslSocketBackendPrivate::transmit: encryption not done yet";
1023#endif
1024 }
1025 }
1026
1027 // If the request is small and the remote host closes the transmission
1028 // after sending, there's a chance that startHandshake() will already
1029 // have triggered a shutdown.
1030 if (!ssl)
1031 continue;
1032
1033 // We always read everything from the SSL decryption buffers, even if
1034 // we have a readBufferMaxSize. There's no point in leaving data there
1035 // just so that readBuffer.size() == readBufferMaxSize.
1036 int readBytes = 0;
1037 data.resize(4096);
1038 ::memset(data.data(), 0, data.size());
1039 do {
1040 // Don't use SSL_pending(). It's very unreliable.
1041 if ((readBytes = q_SSL_read(ssl, data.data(), data.size())) > 0) {
1042#ifdef QSSLSOCKET_DEBUG
1043 qDebug() << "QSslSocketBackendPrivate::transmit: decrypted" << readBytes << "bytes";
1044#endif
1045 char *ptr = readBuffer.reserve(readBytes);
1046 ::memcpy(ptr, data.data(), readBytes);
1047
1048 if (readyReadEmittedPointer)
1049 *readyReadEmittedPointer = true;
1050 emit q->readyRead();
1051 transmitting = true;
1052 continue;
1053 }
1054
1055 // Error.
1056 switch (q_SSL_get_error(ssl, readBytes)) {
1057 case SSL_ERROR_WANT_READ:
1058 case SSL_ERROR_WANT_WRITE:
1059 // Out of data.
1060 break;
1061 case SSL_ERROR_ZERO_RETURN:
1062 // The remote host closed the connection.
1063#ifdef QSSLSOCKET_DEBUG
1064 qDebug() << "QSslSocketBackendPrivate::transmit: remote disconnect";
1065#endif
1066 plainSocket->disconnectFromHost();
1067 break;
1068 case SSL_ERROR_SYSCALL: // some IO error
1069 case SSL_ERROR_SSL: // error in the SSL library
1070 // we do not know exactly what the error is, nor whether we can recover from it,
1071 // so just return to prevent an endless loop in the outer "while" statement
1072 q->setErrorString(QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
1073 q->setSocketError(QAbstractSocket::UnknownSocketError);
1074 emit q->error(QAbstractSocket::UnknownSocketError);
1075 return;
1076 default:
1077 // SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT: can only happen with a
1078 // BIO_s_connect() or BIO_s_accept(), which we do not call.
1079 // SSL_ERROR_WANT_X509_LOOKUP: can only happen with a
1080 // SSL_CTX_set_client_cert_cb(), which we do not call.
1081 // So this default case should never be triggered.
1082 q->setErrorString(QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
1083 q->setSocketError(QAbstractSocket::UnknownSocketError);
1084 emit q->error(QAbstractSocket::UnknownSocketError);
1085 break;
1086 }
1087 } while (ssl && readBytes > 0);
1088 } while (ssl && ctx && transmitting);
1089}
1090
1091static QSslError _q_OpenSSL_to_QSslError(int errorCode, const QSslCertificate &cert)
1092{
1093 QSslError error;
1094 switch (errorCode) {
1095 case X509_V_OK:
1096 // X509_V_OK is also reported if the peer had no certificate.
1097 break;
1098 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1099 error = QSslError(QSslError::UnableToGetIssuerCertificate, cert); break;
1100 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1101 error = QSslError(QSslError::UnableToDecryptCertificateSignature, cert); break;
1102 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1103 error = QSslError(QSslError::UnableToDecodeIssuerPublicKey, cert); break;
1104 case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1105 error = QSslError(QSslError::CertificateSignatureFailed, cert); break;
1106 case X509_V_ERR_CERT_NOT_YET_VALID:
1107 error = QSslError(QSslError::CertificateNotYetValid, cert); break;
1108 case X509_V_ERR_CERT_HAS_EXPIRED:
1109 error = QSslError(QSslError::CertificateExpired, cert); break;
1110 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1111 error = QSslError(QSslError::InvalidNotBeforeField, cert); break;
1112 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1113 error = QSslError(QSslError::InvalidNotAfterField, cert); break;
1114 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1115 error = QSslError(QSslError::SelfSignedCertificate, cert); break;
1116 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1117 error = QSslError(QSslError::SelfSignedCertificateInChain, cert); break;
1118 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1119 error = QSslError(QSslError::UnableToGetLocalIssuerCertificate, cert); break;
1120 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1121 error = QSslError(QSslError::UnableToVerifyFirstCertificate, cert); break;
1122 case X509_V_ERR_CERT_REVOKED:
1123 error = QSslError(QSslError::CertificateRevoked, cert); break;
1124 case X509_V_ERR_INVALID_CA:
1125 error = QSslError(QSslError::InvalidCaCertificate, cert); break;
1126 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1127 error = QSslError(QSslError::PathLengthExceeded, cert); break;
1128 case X509_V_ERR_INVALID_PURPOSE:
1129 error = QSslError(QSslError::InvalidPurpose, cert); break;
1130 case X509_V_ERR_CERT_UNTRUSTED:
1131 error = QSslError(QSslError::CertificateUntrusted, cert); break;
1132 case X509_V_ERR_CERT_REJECTED:
1133 error = QSslError(QSslError::CertificateRejected, cert); break;
1134 default:
1135 error = QSslError(QSslError::UnspecifiedError, cert); break;
1136 }
1137 return error;
1138}
1139
1140bool QSslSocketBackendPrivate::startHandshake()
1141{
1142 Q_Q(QSslSocket);
1143
1144 // Check if the connection has been established. Get all errors from the
1145 // verification stage.
1146 _q_sslErrorList()->mutex.lock();
1147 _q_sslErrorList()->errors.clear();
1148 int result = (mode == QSslSocket::SslClientMode) ? q_SSL_connect(ssl) : q_SSL_accept(ssl);
1149
1150 const QList<QPair<int, int> > &lastErrors = _q_sslErrorList()->errors;
1151 for (int i = 0; i < lastErrors.size(); ++i) {
1152 const QPair<int, int> &currentError = lastErrors.at(i);
1153 // Initialize the peer certificate chain in order to find which certificate caused this error
1154 if (configuration.peerCertificateChain.isEmpty())
1155 configuration.peerCertificateChain = STACKOFX509_to_QSslCertificates(q_SSL_get_peer_cert_chain(ssl));
1156 emit q->peerVerifyError(_q_OpenSSL_to_QSslError(currentError.first,
1157 configuration.peerCertificateChain.value(currentError.second)));
1158 if (q->state() != QAbstractSocket::ConnectedState)
1159 break;
1160 }
1161
1162 errorList << lastErrors;
1163 _q_sslErrorList()->mutex.unlock();
1164
1165 // Connection aborted during handshake phase.
1166 if (q->state() != QAbstractSocket::ConnectedState)
1167 return false;
1168
1169 // Check if we're encrypted or not.
1170 if (result <= 0) {
1171 switch (q_SSL_get_error(ssl, result)) {
1172 case SSL_ERROR_WANT_READ:
1173 case SSL_ERROR_WANT_WRITE:
1174 // The handshake is not yet complete.
1175 break;
1176 default:
1177 q->setErrorString(QSslSocket::tr("Error during SSL handshake: %1").arg(getErrorsFromOpenSsl()));
1178 q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
1179#ifdef QSSLSOCKET_DEBUG
1180 qDebug() << "QSslSocketBackendPrivate::startHandshake: error!" << q->errorString();
1181#endif
1182 emit q->error(QAbstractSocket::SslHandshakeFailedError);
1183 q->abort();
1184 }
1185 return false;
1186 }
1187
1188 // Store the peer certificate and chain. For clients, the peer certificate
1189 // chain includes the peer certificate; for servers, it doesn't. Both the
1190 // peer certificate and the chain may be empty if the peer didn't present
1191 // any certificate.
1192 if (configuration.peerCertificateChain.isEmpty())
1193 configuration.peerCertificateChain = STACKOFX509_to_QSslCertificates(q_SSL_get_peer_cert_chain(ssl));
1194 X509 *x509 = q_SSL_get_peer_certificate(ssl);
1195 configuration.peerCertificate = QSslCertificatePrivate::QSslCertificate_from_X509(x509);
1196 q_X509_free(x509);
1197 if (QSslCertificatePrivate::isBlacklisted(configuration.peerCertificate)) {
1198 q->setErrorString(QSslSocket::tr("The peer certificate is blacklisted"));
1199 q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
1200 emit q->error(QAbstractSocket::SslHandshakeFailedError);
1201 plainSocket->disconnectFromHost();
1202 return false;
1203 }
1204
1205 // Start translating errors.
1206 QList<QSslError> errors;
1207 bool doVerifyPeer = configuration.peerVerifyMode == QSslSocket::VerifyPeer
1208 || (configuration.peerVerifyMode == QSslSocket::AutoVerifyPeer
1209 && mode == QSslSocket::SslClientMode);
1210
1211 // Check the peer certificate itself. First try the subject's common name
1212 // (CN) as a wildcard, then try all alternate subject name DNS entries the
1213 // same way.
1214 if (!configuration.peerCertificate.isNull()) {
1215 // but only if we're a client connecting to a server
1216 // if we're the server, don't check CN
1217 if (mode == QSslSocket::SslClientMode) {
1218 QString peerName = (verificationPeerName.isEmpty () ? q->peerName() : verificationPeerName);
1219 QString commonName = configuration.peerCertificate.subjectInfo(QSslCertificate::CommonName);
1220
1221 if (!isMatchingHostname(commonName.toLower(), peerName.toLower())) {
1222 bool matched = false;
1223 foreach (const QString &altName, configuration.peerCertificate
1224 .alternateSubjectNames().values(QSsl::DnsEntry)) {
1225 if (isMatchingHostname(altName.toLower(), peerName.toLower())) {
1226 matched = true;
1227 break;
1228 }
1229 }
1230
1231 if (!matched) {
1232 // No matches in common names or alternate names.
1233 QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate);
1234 errors << error;
1235 emit q->peerVerifyError(error);
1236 if (q->state() != QAbstractSocket::ConnectedState)
1237 return false;
1238 }
1239 }
1240 }
1241 } else {
1242 // No peer certificate presented. Report as error if the socket
1243 // expected one.
1244 if (doVerifyPeer) {
1245 QSslError error(QSslError::NoPeerCertificate);
1246 errors << error;
1247 emit q->peerVerifyError(error);
1248 if (q->state() != QAbstractSocket::ConnectedState)
1249 return false;
1250 }
1251 }
1252
1253 // Translate errors from the error list into QSslErrors.
1254 for (int i = 0; i < errorList.size(); ++i) {
1255 const QPair<int, int> &errorAndDepth = errorList.at(i);
1256 int err = errorAndDepth.first;
1257 int depth = errorAndDepth.second;
1258 errors << _q_OpenSSL_to_QSslError(err, configuration.peerCertificateChain.value(depth));
1259 }
1260
1261 if (!errors.isEmpty()) {
1262 sslErrors = errors;
1263 emit q->sslErrors(errors);
1264
1265 bool doEmitSslError;
1266 if (!ignoreErrorsList.empty()) {
1267 // check whether the errors we got are all in the list of expected errors
1268 // (applies only if the method QSslSocket::ignoreSslErrors(const QList<QSslError> &errors)
1269 // was called)
1270 doEmitSslError = false;
1271 for (int a = 0; a < errors.count(); a++) {
1272 if (!ignoreErrorsList.contains(errors.at(a))) {
1273 doEmitSslError = true;
1274 break;
1275 }
1276 }
1277 } else {
1278 // if QSslSocket::ignoreSslErrors(const QList<QSslError> &errors) was not called and
1279 // we get an SSL error, emit a signal unless we ignored all errors (by calling
1280 // QSslSocket::ignoreSslErrors() )
1281 doEmitSslError = !ignoreAllSslErrors;
1282 }
1283 // check whether we need to emit an SSL handshake error
1284 if (doVerifyPeer && doEmitSslError) {
1285 q->setErrorString(sslErrors.first().errorString());
1286 q->setSocketError(QAbstractSocket::SslHandshakeFailedError);
1287 emit q->error(QAbstractSocket::SslHandshakeFailedError);
1288 plainSocket->disconnectFromHost();
1289 return false;
1290 }
1291 } else {
1292 sslErrors.clear();
1293 }
1294
1295 // if we have a max read buffer size, reset the plain socket's to 1k
1296 if (readBufferMaxSize)
1297 plainSocket->setReadBufferSize(1024);
1298
1299 connectionEncrypted = true;
1300 emit q->encrypted();
1301 if (autoStartHandshake && pendingClose) {
1302 pendingClose = false;
1303 q->disconnectFromHost();
1304 }
1305 return true;
1306}
1307
1308void QSslSocketBackendPrivate::disconnectFromHost()
1309{
1310 if (ssl) {
1311 q_SSL_shutdown(ssl);
1312 transmit();
1313 }
1314 plainSocket->disconnectFromHost();
1315}
1316
1317void QSslSocketBackendPrivate::disconnected()
1318{
1319 if (ssl) {
1320 q_SSL_free(ssl);
1321 ssl = 0;
1322 }
1323 if (ctx) {
1324 q_SSL_CTX_free(ctx);
1325 ctx = 0;
1326 }
1327 if (pkey) {
1328 q_EVP_PKEY_free(pkey);
1329 pkey = 0;
1330 }
1331
1332}
1333
1334QSslCipher QSslSocketBackendPrivate::sessionCipher() const
1335{
1336 if (!ssl || !ctx)
1337 return QSslCipher();
1338#if OPENSSL_VERSION_NUMBER >= 0x10000000L
1339 // FIXME This is fairly evil, but needed to keep source level compatibility
1340 // with the OpenSSL 0.9.x implementation at maximum -- some other functions
1341 // don't take a const SSL_CIPHER* when they should
1342 SSL_CIPHER *sessionCipher = const_cast<SSL_CIPHER *>(q_SSL_get_current_cipher(ssl));
1343#else
1344 SSL_CIPHER *sessionCipher = q_SSL_get_current_cipher(ssl);
1345#endif
1346 return sessionCipher ? QSslCipher_from_SSL_CIPHER(sessionCipher) : QSslCipher();
1347}
1348
1349QList<QSslCertificate> QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates(STACK_OF(X509) *x509)
1350{
1351 ensureInitialized();
1352 QList<QSslCertificate> certificates;
1353 for (int i = 0; i < q_sk_X509_num(x509); ++i) {
1354 if (X509 *entry = q_sk_X509_value(x509, i))
1355 certificates << QSslCertificatePrivate::QSslCertificate_from_X509(entry);
1356 }
1357 return certificates;
1358}
1359
1360QString QSslSocketBackendPrivate::getErrorsFromOpenSsl()
1361{
1362 QString errorString;
1363 unsigned long errNum;
1364 while((errNum = q_ERR_get_error())) {
1365 if (! errorString.isEmpty())
1366 errorString.append(QLatin1String(", "));
1367 const char *error = q_ERR_error_string(errNum, NULL);
1368 errorString.append(QString::fromAscii(error)); // error is ascii according to man ERR_error_string
1369 }
1370 return errorString;
1371}
1372
1373bool QSslSocketBackendPrivate::isMatchingHostname(const QString &cn, const QString &hostname)
1374{
1375 int wildcard = cn.indexOf(QLatin1Char('*'));
1376
1377 // Check this is a wildcard cert, if not then just compare the strings
1378 if (wildcard < 0)
1379 return cn == hostname;
1380
1381 int firstCnDot = cn.indexOf(QLatin1Char('.'));
1382 int secondCnDot = cn.indexOf(QLatin1Char('.'), firstCnDot+1);
1383
1384 // Check at least 3 components
1385 if ((-1 == secondCnDot) || (secondCnDot+1 >= cn.length()))
1386 return false;
1387
1388 // Check * is last character of 1st component (ie. there's a following .)
1389 if (wildcard+1 != firstCnDot)
1390 return false;
1391
1392 // Check only one star
1393 if (cn.lastIndexOf(QLatin1Char('*')) != wildcard)
1394 return false;
1395
1396 // Check characters preceding * (if any) match
1397 if (wildcard && (hostname.leftRef(wildcard) != cn.leftRef(wildcard)))
1398 return false;
1399
1400 // Check characters following first . match
1401 if (hostname.midRef(hostname.indexOf(QLatin1Char('.'))) != cn.midRef(firstCnDot))
1402 return false;
1403
1404 // Check if the hostname is an IP address, if so then wildcards are not allowed
1405 QHostAddress addr(hostname);
1406 if (!addr.isNull())
1407 return false;
1408
1409 // Ok, I guess this was a wildcard CN and the hostname matches.
1410 return true;
1411}
1412
1413QT_END_NAMESPACE
Note: See TracBrowser for help on using the repository browser.