~ubuntu-branches/ubuntu/precise/qt4-x11/precise-proposed

« back to all changes in this revision

Viewing changes to .pc/blacklist-diginotar-certs.diff/src/network/ssl/qsslsocket_openssl.cpp

  • Committer: Package Import Robot
  • Author(s): Jonathan Riddell, Jonathan Riddell, Felix Geyer
  • Date: 2011-11-01 16:23:55 UTC
  • mfrom: (15.3.22 sid)
  • Revision ID: package-import@ubuntu.com-20111101162355-4dhsj6563ii8enl6
Tags: 4:4.7.4-1ubuntu1
[ Jonathan Riddell ]
* Merge from Debian Git packaging.  Remaining Ubuntu changes:
  - Do not package ibase/firebird package, remove from debian/rules and
    debian/control
  - libqt4-sql-ibase not recommend for libqt4-sql
  - build with -no-phonon
  - do not build libqt4-phonon, disable in debian/control
  - Build packages with lzma compression using the dh addon from pkg-kde-tools
  - Rules to remove po dir in clean
  - Add MessagesQt.sh
  - Rules to create Messages.sh link to MessagesQt.sh and rules to create po
    dir and exectue extract-messages.sh in common-install-prehook-impl
  - Make libqt4-dev depend on libx11-dev
  - Add and install Trolltech.conf in libqtcore4.install
  - Build QtWebkit and use it only for QtAssistant
    + Rule to put qt_webkit_version.pri in mkspecs/modules
    + Rule to remove libQtWebKit* after build
    + Exclude usr/bin/assistant-qt4 from dh_shlibdeps
  - Fix Lucid upgrades: libqt4-help breaks/replaces libqtcore4 (<< 4:4.7.0)
  - Change OpenGL backend from GL to GLES 2 for armel (Debian does this for
    armhf)
    + Build-depend and make libqt4-opengl-dev depend on libgles2-mesa-dev
      instead of libgl1-mesa-dev and libglu1-mesa-dev
    + Pass "-opengl es2" to configure
  - Pass extra_configure_opts += -arch armv6 on both armel and armhf and not
    just armhf
  - In debian/rules Move documentation building to override_dh_auto_install where
    dh_listpackages works as expected with dpkg-buildpackage. (LP: #857377)
  - debian/compat is 9 and build-depend on newer debhelper for multiarch
* debian/patches/blacklist-diginotar-certs.diff is now
  debian/patches/blacklist-diginotar-cert.diff to match Debian
* Add prefix to some patches to clarify they come from Ubuntu rather than Debian
 - kubuntu_97_a11y_qt_and_qml_backport.diff
 - kubuntu_98_fix_accessible_menu.diff
 - kubuntu_99_notify_qml_name_description_change.diff

[ Felix Geyer ]
* Use DEB_*_MAINT_APPEND instead of setting CXXFLAGS and LDFLAGS.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/****************************************************************************
2
 
**
3
 
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4
 
** All rights reserved.
5
 
** Contact: Nokia Corporation (qt-info@nokia.com)
6
 
**
7
 
** This file is part of the QtNetwork module of the Qt Toolkit.
8
 
**
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.
17
 
**
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.
21
 
**
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.
29
 
**
30
 
** Other Usage
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.
33
 
**
34
 
**
35
 
**
36
 
**
37
 
**
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
 
 
63
 
QT_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
 
 
81
 
bool QSslSocketPrivate::s_libraryLoaded = false;
82
 
bool 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
 
*/
101
 
class QOpenSslLocks
102
 
{
103
 
public:
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
 
 
141
 
private:
142
 
    QMutex initLocker;
143
 
    QMutex locksLocker;
144
 
    QMutex **locks;
145
 
};
146
 
Q_GLOBAL_STATIC(QOpenSslLocks, openssl_locks)
147
 
 
148
 
extern "C" {
149
 
static 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
 
}
159
 
static unsigned long id_function()
160
 
{
161
 
    return (quintptr)QThread::currentThreadId();
162
 
}
163
 
} // extern "C"
164
 
 
165
 
QSslSocketBackendPrivate::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
 
 
177
 
QSslSocketBackendPrivate::~QSslSocketBackendPrivate()
178
 
{
179
 
}
180
 
 
181
 
QSslCipher 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.
221
 
struct QSslErrorList
222
 
{
223
 
    QMutex mutex;
224
 
    QList<QPair<int, int> > errors;
225
 
};
226
 
Q_GLOBAL_STATIC(QSslErrorList, _q_sslErrorList)
227
 
static 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
 
 
239
 
bool 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;
247
 
init_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
 
 
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;
321
 
#endif
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());
326
 
        }
327
 
    }
328
 
 
329
 
    // Register a custom callback to get all verification errors.
330
 
    X509_STORE_set_verify_cb_func(ctx->cert_store, q_X509Callback);
331
 
 
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);
337
 
            return false;
338
 
        }
339
 
 
340
 
        // Load certificate
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);
344
 
            return false;
345
 
        }
346
 
 
347
 
        // Load private key
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());
354
 
        else
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);
359
 
            return false;
360
 
        }
361
 
 
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);
366
 
            return false;
367
 
        }
368
 
    }
369
 
 
370
 
    // Initialize peer verification.
371
 
    if (configuration.peerVerifyMode == QSslSocket::VerifyNone) {
372
 
        q_SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
373
 
    } else {
374
 
        q_SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, q_X509Callback);
375
 
    }
376
 
 
377
 
    // Set verification depth.
378
 
    if (configuration.peerVerifyDepth != 0)
379
 
        q_SSL_CTX_set_verify_depth(ctx, configuration.peerVerifyDepth);
380
 
 
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);
387
 
        return false;
388
 
    }
389
 
 
390
 
    // Clear the session.
391
 
    q_SSL_clear(ssl);
392
 
    errorList.clear();
393
 
 
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);
402
 
        return false;
403
 
    }
404
 
 
405
 
    // Assign the bios.
406
 
    q_SSL_set_bio(ssl, readBio, writeBio);
407
 
 
408
 
    if (mode == QSslSocket::SslClientMode)
409
 
        q_SSL_set_connect_state(ssl);
410
 
    else
411
 
        q_SSL_set_accept_state(ssl);
412
 
 
413
 
    return true;
414
 
}
415
 
 
416
 
/*!
417
 
    \internal
418
 
*/
419
 
void QSslSocketPrivate::deinitialize()
420
 
{
421
 
    q_CRYPTO_set_id_callback(0);
422
 
    q_CRYPTO_set_locking_callback(0);
423
 
}
424
 
 
425
 
/*!
426
 
    \internal
427
 
 
428
 
    Does the minimum amount of initialization to determine whether SSL
429
 
    is supported or not.
430
 
*/
431
 
 
432
 
bool QSslSocketPrivate::supportsSsl()
433
 
{
434
 
    return ensureLibraryLoaded();
435
 
}
436
 
 
437
 
bool QSslSocketPrivate::ensureLibraryLoaded()
438
 
{
439
 
    if (!q_resolveOpenSslSymbols())
440
 
        return false;
441
 
 
442
 
    // Check if the library itself needs to be initialized.
443
 
    QMutexLocker locker(openssl_locks()->initLock());
444
 
    if (!s_libraryLoaded) {
445
 
        s_libraryLoaded = true;
446
 
 
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)
451
 
            return false;
452
 
        q_SSL_load_error_strings();
453
 
        q_OpenSSL_add_all_algorithms();
454
 
 
455
 
        // Initialize OpenSSL's random seed.
456
 
        if (!q_RAND_status()) {
457
 
            struct {
458
 
                int msec;
459
 
                int sec;
460
 
                void *stack;
461
 
            } randomish;
462
 
 
463
 
            int attempts = 500;
464
 
            do {
465
 
                if (attempts < 500) {
466
 
#ifdef Q_OS_UNIX
467
 
                    struct timespec ts = {0, 33333333};
468
 
                    nanosleep(&ts, 0);
469
 
#else
470
 
                    Sleep(3);
471
 
#endif
472
 
                    randomish.msec = attempts;
473
 
                }
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);
479
 
            if (!attempts)
480
 
                return false;
481
 
        }
482
 
    }
483
 
    return true;
484
 
}
485
 
 
486
 
void QSslSocketPrivate::ensureCiphersAndCertsLoaded()
487
 
{
488
 
    QMutexLocker locker(openssl_locks()->initLock());
489
 
    if (s_loadedCiphersAndCerts)
490
 
        return;
491
 
    s_loadedCiphersAndCerts = true;
492
 
 
493
 
    resetDefaultCiphers();
494
 
 
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
502
 
 
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
508
 
        }
509
 
    } else {
510
 
        qWarning("could not load security library");
511
 
    }
512
 
#elif defined(Q_OS_WIN)
513
 
    HINSTANCE hLib = LoadLibraryW(L"Crypt32");
514
 
    if (hLib) {
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");
519
 
#else
520
 
        ptrCertOpenSystemStoreW = (PtrCertOpenSystemStoreW)GetProcAddress(hLib, "CertOpenSystemStoreW");
521
 
        ptrCertFindCertificateInStore = (PtrCertFindCertificateInStore)GetProcAddress(hLib, "CertFindCertificateInStore");
522
 
        ptrCertCloseStore = (PtrCertCloseStore)GetProcAddress(hLib, "CertCloseStore");
523
 
#endif
524
 
        if (!ptrCertOpenSystemStoreW || !ptrCertFindCertificateInStore || !ptrCertCloseStore)
525
 
            qWarning("could not resolve symbols in crypt32 library"); // should never happen
526
 
    } else {
527
 
        qWarning("could not load crypt32 library"); // should never happen
528
 
    }
529
 
#endif
530
 
    setDefaultCaCertificates(systemCaCertificates());
531
 
}
532
 
 
533
 
/*!
534
 
    \internal
535
 
 
536
 
    Declared static in QSslSocketPrivate, makes sure the SSL libraries have
537
 
    been initialized.
538
 
*/
539
 
 
540
 
void QSslSocketPrivate::ensureInitialized()
541
 
{
542
 
    if (!supportsSsl())
543
 
        return;
544
 
 
545
 
    ensureCiphersAndCertsLoaded();
546
 
}
547
 
 
548
 
/*!
549
 
    \internal
550
 
 
551
 
    Declared static in QSslSocketPrivate, backend-dependent loading of
552
 
    application-wide global ciphers.
553
 
*/
554
 
void QSslSocketPrivate::resetDefaultCiphers()
555
 
{
556
 
    SSL_CTX *myCtx = q_SSL_CTX_new(q_SSLv23_client_method());
557
 
    SSL *mySsl = q_SSL_new(myCtx);
558
 
 
559
 
    QList<QSslCipher> ciphers;
560
 
 
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)) {
564
 
            if (cipher->valid) {
565
 
                QSslCipher ciph = QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(cipher);
566
 
                if (!ciph.isNull()) {
567
 
                    if (!ciph.name().toLower().startsWith(QLatin1String("adh")))
568
 
                        ciphers << ciph;
569
 
                }
570
 
            }
571
 
        }
572
 
    }
573
 
 
574
 
    q_SSL_CTX_free(myCtx);
575
 
    q_SSL_free(mySsl);
576
 
 
577
 
    setDefaultSupportedCiphers(ciphers);
578
 
    setDefaultCiphers(ciphers);
579
 
}
580
 
 
581
 
#if defined(Q_OS_SYMBIAN)
582
 
 
583
 
CSymbianCertificateRetriever::CSymbianCertificateRetriever() : CActive(CActive::EPriorityStandard),
584
 
    iCertificatePtr(0,0,0), iSequenceError(KErrNone)
585
 
{
586
 
}
587
 
 
588
 
CSymbianCertificateRetriever::~CSymbianCertificateRetriever()
589
 
{
590
 
    iThread.Close();
591
 
}
592
 
 
593
 
CSymbianCertificateRetriever* CSymbianCertificateRetriever::NewL()
594
 
{
595
 
    CSymbianCertificateRetriever* self = new (ELeave) CSymbianCertificateRetriever();
596
 
    CleanupStack::PushL(self);
597
 
    self->ConstructL();
598
 
    CleanupStack::Pop();
599
 
    return self;
600
 
}
601
 
 
602
 
int CSymbianCertificateRetriever::GetCertificates(QList<QByteArray> &certificates)
603
 
{
604
 
    iCertificates = &certificates;
605
 
 
606
 
    TRequestStatus status;
607
 
    iThread.Logon(status);
608
 
    iThread.Resume();
609
 
    User::WaitForRequest(status);
610
 
    if (iThread.ExitType() == EExitKill)
611
 
        return KErrDied;
612
 
    else
613
 
        return status.Int();    // Logon() completes with the thread's exit value
614
 
}
615
 
 
616
 
void CSymbianCertificateRetriever::doThreadEntryL()
617
 
{
618
 
    CActiveScheduler* activeScheduler = new (ELeave) CActiveScheduler;
619
 
    CleanupStack::PushL(activeScheduler);
620
 
    CActiveScheduler::Install(activeScheduler);
621
 
 
622
 
    CActiveScheduler::Add(this);
623
 
 
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();
627
 
 
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);
632
 
 
633
 
    // Kick off the sequence by initializing the cert store
634
 
    iState = Initializing;
635
 
    iCertStore->Initialize(iStatus);
636
 
    SetActive();
637
 
 
638
 
    CActiveScheduler::Start();
639
 
 
640
 
    // Sequence complete, clean up
641
 
 
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
644
 
    // stuck.
645
 
    iCertInfos.Close();
646
 
    CleanupStack::PopAndDestroy(3);     // activeScheduler, iCertStore, iCertFilter
647
 
}
648
 
 
649
 
 
650
 
TInt CSymbianCertificateRetriever::ThreadEntryPoint(TAny* aParams)
651
 
{
652
 
    User::SetCritical(User::EProcessCritical);
653
 
    CTrapCleanup* cleanupStack = CTrapCleanup::New();
654
 
 
655
 
    CSymbianCertificateRetriever* self = (CSymbianCertificateRetriever*) aParams;
656
 
    TRAPD(err, self->doThreadEntryL());
657
 
    delete cleanupStack;
658
 
 
659
 
    // doThreadEntryL() can leave only before the retrieval sequence is started
660
 
    if (err)
661
 
        return err;
662
 
    else
663
 
        return self->iSequenceError;    // return any error that occurred during the retrieval
664
 
}
665
 
 
666
 
void CSymbianCertificateRetriever::ConstructL()
667
 
{
668
 
    TInt err;
669
 
    int i=0;
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
673
 
    do {
674
 
        err = iThread.Create(qt_QString2TPtrC(name.arg(i++)),
675
 
            CSymbianCertificateRetriever::ThreadEntryPoint, 16384, NULL, this);
676
 
    } while (err == KErrAlreadyExists);
677
 
    User::LeaveIfError(err);
678
 
}
679
 
 
680
 
void CSymbianCertificateRetriever::DoCancel()
681
 
{
682
 
    switch(iState) {
683
 
    case Initializing:
684
 
        iCertStore->CancelInitialize();
685
 
        break;
686
 
    case Listing:
687
 
        iCertStore->CancelList();
688
 
        break;
689
 
    case RetrievingCertificates:
690
 
        iCertStore->CancelGetCert();
691
 
        break;
692
 
    }
693
 
}
694
 
 
695
 
TInt CSymbianCertificateRetriever::RunError(TInt aError)
696
 
{
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();
700
 
    return KErrNone;
701
 
}
702
 
 
703
 
void CSymbianCertificateRetriever::GetCertificateL()
704
 
{
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;
715
 
#endif
716
 
        iCertStore->Retrieve(*certInfo, iCertificatePtr, iStatus);
717
 
        iState = RetrievingCertificates;
718
 
        SetActive();
719
 
    } else {
720
 
        //reached end of list
721
 
        CActiveScheduler::Stop();
722
 
    }
723
 
}
724
 
 
725
 
void CSymbianCertificateRetriever::RunL()
726
 
{
727
 
#ifdef QSSLSOCKET_DEBUG
728
 
    qDebug() << "CSymbianCertificateRetriever::RunL status " << iStatus.Int() << " count " << iCertInfos.Count() << " index " << iCurrentCertIndex;
729
 
#endif
730
 
    switch (iState) {
731
 
    case Initializing:
732
 
        User::LeaveIfError(iStatus.Int()); // initialise fail means pointless to continue
733
 
        iState = Listing;
734
 
        iCertStore->List(iCertInfos, *iCertFilter, iStatus);
735
 
        SetActive();
736
 
        break;
737
 
 
738
 
    case Listing:
739
 
        User::LeaveIfError(iStatus.Int()); // listing fail means pointless to continue
740
 
        iCurrentCertIndex = 0;
741
 
        GetCertificateL();
742
 
        break;
743
 
 
744
 
    case RetrievingCertificates:
745
 
        if (iStatus.Int() == KErrNone)
746
 
            iCertificates->append(iCertificateData);
747
 
        else
748
 
            qWarning() << "CSymbianCertificateRetriever: failed to retrieve a certificate, error " << iStatus.Int();
749
 
        GetCertificateL();
750
 
        break;
751
 
    }
752
 
}
753
 
#endif // defined(Q_OS_SYMBIAN)
754
 
 
755
 
QList<QSslCertificate> QSslSocketPrivate::systemCaCertificates()
756
 
{
757
 
    ensureInitialized();
758
 
#ifdef QSSLSOCKET_DEBUG
759
 
    QElapsedTimer timer;
760
 
    timer.start();
761
 
#endif
762
 
    QList<QSslCertificate> systemCerts;
763
 
#if defined(Q_OS_MAC)
764
 
    CFArrayRef cfCerts;
765
 
    OSStatus status = 1;
766
 
 
767
 
    OSStatus SecCertificateGetData (
768
 
       SecCertificateRef certificate,
769
 
       CSSM_DATA_PTR data
770
 
    );
771
 
 
772
 
    if (ptrSecCertificateGetData) {
773
 
        if (ptrSecTrustSettingsCopyCertificates)
774
 
            status = ptrSecTrustSettingsCopyCertificates(kSecTrustSettingsDomainSystem, &cfCerts);
775
 
        else if (ptrSecTrustCopyAnchorCertificates)
776
 
            status = ptrSecTrustCopyAnchorCertificates(&cfCerts);
777
 
        if (!status) {
778
 
            CFIndex size = CFArrayGetCount(cfCerts);
779
 
            for (CFIndex i = 0; i < size; ++i) {
780
 
                SecCertificateRef cfCert = (SecCertificateRef)CFArrayGetValueAtIndex(cfCerts, i);
781
 
                CSSM_DATA data;
782
 
                CSSM_DATA_PTR dataPtr = &data;
783
 
                if (ptrSecCertificateGetData(cfCert, dataPtr)) {
784
 
                    qWarning("error retrieving a CA certificate from the system store");
785
 
                } else {
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));
790
 
                }
791
 
            }
792
 
            CFRelease(cfCerts);
793
 
        }
794
 
        else {
795
 
           // no detailed error handling here
796
 
           qWarning("could not retrieve system CA certificates");
797
 
        }
798
 
    }
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,
804
 
                                               0,
805
 
                                               0,
806
 
                                               CERT_STORE_NO_CRYPT_RELEASE_FLAG|CERT_SYSTEM_STORE_CURRENT_USER,
807
 
                                               L"ROOT");
808
 
#else
809
 
        hSystemStore = ptrCertOpenSystemStoreW(0, L"ROOT");
810
 
#endif
811
 
        if(hSystemStore) {
812
 
            PCCERT_CONTEXT pc = NULL;
813
 
            while(1) {
814
 
                pc = ptrCertFindCertificateInStore( hSystemStore, X509_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, pc);
815
 
                if(!pc)
816
 
                    break;
817
 
                QByteArray der((const char *)(pc->pbCertEncoded), static_cast<int>(pc->cbCertEncoded));
818
 
                QSslCertificate cert(der, QSsl::Der);
819
 
                systemCerts.append(cert);
820
 
            }
821
 
            ptrCertCloseStore(hSystemStore, 0);
822
 
        }
823
 
    }
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
834
 
 
835
 
    QDir currentDir;
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()) {
843
 
            it.next();
844
 
            // use canonical path here to not load the same certificate twice if symlinked
845
 
            certFiles.insert(it.fileInfo().canonicalFilePath());
846
 
        }
847
 
    }
848
 
    QSetIterator<QString> it(certFiles);
849
 
    while(it.hasNext()) {
850
 
        systemCerts.append(QSslCertificate::fromPath(it.next()));
851
 
    }
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
854
 
 
855
 
#elif defined(Q_OS_SYMBIAN)
856
 
    QList<QByteArray> certs;
857
 
    QScopedPointer<CSymbianCertificateRetriever> retriever(CSymbianCertificateRetriever::NewL());
858
 
 
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);
865
 
#endif
866
 
            systemCerts.append(cert);
867
 
        }
868
 
    }
869
 
#endif
870
 
#ifdef QSSLSOCKET_DEBUG
871
 
    qDebug() << "systemCaCertificates retrieval time " << timer.elapsed() << "ms";
872
 
    qDebug() << "imported " << systemCerts.count() << " certificates";
873
 
#endif
874
 
 
875
 
    return systemCerts;
876
 
}
877
 
 
878
 
void QSslSocketBackendPrivate::startClientEncryption()
879
 
{
880
 
    if (!initSslContext()) {
881
 
        // ### report error: internal OpenSSL failure
882
 
        return;
883
 
    }
884
 
 
885
 
    // Start connecting. This will place outgoing data in the BIO, so we
886
 
    // follow up with calling transmit().
887
 
    startHandshake();
888
 
    transmit();
889
 
}
890
 
 
891
 
void QSslSocketBackendPrivate::startServerEncryption()
892
 
{
893
 
    if (!initSslContext()) {
894
 
        // ### report error: internal OpenSSL failure
895
 
        return;
896
 
    }
897
 
 
898
 
    // Start connecting. This will place outgoing data in the BIO, so we
899
 
    // follow up with calling transmit().
900
 
    startHandshake();
901
 
    transmit();
902
 
}
903
 
 
904
 
/*!
905
 
    \internal
906
 
 
907
 
    Transmits encrypted data between the BIOs and the socket.
908
 
*/
909
 
void QSslSocketBackendPrivate::transmit()
910
 
{
911
 
    Q_Q(QSslSocket);
912
 
 
913
 
    // If we don't have any SSL context, don't bother transmitting.
914
 
    if (!ssl)
915
 
        return;
916
 
 
917
 
    bool transmitting;
918
 
    do {
919
 
        transmitting = false;
920
 
 
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);
933
 
                    return;
934
 
                }
935
 
#ifdef QSSLSOCKET_DEBUG
936
 
                qDebug() << "QSslSocketBackendPrivate::transmit: encrypted" << writtenBytes << "bytes";
937
 
#endif
938
 
                writeBuffer.free(writtenBytes);
939
 
                totalBytesWritten += writtenBytes;
940
 
 
941
 
                if (writtenBytes < nextDataBlockSize) {
942
 
                    // break out of the writing loop and try again after we had read
943
 
                    transmitting = true;
944
 
                    break;
945
 
                }
946
 
            }
947
 
 
948
 
            if (totalBytesWritten > 0) {
949
 
                // Don't emit bytesWritten() recursively.
950
 
                if (!emittedBytesWritten) {
951
 
                    emittedBytesWritten = true;
952
 
                    emit q->bytesWritten(totalBytesWritten);
953
 
                    emittedBytesWritten = false;
954
 
                }
955
 
            }
956
 
        }
957
 
 
958
 
        // Check if we've got any data to be written to the socket.
959
 
        QVarLengthArray<char, 4096> data;
960
 
        int pendingBytes;
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);
965
 
 
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";
970
 
#endif
971
 
            transmitting = true;
972
 
        }
973
 
 
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";
983
 
#endif
984
 
                // Write encrypted data from the buffer into the read BIO.
985
 
                int writtenToBio = q_BIO_write(readBio, data.constData(), encryptedBytesRead);
986
 
 
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);
991
 
                } else {
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);
996
 
                    return;
997
 
                }
998
 
 
999
 
                transmitting = true;
1000
 
            }
1001
 
 
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";
1007
 
#endif
1008
 
            if (startHandshake()) {
1009
 
#ifdef QSSLSOCKET_DEBUG
1010
 
                qDebug() << "QSslSocketBackendPrivate::transmit: encryption established";
1011
 
#endif
1012
 
                connectionEncrypted = true;
1013
 
                transmitting = true;
1014
 
            } else if (plainSocket->state() != QAbstractSocket::ConnectedState) {
1015
 
#ifdef QSSLSOCKET_DEBUG
1016
 
                qDebug() << "QSslSocketBackendPrivate::transmit: connection lost";
1017
 
#endif
1018
 
                break;
1019
 
            } else {
1020
 
#ifdef QSSLSOCKET_DEBUG
1021
 
                qDebug() << "QSslSocketBackendPrivate::transmit: encryption not done yet";
1022
 
#endif
1023
 
            }
1024
 
        }
1025
 
 
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.
1029
 
        if (!ssl)
1030
 
            continue;
1031
 
 
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.
1035
 
        int readBytes = 0;
1036
 
        data.resize(4096);
1037
 
        ::memset(data.data(), 0, data.size());
1038
 
        do {
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";
1043
 
#endif
1044
 
                char *ptr = readBuffer.reserve(readBytes);
1045
 
                ::memcpy(ptr, data.data(), readBytes);
1046
 
 
1047
 
                if (readyReadEmittedPointer)
1048
 
                    *readyReadEmittedPointer = true;
1049
 
                emit q->readyRead();
1050
 
                transmitting = true;
1051
 
                continue;
1052
 
            }
1053
 
 
1054
 
            // Error.
1055
 
            switch (q_SSL_get_error(ssl, readBytes)) {
1056
 
            case SSL_ERROR_WANT_READ:
1057
 
            case SSL_ERROR_WANT_WRITE:
1058
 
                // Out of data.
1059
 
                break;
1060
 
            case SSL_ERROR_ZERO_RETURN:
1061
 
                // The remote host closed the connection.
1062
 
#ifdef QSSLSOCKET_DEBUG
1063
 
                qDebug() << "QSslSocketBackendPrivate::transmit: remote disconnect";
1064
 
#endif
1065
 
                plainSocket->disconnectFromHost();
1066
 
                break;
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);
1074
 
                return;
1075
 
            default:
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);
1084
 
                break;
1085
 
            }
1086
 
        } while (ssl && readBytes > 0);
1087
 
    } while (ssl && ctx && transmitting);
1088
 
}
1089
 
 
1090
 
static QSslError _q_OpenSSL_to_QSslError(int errorCode, const QSslCertificate &cert)
1091
 
{
1092
 
    QSslError error;
1093
 
    switch (errorCode) {
1094
 
    case X509_V_OK:
1095
 
        // X509_V_OK is also reported if the peer had no certificate.
1096
 
        break;
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;
1133
 
    default:
1134
 
        error = QSslError(QSslError::UnspecifiedError, cert); break;
1135
 
    }
1136
 
    return error;
1137
 
}
1138
 
 
1139
 
bool QSslSocketBackendPrivate::startHandshake()
1140
 
{
1141
 
    Q_Q(QSslSocket);
1142
 
 
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);
1148
 
 
1149
 
    const QList<QPair<int, int> > &lastErrors = _q_sslErrorList()->errors;
1150
 
    for (int i = 0; i < lastErrors.size(); ++i) {
1151
 
        const QPair<int, int> &currentError = 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)
1158
 
            break;
1159
 
    }
1160
 
 
1161
 
    errorList << lastErrors;
1162
 
    _q_sslErrorList()->mutex.unlock();
1163
 
 
1164
 
    // Connection aborted during handshake phase.
1165
 
    if (q->state() != QAbstractSocket::ConnectedState)
1166
 
        return false;
1167
 
 
1168
 
    // Check if we're encrypted or not.
1169
 
    if (result <= 0) {
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.
1174
 
            break;
1175
 
        default:
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();
1180
 
#endif
1181
 
            emit q->error(QAbstractSocket::SslHandshakeFailedError);
1182
 
            q->abort();
1183
 
        }
1184
 
        return false;
1185
 
    }
1186
 
 
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
1190
 
    // any certificate.
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);
1195
 
    q_X509_free(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();
1201
 
        return false;
1202
 
    }
1203
 
 
1204
 
    // Start translating errors.
1205
 
    QList<QSslError> errors;
1206
 
    bool doVerifyPeer = configuration.peerVerifyMode == QSslSocket::VerifyPeer
1207
 
                        || (configuration.peerVerifyMode == QSslSocket::AutoVerifyPeer
1208
 
                            && mode == QSslSocket::SslClientMode);
1209
 
 
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
1212
 
    // same way.
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);
1219
 
 
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())) {
1225
 
                        matched = true;
1226
 
                        break;
1227
 
                    }
1228
 
                }
1229
 
 
1230
 
                if (!matched) {
1231
 
                    // No matches in common names or alternate names.
1232
 
                    QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate);
1233
 
                    errors << error;
1234
 
                    emit q->peerVerifyError(error);
1235
 
                    if (q->state() != QAbstractSocket::ConnectedState)
1236
 
                        return false;
1237
 
                }
1238
 
            }
1239
 
        }
1240
 
    } else {
1241
 
        // No peer certificate presented. Report as error if the socket
1242
 
        // expected one.
1243
 
        if (doVerifyPeer) {
1244
 
            QSslError error(QSslError::NoPeerCertificate);
1245
 
            errors << error;
1246
 
            emit q->peerVerifyError(error);
1247
 
            if (q->state() != QAbstractSocket::ConnectedState)
1248
 
                return false;
1249
 
        }
1250
 
    }
1251
 
 
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));
1258
 
    }
1259
 
 
1260
 
    if (!errors.isEmpty()) {
1261
 
        sslErrors = errors;
1262
 
        emit q->sslErrors(errors);
1263
 
 
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)
1268
 
            // was called)
1269
 
            doEmitSslError = false;
1270
 
            for (int a = 0; a < errors.count(); a++) {
1271
 
                if (!ignoreErrorsList.contains(errors.at(a))) {
1272
 
                    doEmitSslError = true;
1273
 
                    break;
1274
 
                }
1275
 
            }
1276
 
        } else {
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;
1281
 
        }
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();
1288
 
            return false;
1289
 
        }
1290
 
    } else {
1291
 
        sslErrors.clear();
1292
 
    }
1293
 
 
1294
 
    // if we have a max read buffer size, reset the plain socket's to 32k
1295
 
    if (readBufferMaxSize)
1296
 
        plainSocket->setReadBufferSize(32768);
1297
 
 
1298
 
    connectionEncrypted = true;
1299
 
    emit q->encrypted();
1300
 
    if (autoStartHandshake && pendingClose) {
1301
 
        pendingClose = false;
1302
 
        q->disconnectFromHost();
1303
 
    }
1304
 
    return true;
1305
 
}
1306
 
 
1307
 
void QSslSocketBackendPrivate::disconnectFromHost()
1308
 
{
1309
 
    if (ssl) {
1310
 
        q_SSL_shutdown(ssl);
1311
 
        transmit();
1312
 
    }
1313
 
    plainSocket->disconnectFromHost();
1314
 
}
1315
 
 
1316
 
void QSslSocketBackendPrivate::disconnected()
1317
 
{
1318
 
    if (ssl) {
1319
 
        q_SSL_free(ssl);
1320
 
        ssl = 0;
1321
 
    }
1322
 
    if (ctx) {
1323
 
        q_SSL_CTX_free(ctx);
1324
 
        ctx = 0;
1325
 
    }
1326
 
    if (pkey) {
1327
 
        q_EVP_PKEY_free(pkey);
1328
 
        pkey = 0;
1329
 
    }
1330
 
 
1331
 
}
1332
 
 
1333
 
QSslCipher QSslSocketBackendPrivate::sessionCipher() const
1334
 
{
1335
 
    if (!ssl || !ctx)
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));
1342
 
#else
1343
 
    SSL_CIPHER *sessionCipher = q_SSL_get_current_cipher(ssl);
1344
 
#endif
1345
 
    return sessionCipher ? QSslCipher_from_SSL_CIPHER(sessionCipher) : QSslCipher();
1346
 
}
1347
 
 
1348
 
QList<QSslCertificate> QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates(STACK_OF(X509) *x509)
1349
 
{
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);
1355
 
    }
1356
 
    return certificates;
1357
 
}
1358
 
 
1359
 
QString QSslSocketBackendPrivate::getErrorsFromOpenSsl()
1360
 
{
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
1368
 
    }
1369
 
    return errorString;
1370
 
}
1371
 
 
1372
 
bool QSslSocketBackendPrivate::isMatchingHostname(const QString &cn, const QString &hostname)
1373
 
{
1374
 
    int wildcard = cn.indexOf(QLatin1Char('*'));
1375
 
 
1376
 
    // Check this is a wildcard cert, if not then just compare the strings
1377
 
    if (wildcard < 0)
1378
 
        return cn == hostname;
1379
 
 
1380
 
    int firstCnDot = cn.indexOf(QLatin1Char('.'));
1381
 
    int secondCnDot = cn.indexOf(QLatin1Char('.'), firstCnDot+1);
1382
 
 
1383
 
    // Check at least 3 components
1384
 
    if ((-1 == secondCnDot) || (secondCnDot+1 >= cn.length()))
1385
 
        return false;
1386
 
 
1387
 
    // Check * is last character of 1st component (ie. there's a following .)
1388
 
    if (wildcard+1 != firstCnDot)
1389
 
        return false;
1390
 
 
1391
 
    // Check only one star
1392
 
    if (cn.lastIndexOf(QLatin1Char('*')) != wildcard)
1393
 
        return false;
1394
 
 
1395
 
    // Check characters preceding * (if any) match
1396
 
    if (wildcard && (hostname.leftRef(wildcard) != cn.leftRef(wildcard)))
1397
 
        return false;
1398
 
 
1399
 
    // Check characters following first . match
1400
 
    if (hostname.midRef(hostname.indexOf(QLatin1Char('.'))) != cn.midRef(firstCnDot))
1401
 
        return false;
1402
 
 
1403
 
    // Check if the hostname is an IP address, if so then wildcards are not allowed
1404
 
    QHostAddress addr(hostname);
1405
 
    if (!addr.isNull())
1406
 
        return false;
1407
 
 
1408
 
    // Ok, I guess this was a wildcard CN and the hostname matches.
1409
 
    return true;
1410
 
}
1411
 
 
1412
 
QT_END_NAMESPACE