Coverage Report

Created: 2026-05-31 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qtbase/src/plugins/tls/openssl/qtls_openssl.cpp
Line
Count
Source
1
// Copyright (C) 2021 The Qt Company Ltd.
2
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
// Qt-Security score:critical reason:cryptography
4
5
#include "qsslsocket_openssl_symbols_p.h"
6
#include "qx509_openssl_p.h"
7
#include "qtls_openssl_p.h"
8
9
#ifdef Q_OS_WIN
10
#include "qwindowscarootfetcher_p.h"
11
#endif
12
13
#include <QtNetwork/private/qsslpresharedkeyauthenticator_p.h>
14
#include <QtNetwork/private/qsslcertificate_p.h>
15
#include <QtNetwork/private/qocspresponse_p.h>
16
#include <QtNetwork/private/qsslsocket_p.h>
17
18
#include <QtNetwork/qsslpresharedkeyauthenticator.h>
19
#include <QtNetwork/qsslkeyingmaterial.h>
20
21
#include <QtCore/qscopedvaluerollback.h>
22
#include <QtCore/qscopeguard.h>
23
24
#include <algorithm>
25
#include <cstring>
26
27
QT_BEGIN_NAMESPACE
28
29
using namespace Qt::StringLiterals;
30
31
namespace  {
32
33
QSsl::AlertLevel tlsAlertLevel(int value)
34
0
{
35
0
    using QSsl::AlertLevel;
36
37
0
    if (const char *typeString = q_SSL_alert_type_string(value)) {
38
        // Documented to return 'W' for warning, 'F' for fatal,
39
        // 'U' for unknown.
40
0
        switch (typeString[0]) {
41
0
        case 'W':
42
0
            return AlertLevel::Warning;
43
0
        case 'F':
44
0
            return AlertLevel::Fatal;
45
0
        default:;
46
0
        }
47
0
    }
48
49
0
    return AlertLevel::Unknown;
50
0
}
51
52
QString tlsAlertDescription(int value)
53
0
{
54
0
    QString description = QLatin1StringView(q_SSL_alert_desc_string_long(value));
55
0
    if (!description.size())
56
0
        description = "no description provided"_L1;
57
0
    return description;
58
0
}
59
60
QSsl::AlertType tlsAlertType(int value)
61
0
{
62
    // In case for some reason openssl gives us a value,
63
    // which is not in our enum actually, we leave it to
64
    // an application to handle (supposedly they have
65
    // if or switch-statements).
66
0
    return QSsl::AlertType(value & 0xff);
67
0
}
68
69
#ifdef Q_OS_WIN
70
71
QSslCertificate findCertificateToFetch(const QList<QSslError> &tlsErrors, bool checkAIA)
72
{
73
    QSslCertificate certToFetch;
74
75
    for (const auto &tlsError : tlsErrors) {
76
        switch (tlsError.error()) {
77
        case QSslError::UnableToGetLocalIssuerCertificate: // site presented intermediate cert, but root is unknown
78
        case QSslError::SelfSignedCertificateInChain: // site presented a complete chain, but root is unknown
79
            certToFetch = tlsError.certificate();
80
            break;
81
        case QSslError::SelfSignedCertificate:
82
        case QSslError::CertificateBlacklisted:
83
            //With these errors, we know it will be untrusted so save time by not asking windows
84
            return QSslCertificate{};
85
        default:
86
#ifdef QSSLSOCKET_DEBUG
87
            qCDebug(lcTlsBackend) << tlsError.errorString();
88
#endif
89
            //TODO - this part is strange.
90
            break;
91
        }
92
    }
93
94
    if (checkAIA) {
95
        const auto extensions = certToFetch.extensions();
96
        for (const auto &ext : extensions) {
97
            if (ext.oid() == u"1.3.6.1.5.5.7.1.1") // See RFC 4325
98
                return certToFetch;
99
        }
100
        //The only reason we check this extensions is because an application set trusted
101
        //CA certificates explicitly, thus technically disabling CA fetch. So, if it's
102
        //the case and an intermediate certificate is missing, and no extensions is
103
        //present on the leaf certificate - we fail the handshake immediately.
104
        return QSslCertificate{};
105
    }
106
107
    return certToFetch;
108
}
109
110
#endif // Q_OS_WIN
111
112
} // unnamed namespace
113
114
namespace QTlsPrivate {
115
116
int q_X509Callback(int ok, X509_STORE_CTX *ctx)
117
0
{
118
0
    if (!ok) {
119
        // Store the error and at which depth the error was detected.
120
121
0
        using ErrorListPtr = QList<QSslErrorEntry> *;
122
0
        ErrorListPtr errors = nullptr;
123
124
        // Error list is attached to either 'SSL' or 'X509_STORE'.
125
0
        if (X509_STORE *store = q_X509_STORE_CTX_get0_store(ctx)) // We try store first:
126
0
            errors = ErrorListPtr(q_X509_STORE_get_ex_data(store, 0));
127
128
0
        if (!errors) {
129
            // Not found on store? Try SSL and its external data then. According to the OpenSSL's
130
            // documentation:
131
            //
132
            // "Whenever a X509_STORE_CTX object is created for the verification of the
133
            // peer's certificate during a handshake, a pointer to the SSL object is
134
            // stored into the X509_STORE_CTX object to identify the connection affected.
135
            // To retrieve this pointer the X509_STORE_CTX_get_ex_data() function can be
136
            // used with the correct index."
137
0
            const auto offset = QTlsBackendOpenSSL::s_indexForSSLExtraData
138
0
                    + TlsCryptographOpenSSL::errorOffsetInExData;
139
0
            if (SSL *ssl = static_cast<SSL *>(q_X509_STORE_CTX_get_ex_data(
140
0
                        ctx, q_SSL_get_ex_data_X509_STORE_CTX_idx()))) {
141
142
                // We may be in a renegotiation, check if we are inside a call to SSL_read:
143
0
                const auto tlsOffset = QTlsBackendOpenSSL::s_indexForSSLExtraData
144
0
                        + TlsCryptographOpenSSL::socketOffsetInExData;
145
0
                auto tls = static_cast<TlsCryptographOpenSSL *>(q_SSL_get_ex_data(ssl, tlsOffset));
146
0
                Q_ASSERT(tls);
147
0
                if (tls->isInSslRead()) {
148
                    // We are in a renegotiation, make a note of this for later.
149
                    // We'll check that the certificate is the same as the one we got during
150
                    // the initial handshake
151
0
                    tls->setRenegotiated(true);
152
0
                    return 1;
153
0
                }
154
155
0
                errors = ErrorListPtr(q_SSL_get_ex_data(ssl, offset));
156
0
            }
157
0
        }
158
159
0
        if (!errors) {
160
0
            qCWarning(lcTlsBackend, "Neither X509_STORE, nor SSL contains error list, handshake failure");
161
0
            return 0;
162
0
        }
163
164
0
        errors->append(X509CertificateOpenSSL::errorEntryFromStoreContext(ctx));
165
0
    }
166
    // Always return OK to allow verification to continue. We handle the
167
    // errors gracefully after collecting all errors, after verification has
168
    // completed.
169
0
    return 1;
170
0
}
171
172
int q_X509CallbackDirect(int ok, X509_STORE_CTX *ctx)
173
0
{
174
    // Passed to SSL_CTX_set_verify()
175
    // https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set_verify.html
176
    // Returns 0 to abort verification, 1 to continue.
177
178
    // This is a new, experimental verification callback, reporting
179
    // errors immediately and returning 0 or 1 depending on an application
180
    // either ignoring or not ignoring verification errors as they come.
181
0
    if (!ctx) {
182
0
        qCWarning(lcTlsBackend, "Invalid store context (nullptr)");
183
0
        return 0;
184
0
    }
185
186
0
    if (!ok) {
187
        // "Whenever a X509_STORE_CTX object is created for the verification of the
188
        // peer's certificate during a handshake, a pointer to the SSL object is
189
        // stored into the X509_STORE_CTX object to identify the connection affected.
190
        // To retrieve this pointer the X509_STORE_CTX_get_ex_data() function can be
191
        // used with the correct index."
192
0
        SSL *ssl = static_cast<SSL *>(q_X509_STORE_CTX_get_ex_data(ctx, q_SSL_get_ex_data_X509_STORE_CTX_idx()));
193
0
        if (!ssl) {
194
0
            qCWarning(lcTlsBackend, "No external data (SSL) found in X509 store object");
195
0
            return 0;
196
0
        }
197
198
0
        const auto offset = QTlsBackendOpenSSL::s_indexForSSLExtraData
199
0
                            + TlsCryptographOpenSSL::socketOffsetInExData;
200
0
        auto crypto = static_cast<TlsCryptographOpenSSL *>(q_SSL_get_ex_data(ssl, offset));
201
0
        if (!crypto) {
202
0
            qCWarning(lcTlsBackend, "No external data (TlsCryptographOpenSSL) found in SSL object");
203
0
            return 0;
204
0
        }
205
206
0
        return crypto->emitErrorFromCallback(ctx);
207
0
    }
208
0
    return 1;
209
0
}
210
211
#ifndef OPENSSL_NO_PSK
212
static unsigned q_ssl_psk_client_callback(SSL *ssl, const char *hint, char *identity, unsigned max_identity_len,
213
                                          unsigned char *psk, unsigned max_psk_len)
214
0
{
215
0
    auto *tls = static_cast<TlsCryptographOpenSSL *>(q_SSL_get_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData));
216
0
    return tls->pskClientTlsCallback(hint, identity, max_identity_len, psk, max_psk_len);
217
0
}
218
219
static unsigned int q_ssl_psk_server_callback(SSL *ssl, const char *identity, unsigned char *psk,
220
                                              unsigned int max_psk_len)
221
0
{
222
0
    auto *tls = static_cast<TlsCryptographOpenSSL *>(q_SSL_get_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData));
223
0
    Q_ASSERT(tls);
224
0
    return tls->pskServerTlsCallback(identity, psk, max_psk_len);
225
0
}
226
227
#ifdef TLS1_3_VERSION
228
static unsigned q_ssl_psk_restore_client(SSL *ssl, const char *hint, char *identity, unsigned max_identity_len,
229
                                         unsigned char *psk, unsigned max_psk_len)
230
0
{
231
0
    Q_UNUSED(hint);
232
0
    Q_UNUSED(identity);
233
0
    Q_UNUSED(max_identity_len);
234
0
    Q_UNUSED(psk);
235
0
    Q_UNUSED(max_psk_len);
236
237
0
#ifdef QT_DEBUG
238
0
    auto tls = static_cast<TlsCryptographOpenSSL *>(q_SSL_get_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData));
239
0
    Q_ASSERT(tls);
240
0
    Q_ASSERT(tls->d);
241
0
    Q_ASSERT(tls->d->tlsMode() == QSslSocket::SslClientMode);
242
0
#endif
243
0
    unsigned retVal = 0;
244
245
    // Let developers opt-in to having the normal PSK callback get called for TLS 1.3
246
    // PSK (which works differently in a few ways, and is called at the start of every connection).
247
    // When they do opt-in we just call the old callback from here.
248
0
    if (qEnvironmentVariableIsSet("QT_USE_TLS_1_3_PSK"))
249
0
        retVal = q_ssl_psk_client_callback(ssl, hint, identity, max_identity_len, psk, max_psk_len);
250
251
0
    q_SSL_set_psk_client_callback(ssl, &q_ssl_psk_client_callback);
252
253
0
    return retVal;
254
0
}
255
256
static int q_ssl_psk_use_session_callback(SSL *ssl, const EVP_MD *md, const unsigned char **id,
257
                                          size_t *idlen, SSL_SESSION **sess)
258
0
{
259
0
    Q_UNUSED(md);
260
0
    Q_UNUSED(id);
261
0
    Q_UNUSED(idlen);
262
0
    Q_UNUSED(sess);
263
264
0
#ifdef QT_DEBUG
265
0
    auto *tls = static_cast<TlsCryptographOpenSSL *>(q_SSL_get_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData));
266
0
    Q_ASSERT(tls);
267
0
    Q_ASSERT(tls->d);
268
0
    Q_ASSERT(tls->d->tlsMode() == QSslSocket::SslClientMode);
269
0
#endif
270
271
    // Temporarily rebind the psk because it will be called next. The function will restore it.
272
0
    q_SSL_set_psk_client_callback(ssl, &q_ssl_psk_restore_client);
273
274
0
    return 1; // need to return 1 or else "the connection setup fails."
275
0
}
276
277
int q_ssl_sess_set_new_cb(SSL *ssl, SSL_SESSION *session)
278
0
{
279
0
    if (!ssl) {
280
0
        qCWarning(lcTlsBackend, "Invalid SSL (nullptr)");
281
0
        return 0;
282
0
    }
283
0
    if (!session) {
284
0
        qCWarning(lcTlsBackend, "Invalid SSL_SESSION (nullptr)");
285
0
        return 0;
286
0
    }
287
288
0
    auto *tls = static_cast<TlsCryptographOpenSSL *>(q_SSL_get_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData));
289
0
    Q_ASSERT(tls);
290
0
    return tls->handleNewSessionTicket(ssl);
291
0
}
292
#endif // TLS1_3_VERSION
293
294
#endif // !OPENSSL_NO_PSK
295
296
#if QT_CONFIG(ocsp)
297
298
int qt_OCSP_status_server_callback(SSL *ssl, void *ocspRequest)
299
0
{
300
0
    Q_UNUSED(ocspRequest);
301
0
    if (!ssl)
302
0
        return SSL_TLSEXT_ERR_ALERT_FATAL;
303
304
0
    auto crypto = static_cast<TlsCryptographOpenSSL *>(q_SSL_get_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData));
305
0
    if (!crypto)
306
0
        return SSL_TLSEXT_ERR_ALERT_FATAL;
307
308
0
    Q_ASSERT(crypto->d);
309
0
    Q_ASSERT(crypto->d->tlsMode() == QSslSocket::SslServerMode);
310
0
    const QByteArray &response = crypto->ocspResponseDer;
311
0
    Q_ASSERT(response.size());
312
313
0
    unsigned char *derCopy = static_cast<unsigned char *>(q_OPENSSL_malloc(size_t(response.size())));
314
0
    if (!derCopy)
315
0
        return SSL_TLSEXT_ERR_ALERT_FATAL;
316
317
0
    std::copy(response.data(), response.data() + response.size(), derCopy);
318
    // We don't check the return value: internally OpenSSL simply assigns the
319
    // pointer (it assumes it now owns this memory btw!) and the length.
320
0
    q_SSL_set_tlsext_status_ocsp_resp(ssl, derCopy, response.size());
321
322
0
    return SSL_TLSEXT_ERR_OK;
323
0
}
324
325
#endif // ocsp
326
327
void qt_AlertInfoCallback(const SSL *connection, int from, int value)
328
0
{
329
    // Passed to SSL_set_info_callback()
330
    // https://www.openssl.org/docs/man1.1.1/man3/SSL_set_info_callback.html
331
332
0
    if (!connection) {
333
#ifdef QSSLSOCKET_DEBUG
334
        qCWarning(lcTlsBackend, "Invalid 'connection' parameter (nullptr)");
335
#endif // QSSLSOCKET_DEBUG
336
0
        return;
337
0
    }
338
339
0
    const auto offset = QTlsBackendOpenSSL::s_indexForSSLExtraData
340
0
                        + TlsCryptographOpenSSL::socketOffsetInExData;
341
0
    auto crypto = static_cast<TlsCryptographOpenSSL *>(q_SSL_get_ex_data(connection, offset));
342
0
    if (!crypto) {
343
        // SSL_set_ex_data can fail:
344
#ifdef QSSLSOCKET_DEBUG
345
        qCWarning(lcTlsBackend, "No external data (socket backend) found for parameter 'connection'");
346
#endif // QSSLSOCKET_DEBUG
347
0
        return;
348
0
    }
349
350
0
    if (!(from & SSL_CB_ALERT)) {
351
        // We only want to know about alerts (at least for now).
352
0
        return;
353
0
    }
354
355
0
    if (from & SSL_CB_WRITE)
356
0
        crypto->alertMessageSent(value);
357
0
    else
358
0
        crypto->alertMessageReceived(value);
359
0
}
360
361
#if QT_CONFIG(ocsp)
362
namespace {
363
364
QSslError::SslError qt_OCSP_response_status_to_SslError(long code)
365
0
{
366
0
    switch (code) {
367
0
    case OCSP_RESPONSE_STATUS_MALFORMEDREQUEST:
368
0
        return QSslError::OcspMalformedRequest;
369
0
    case OCSP_RESPONSE_STATUS_INTERNALERROR:
370
0
        return QSslError::OcspInternalError;
371
0
    case OCSP_RESPONSE_STATUS_TRYLATER:
372
0
        return QSslError::OcspTryLater;
373
0
    case OCSP_RESPONSE_STATUS_SIGREQUIRED:
374
0
        return QSslError::OcspSigRequred;
375
0
    case OCSP_RESPONSE_STATUS_UNAUTHORIZED:
376
0
        return QSslError::OcspUnauthorized;
377
0
    case OCSP_RESPONSE_STATUS_SUCCESSFUL:
378
0
    default:
379
0
        return {};
380
0
    }
381
0
    Q_UNREACHABLE();
382
0
}
383
384
QOcspRevocationReason qt_OCSP_revocation_reason(int reason)
385
0
{
386
0
    switch (reason) {
387
0
    case OCSP_REVOKED_STATUS_NOSTATUS:
388
0
        return QOcspRevocationReason::None;
389
0
    case OCSP_REVOKED_STATUS_UNSPECIFIED:
390
0
        return QOcspRevocationReason::Unspecified;
391
0
    case OCSP_REVOKED_STATUS_KEYCOMPROMISE:
392
0
        return QOcspRevocationReason::KeyCompromise;
393
0
    case OCSP_REVOKED_STATUS_CACOMPROMISE:
394
0
        return QOcspRevocationReason::CACompromise;
395
0
    case OCSP_REVOKED_STATUS_AFFILIATIONCHANGED:
396
0
        return QOcspRevocationReason::AffiliationChanged;
397
0
    case OCSP_REVOKED_STATUS_SUPERSEDED:
398
0
        return QOcspRevocationReason::Superseded;
399
0
    case OCSP_REVOKED_STATUS_CESSATIONOFOPERATION:
400
0
        return QOcspRevocationReason::CessationOfOperation;
401
0
    case OCSP_REVOKED_STATUS_CERTIFICATEHOLD:
402
0
        return QOcspRevocationReason::CertificateHold;
403
0
    case OCSP_REVOKED_STATUS_REMOVEFROMCRL:
404
0
        return QOcspRevocationReason::RemoveFromCRL;
405
0
    default:
406
0
        return QOcspRevocationReason::None;
407
0
    }
408
409
0
    Q_UNREACHABLE();
410
0
}
411
412
bool qt_OCSP_certificate_match(OCSP_SINGLERESP *singleResponse, X509 *peerCert, X509 *issuer)
413
0
{
414
    // OCSP_basic_verify does verify that the responder is legit, the response is
415
    // correctly signed, CertID is correct. But it does not know which certificate
416
    // we were presented with by our peer, so it does not check if it's a response
417
    // for our peer's certificate.
418
0
    Q_ASSERT(singleResponse && peerCert && issuer);
419
420
0
    const OCSP_CERTID *certId = q_OCSP_SINGLERESP_get0_id(singleResponse); // Does not increment refcount.
421
0
    if (!certId) {
422
0
        qCWarning(lcTlsBackend, "A SingleResponse without CertID");
423
0
        return false;
424
0
    }
425
426
0
    ASN1_OBJECT *md = nullptr;
427
0
    ASN1_INTEGER *reportedSerialNumber = nullptr;
428
0
    const int result =  q_OCSP_id_get0_info(nullptr, &md, nullptr, &reportedSerialNumber, const_cast<OCSP_CERTID *>(certId));
429
0
    if (result != 1 || !md || !reportedSerialNumber) {
430
0
        qCWarning(lcTlsBackend, "Failed to extract a hash and serial number from CertID structure");
431
0
        return false;
432
0
    }
433
434
0
    if (!q_X509_get_serialNumber(peerCert)) {
435
        // Is this possible at all? But we have to check this,
436
        // ASN1_INTEGER_cmp (called from OCSP_id_cmp) dereferences
437
        // without any checks at all.
438
0
        qCWarning(lcTlsBackend, "No serial number in peer's ceritificate");
439
0
        return false;
440
0
    }
441
442
0
    const int nid = q_OBJ_obj2nid(md);
443
0
    if (nid == NID_undef) {
444
0
        qCWarning(lcTlsBackend, "Unknown hash algorithm in CertID");
445
0
        return false;
446
0
    }
447
448
0
    const EVP_MD *digest = q_EVP_get_digestbynid(nid); // Does not increment refcount.
449
0
    if (!digest) {
450
0
        qCWarning(lcTlsBackend) << "No digest for nid" << nid;
451
0
        return false;
452
0
    }
453
454
0
    OCSP_CERTID *recreatedId = q_OCSP_cert_to_id(digest, peerCert, issuer);
455
0
    if (!recreatedId) {
456
0
        qCWarning(lcTlsBackend, "Failed to re-create CertID");
457
0
        return false;
458
0
    }
459
0
    const QSharedPointer<OCSP_CERTID> guard(recreatedId, q_OCSP_CERTID_free);
460
461
0
    if (q_OCSP_id_cmp(const_cast<OCSP_CERTID *>(certId), recreatedId)) {
462
0
        qCDebug(lcTlsBackend, "Certificate ID mismatch");
463
0
        return false;
464
0
    }
465
    // Bingo!
466
0
    return true;
467
0
}
468
469
} // unnamed namespace
470
#endif // ocsp
471
472
TlsCryptographOpenSSL::~TlsCryptographOpenSSL()
473
0
{
474
0
    destroySslContext();
475
0
}
476
477
void TlsCryptographOpenSSL::init(QSslSocket *qObj, QSslSocketPrivate *dObj)
478
0
{
479
0
    Q_ASSERT(qObj);
480
0
    Q_ASSERT(dObj);
481
0
    q = qObj;
482
0
    d = dObj;
483
484
0
    ocspResponses.clear();
485
0
    ocspResponseDer.clear();
486
487
0
    systemOrSslErrorDetected = false;
488
0
    handshakeInterrupted = false;
489
490
0
    fetchAuthorityInformation = false;
491
0
    caToFetch.reset();
492
0
}
493
494
void TlsCryptographOpenSSL::checkSettingSslContext(std::shared_ptr<QSslContext> tlsContext)
495
0
{
496
0
    if (!sslContextPointer)
497
0
        sslContextPointer = std::move(tlsContext);
498
0
}
499
500
std::shared_ptr<QSslContext> TlsCryptographOpenSSL::sslContext() const
501
0
{
502
0
    return sslContextPointer;
503
0
}
504
505
QList<QSslError> TlsCryptographOpenSSL::tlsErrors() const
506
0
{
507
0
    return sslErrors;
508
0
}
509
510
void TlsCryptographOpenSSL::startClientEncryption()
511
0
{
512
0
    if (!initSslContext()) {
513
0
        Q_ASSERT(d);
514
0
        setErrorAndEmit(d, QAbstractSocket::SslInternalError,
515
0
                        QSslSocket::tr("Unable to init SSL Context: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
516
0
        return;
517
0
    }
518
519
    // Start connecting. This will place outgoing data in the BIO, so we
520
    // follow up with calling transmit().
521
0
    startHandshake();
522
0
    transmit();
523
0
}
524
525
void TlsCryptographOpenSSL::startServerEncryption()
526
0
{
527
0
    if (!initSslContext()) {
528
0
        Q_ASSERT(d);
529
0
        setErrorAndEmit(d, QAbstractSocket::SslInternalError,
530
0
                        QSslSocket::tr("Unable to init SSL Context: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
531
0
        return;
532
0
    }
533
534
    // Start connecting. This will place outgoing data in the BIO, so we
535
    // follow up with calling transmit().
536
0
    startHandshake();
537
0
    transmit();
538
0
}
539
540
bool TlsCryptographOpenSSL::startHandshake()
541
0
{
542
    // Check if the connection has been established. Get all errors from the
543
    // verification stage.
544
0
    Q_ASSERT(q);
545
0
    Q_ASSERT(d);
546
547
0
    using ScopedBool = QScopedValueRollback<bool>;
548
549
0
    if (inSetAndEmitError)
550
0
        return false;
551
552
0
    const auto mode = d->tlsMode();
553
554
0
    pendingFatalAlert = false;
555
0
    errorsReportedFromCallback = false;
556
0
    QList<QSslErrorEntry> lastErrors;
557
0
    q_SSL_set_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData + errorOffsetInExData, &lastErrors);
558
559
    // SSL_set_ex_data can fail, but see the callback's code - we handle this there.
560
0
    q_SSL_set_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData + socketOffsetInExData, this);
561
0
    q_SSL_set_info_callback(ssl, qt_AlertInfoCallback);
562
563
0
    int result = (mode == QSslSocket::SslClientMode) ? q_SSL_connect(ssl) : q_SSL_accept(ssl);
564
0
    q_SSL_set_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData + errorOffsetInExData, nullptr);
565
    // Note, unlike errors as external data on SSL object, we do not unset
566
    // a callback/ex-data if alert notifications are enabled: an alert can
567
    // arrive after the handshake, for example, this happens when the server
568
    // does not find a ClientCert or does not like it.
569
570
0
    if (!lastErrors.isEmpty() || errorsReportedFromCallback)
571
0
        storePeerCertificates();
572
573
    // storePeerCertificate() if called above - would update the
574
    // configuration with peer's certificates.
575
0
    auto configuration = q->sslConfiguration();
576
0
    if (!errorsReportedFromCallback) {
577
0
        const auto &peerCertificateChain = configuration.peerCertificateChain();
578
0
        for (const auto &currentError : std::as_const(lastErrors)) {
579
0
            emit q->peerVerifyError(QTlsPrivate::X509CertificateOpenSSL::openSSLErrorToQSslError(currentError.code,
580
0
                                    peerCertificateChain.value(currentError.depth)));
581
0
            if (q->state() != QAbstractSocket::ConnectedState)
582
0
                break;
583
0
        }
584
0
    }
585
586
0
    errorList << lastErrors;
587
588
    // Connection aborted during handshake phase.
589
0
    if (q->state() != QAbstractSocket::ConnectedState)
590
0
        return false;
591
592
    // Check if we're encrypted or not.
593
0
    if (result <= 0) {
594
0
        switch (q_SSL_get_error(ssl, result)) {
595
0
        case SSL_ERROR_WANT_READ:
596
0
        case SSL_ERROR_WANT_WRITE:
597
            // The handshake is not yet complete.
598
0
            break;
599
0
        default:
600
0
            QString errorString = QTlsBackendOpenSSL::msgErrorsDuringHandshake();
601
#ifdef QSSLSOCKET_DEBUG
602
            qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::startHandshake: error!" << errorString;
603
#endif
604
0
            {
605
0
                const ScopedBool bg(inSetAndEmitError, true);
606
0
                setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, errorString);
607
0
                if (pendingFatalAlert) {
608
0
                    trySendFatalAlert();
609
0
                    pendingFatalAlert = false;
610
0
                }
611
0
            }
612
0
            q->abort();
613
0
        }
614
0
        return false;
615
0
    }
616
617
    // store peer certificate chain
618
0
    storePeerCertificates();
619
620
    // Start translating errors.
621
0
    QList<QSslError> errors;
622
623
    // Note, the storePeerCerificates() probably updated the configuration at this point.
624
0
    configuration = q->sslConfiguration();
625
    // Check the whole chain for blacklisting (including root, as we check for subjectInfo and issuer)
626
0
    const auto &peerCertificateChain = configuration.peerCertificateChain();
627
0
    for (const QSslCertificate &cert : peerCertificateChain) {
628
0
        if (QSslCertificatePrivate::isBlacklisted(cert)) {
629
0
            QSslError error(QSslError::CertificateBlacklisted, cert);
630
0
            errors << error;
631
0
            emit q->peerVerifyError(error);
632
0
            if (q->state() != QAbstractSocket::ConnectedState)
633
0
                return false;
634
0
        }
635
0
    }
636
637
0
    const bool doVerifyPeer = configuration.peerVerifyMode() == QSslSocket::VerifyPeer
638
0
                              || (configuration.peerVerifyMode() == QSslSocket::AutoVerifyPeer
639
0
                                  && mode == QSslSocket::SslClientMode);
640
641
0
#if QT_CONFIG(ocsp)
642
    // For now it's always QSslSocket::SslClientMode - initSslContext() will bail out early,
643
    // if it's enabled in QSslSocket::SslServerMode. This can change.
644
0
    if (!configuration.peerCertificate().isNull() && configuration.ocspStaplingEnabled() && doVerifyPeer) {
645
0
        if (!checkOcspStatus()) {
646
0
            if (ocspErrors.isEmpty()) {
647
0
                {
648
0
                    const ScopedBool bg(inSetAndEmitError, true);
649
0
                    setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, ocspErrorDescription);
650
0
                }
651
0
                q->abort();
652
0
                return false;
653
0
            }
654
655
0
            for (const QSslError &error : ocspErrors) {
656
0
                errors << error;
657
0
                emit q->peerVerifyError(error);
658
0
                if (q->state() != QAbstractSocket::ConnectedState)
659
0
                    return false;
660
0
            }
661
0
        }
662
0
    }
663
0
#endif // ocsp
664
665
    // Check the peer certificate itself. First try the subject's common name
666
    // (CN) as a wildcard, then try all alternate subject name DNS entries the
667
    // same way.
668
0
    if (!configuration.peerCertificate().isNull()) {
669
        // but only if we're a client connecting to a server
670
        // if we're the server, don't check CN
671
0
        const auto verificationPeerName = d->verificationName();
672
0
        if (mode == QSslSocket::SslClientMode) {
673
0
            QString peerName = (verificationPeerName.isEmpty () ? q->peerName() : verificationPeerName);
674
675
0
            if (!isMatchingHostname(configuration.peerCertificate(), peerName)) {
676
                // No matches in common names or alternate names.
677
0
                QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate());
678
0
                errors << error;
679
0
                emit q->peerVerifyError(error);
680
0
                if (q->state() != QAbstractSocket::ConnectedState)
681
0
                    return false;
682
0
            }
683
0
        }
684
0
    } else {
685
        // No peer certificate presented. Report as error if the socket
686
        // expected one.
687
0
        if (doVerifyPeer) {
688
0
            QSslError error(QSslError::NoPeerCertificate);
689
0
            errors << error;
690
0
            emit q->peerVerifyError(error);
691
0
            if (q->state() != QAbstractSocket::ConnectedState)
692
0
                return false;
693
0
        }
694
0
    }
695
696
    // Translate errors from the error list into QSslErrors.
697
0
    errors.reserve(errors.size() + errorList.size());
698
0
    for (const auto &error : std::as_const(errorList))
699
0
        errors << X509CertificateOpenSSL::openSSLErrorToQSslError(error.code, peerCertificateChain.value(error.depth));
700
701
0
    if (!errors.isEmpty()) {
702
0
        sslErrors = errors;
703
#ifdef Q_OS_WIN
704
        const bool fetchEnabled = QSslSocketPrivate::rootCertOnDemandLoadingSupported()
705
                                  && d->isRootsOnDemandAllowed();
706
        // !fetchEnabled is a special case scenario, when we potentially have a missing
707
        // intermediate certificate and a recoverable chain, but on demand cert loading
708
        // was disabled by setCaCertificates call. For this scenario we check if "Authority
709
        // Information Access" is present - wincrypt can deal with such certificates.
710
        QSslCertificate certToFetch;
711
        if (doVerifyPeer && !d->verifyErrorsHaveBeenIgnored())
712
            certToFetch = findCertificateToFetch(sslErrors, !fetchEnabled);
713
714
        //Skip this if not using system CAs, or if the SSL errors are configured in advance to be ignorable
715
        if (!certToFetch.isNull()) {
716
            fetchAuthorityInformation = !fetchEnabled;
717
            //Windows desktop versions starting from vista ship with minimal set of roots and download on demand
718
            //from the windows update server CA roots that are trusted by MS. It also can fetch a missing intermediate
719
            //in case "Authority Information Access" extension is present.
720
            //
721
            //However, this is only transparent if using WinINET - we have to trigger it
722
            //ourselves.
723
            fetchCaRootForCert(certToFetch);
724
            return false;
725
        }
726
#endif // Q_OS_WIN
727
0
        if (!checkSslErrors())
728
0
            return false;
729
        // A slot, attached to sslErrors signal can call
730
        // abort/close/disconnetFromHost/etc; no need to
731
        // continue handshake then.
732
0
        if (q->state() != QAbstractSocket::ConnectedState)
733
0
            return false;
734
0
    } else {
735
0
        sslErrors.clear();
736
0
    }
737
738
0
    continueHandshake();
739
0
    return true;
740
0
}
741
742
void TlsCryptographOpenSSL::enableHandshakeContinuation()
743
0
{
744
0
    handshakeInterrupted = false;
745
0
}
746
747
void TlsCryptographOpenSSL::cancelCAFetch()
748
0
{
749
0
    fetchAuthorityInformation = false;
750
0
    caToFetch.reset();
751
0
}
752
753
void TlsCryptographOpenSSL::exportKeyingMaterial()
754
0
{
755
0
    auto sslCfg = q->sslConfiguration();
756
0
    auto list = sslCfg.keyingMaterial();
757
758
0
    for (auto &entry : list) {
759
0
        if (!entry.isValid()) {
760
#ifdef QSSLSOCKET_DEBUG
761
            qCDebug(lcTlsBackend) << "keying material request is invalid:" << entry;
762
#endif
763
0
            continue;
764
0
        }
765
766
        /*
767
         * https://docs.openssl.org/1.1.1/man3/SSL_export_keying_material/
768
         * Note that in TLSv1.2 and below a zero length context is treated
769
         * differently from no context at all, and will result in different
770
         * keying material being returned. In TLSv1.3 a zero length context
771
         * is that same as no context at all and will result in the same
772
         * keying material being returned.
773
         */
774
0
        const auto context = entry.context();
775
0
        const auto label = entry.label();
776
0
        if (QByteArray output(entry.keyingValueSize, Qt::Uninitialized);
777
0
            q_SSL_export_keying_material(ssl,
778
0
                                         reinterpret_cast<unsigned char*>(output.data_ptr().data()),
779
0
                                         entry.keyingValueSize,
780
0
                                         label.data(),
781
0
                                         label.size(),
782
0
                                         reinterpret_cast<const unsigned char*>(context.data()),
783
0
                                         context.size(),
784
0
                                         context.isNull() ? 0 : 1))
785
0
        {
786
0
            entry.keyingValue = std::move(output);
787
#ifdef QSSLSOCKET_DEBUG
788
        } else {
789
            qCDebug(lcTlsBackend) << "cannot export keying material:" << entry;
790
#endif
791
0
        }
792
0
    }
793
794
0
    sslCfg.setKeyingMaterial(list);
795
0
    q->setSslConfiguration(sslCfg);
796
0
}
797
798
void TlsCryptographOpenSSL::continueHandshake()
799
0
{
800
0
    Q_ASSERT(q);
801
0
    Q_ASSERT(d);
802
803
0
    auto *plainSocket = d->plainTcpSocket();
804
0
    Q_ASSERT(plainSocket);
805
806
0
    const auto mode = d->tlsMode();
807
808
    // if we have a max read buffer size, reset the plain socket's to match
809
0
    if (const auto maxSize = d->maxReadBufferSize())
810
0
        plainSocket->setReadBufferSize(maxSize);
811
812
0
    if (q_SSL_session_reused(ssl))
813
0
        QTlsBackend::setPeerSessionShared(d, true);
814
815
#ifdef QT_DECRYPT_SSL_TRAFFIC
816
    if (q_SSL_get_session(ssl)) {
817
        size_t master_key_len = q_SSL_SESSION_get_master_key(q_SSL_get_session(ssl), nullptr, 0);
818
        size_t client_random_len = q_SSL_get_client_random(ssl, nullptr, 0);
819
        QByteArray masterKey(int(master_key_len), Qt::Uninitialized); // Will not overflow
820
        QByteArray clientRandom(int(client_random_len), Qt::Uninitialized); // Will not overflow
821
822
        q_SSL_SESSION_get_master_key(q_SSL_get_session(ssl),
823
                                     reinterpret_cast<unsigned char*>(masterKey.data()),
824
                                     masterKey.size());
825
        q_SSL_get_client_random(ssl, reinterpret_cast<unsigned char *>(clientRandom.data()),
826
                                clientRandom.size());
827
828
        QByteArray debugLineClientRandom("CLIENT_RANDOM ");
829
        debugLineClientRandom.append(clientRandom.toHex().toUpper());
830
        debugLineClientRandom.append(" ");
831
        debugLineClientRandom.append(masterKey.toHex().toUpper());
832
        debugLineClientRandom.append("\n");
833
834
        QString sslKeyFile = QDir::tempPath() + "/qt-ssl-keys"_L1;
835
        QFile file(sslKeyFile);
836
        if (!file.open(QIODevice::Append))
837
            qCWarning(lcTlsBackend) << "could not open file" << sslKeyFile << "for appending";
838
        if (!file.write(debugLineClientRandom))
839
            qCWarning(lcTlsBackend) << "could not write to file" << sslKeyFile;
840
        file.close();
841
    } else {
842
        qCWarning(lcTlsBackend, "could not decrypt SSL traffic");
843
    }
844
#endif // QT_DECRYPT_SSL_TRAFFIC
845
846
0
    const auto &configuration = q->sslConfiguration();
847
    // Cache this SSL session inside the QSslContext
848
0
    if (!(configuration.testSslOption(QSsl::SslOptionDisableSessionSharing))) {
849
0
        if (!sslContextPointer->cacheSession(ssl)) {
850
0
            sslContextPointer.reset(); // we could not cache the session
851
0
        } else {
852
            // Cache the session for permanent usage as well
853
0
            if (!(configuration.testSslOption(QSsl::SslOptionDisableSessionPersistence))) {
854
0
                if (!sslContextPointer->sessionASN1().isEmpty())
855
0
                    QTlsBackend::setSessionAsn1(d, sslContextPointer->sessionASN1());
856
0
                QTlsBackend::setSessionLifetimeHint(d, sslContextPointer->sessionTicketLifeTimeHint());
857
0
            }
858
0
        }
859
0
    }
860
861
0
#if !defined(OPENSSL_NO_NEXTPROTONEG)
862
863
0
    QTlsBackend::setAlpnStatus(d, sslContextPointer->npnContext().status);
864
0
    if (sslContextPointer->npnContext().status == QSslConfiguration::NextProtocolNegotiationUnsupported) {
865
        // we could not agree -> be conservative and use HTTP/1.1
866
        // T.P.: I have to admit, this is a really strange notion of 'conservative',
867
        // given the protocol-neutral nature of ALPN/NPN.
868
0
        QTlsBackend::setNegotiatedProtocol(d, QByteArrayLiteral("http/1.1"));
869
0
    } else {
870
0
        const unsigned char *proto = nullptr;
871
0
        unsigned int proto_len = 0;
872
873
0
        q_SSL_get0_alpn_selected(ssl, &proto, &proto_len);
874
0
        if (proto_len && mode == QSslSocket::SslClientMode) {
875
            // Client does not have a callback that sets it ...
876
0
            QTlsBackend::setAlpnStatus(d, QSslConfiguration::NextProtocolNegotiationNegotiated);
877
0
        }
878
879
0
        if (!proto_len) { // Test if NPN was more lucky ...
880
0
            q_SSL_get0_next_proto_negotiated(ssl, &proto, &proto_len);
881
0
        }
882
883
0
        if (proto_len)
884
0
            QTlsBackend::setNegotiatedProtocol(d, QByteArray(reinterpret_cast<const char *>(proto), proto_len));
885
0
        else
886
0
            QTlsBackend::setNegotiatedProtocol(d,{});
887
0
    }
888
0
#endif // !defined(OPENSSL_NO_NEXTPROTONEG)
889
890
0
    if (mode == QSslSocket::SslClientMode) {
891
0
        EVP_PKEY *key;
892
0
        if (q_SSL_get_server_tmp_key(ssl, &key))
893
0
            QTlsBackend::setEphemeralKey(d, QSslKey(key, QSsl::PublicKey));
894
0
    }
895
896
0
    exportKeyingMaterial();
897
898
0
    d->setEncrypted(true);
899
0
    emit q->encrypted();
900
0
    if (d->isAutoStartingHandshake() && d->isPendingClose()) {
901
0
        d->setPendingClose(false);
902
0
        q->disconnectFromHost();
903
0
    }
904
0
}
905
906
void TlsCryptographOpenSSL::transmit()
907
0
{
908
0
    Q_ASSERT(q);
909
0
    Q_ASSERT(d);
910
911
0
    using ScopedBool = QScopedValueRollback<bool>;
912
913
0
    if (inSetAndEmitError)
914
0
        return;
915
916
    // If we don't have any SSL context, don't bother transmitting.
917
0
    if (!ssl)
918
0
        return;
919
920
0
    auto &writeBuffer = d->tlsWriteBuffer();
921
0
    auto &buffer = d->tlsBuffer();
922
0
    auto *plainSocket = d->plainTcpSocket();
923
0
    Q_ASSERT(plainSocket);
924
0
    bool &emittedBytesWritten = d->tlsEmittedBytesWritten();
925
926
0
    bool transmitting;
927
0
    do {
928
0
        transmitting = false;
929
930
        // If the connection is secure, we can transfer data from the write
931
        // buffer (in plain text) to the write BIO through SSL_write.
932
0
        if (q->isEncrypted() && !writeBuffer.isEmpty()) {
933
0
            qint64 totalBytesWritten = 0;
934
0
            int nextDataBlockSize;
935
0
            while ((nextDataBlockSize = writeBuffer.nextDataBlockSize()) > 0) {
936
0
                int writtenBytes = q_SSL_write(ssl, writeBuffer.readPointer(), nextDataBlockSize);
937
0
                if (writtenBytes <= 0) {
938
0
                    int error = q_SSL_get_error(ssl, writtenBytes);
939
                    //write can result in a want_write_error - not an error - continue transmitting
940
0
                    if (error == SSL_ERROR_WANT_WRITE) {
941
0
                        transmitting = true;
942
0
                        break;
943
0
                    } else if (error == SSL_ERROR_WANT_READ) {
944
                        //write can result in a want_read error, possibly due to renegotiation - not an error - stop transmitting
945
0
                        transmitting = false;
946
0
                        break;
947
0
                    } else {
948
                        // ### Better error handling.
949
0
                        const ScopedBool bg(inSetAndEmitError, true);
950
0
                        setErrorAndEmit(d, QAbstractSocket::SslInternalError,
951
0
                                        QSslSocket::tr("Unable to write data: %1").arg(
952
0
                                        QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
953
0
                        return;
954
0
                    }
955
0
                }
956
#ifdef QSSLSOCKET_DEBUG
957
                qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: encrypted" << writtenBytes << "bytes";
958
#endif
959
0
                writeBuffer.free(writtenBytes);
960
0
                totalBytesWritten += writtenBytes;
961
962
0
                if (writtenBytes < nextDataBlockSize) {
963
                    // break out of the writing loop and try again after we had read
964
0
                    transmitting = true;
965
0
                    break;
966
0
                }
967
0
            }
968
969
0
            if (totalBytesWritten > 0) {
970
                // Don't emit bytesWritten() recursively.
971
0
                if (!emittedBytesWritten) {
972
0
                    emittedBytesWritten = true;
973
0
                    emit q->bytesWritten(totalBytesWritten);
974
0
                    emittedBytesWritten = false;
975
0
                }
976
0
                emit q->channelBytesWritten(0, totalBytesWritten);
977
0
            }
978
0
        }
979
980
        // Check if we've got any data to be written to the socket.
981
0
        QVarLengthArray<char, 4096> data;
982
0
        int pendingBytes;
983
0
        while (plainSocket->isValid() && (pendingBytes = q_BIO_pending(writeBio)) > 0
984
0
                && plainSocket->openMode() != QIODevice::NotOpen) {
985
            // Read encrypted data from the write BIO into a buffer.
986
0
            data.resize(pendingBytes);
987
0
            int encryptedBytesRead = q_BIO_read(writeBio, data.data(), pendingBytes);
988
989
            // Write encrypted data from the buffer to the socket.
990
0
            qint64 actualWritten = plainSocket->write(data.constData(), encryptedBytesRead);
991
#ifdef QSSLSOCKET_DEBUG
992
            qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: wrote" << encryptedBytesRead
993
                                  << "encrypted bytes to the socket" << actualWritten << "actual.";
994
#endif
995
0
            if (actualWritten < 0) {
996
                //plain socket write fails if it was in the pending close state.
997
0
                const ScopedBool bg(inSetAndEmitError, true);
998
0
                setErrorAndEmit(d, plainSocket->error(), plainSocket->errorString());
999
0
                return;
1000
0
            }
1001
0
            transmitting = true;
1002
0
        }
1003
1004
        // Check if we've got any data to be read from the socket.
1005
0
        if (!q->isEncrypted() || !d->maxReadBufferSize() || buffer.size() < d->maxReadBufferSize())
1006
0
            while ((pendingBytes = plainSocket->bytesAvailable()) > 0) {
1007
                // Read encrypted data from the socket into a buffer.
1008
0
                data.resize(pendingBytes);
1009
                // just peek() here because q_BIO_write could write less data than expected
1010
0
                int encryptedBytesRead = plainSocket->peek(data.data(), pendingBytes);
1011
1012
#ifdef QSSLSOCKET_DEBUG
1013
                qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: read" << encryptedBytesRead << "encrypted bytes from the socket";
1014
#endif
1015
                // Write encrypted data from the buffer into the read BIO.
1016
0
                int writtenToBio = q_BIO_write(readBio, data.constData(), encryptedBytesRead);
1017
1018
                // Throw away the results.
1019
0
                if (writtenToBio > 0) {
1020
0
                    plainSocket->skip(writtenToBio);
1021
0
                } else {
1022
                    // ### Better error handling.
1023
0
                    const ScopedBool bg(inSetAndEmitError, true);
1024
0
                    setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1025
0
                                    QSslSocket::tr("Unable to decrypt data: %1")
1026
0
                                    .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1027
0
                    return;
1028
0
                }
1029
1030
0
                transmitting = true;
1031
0
            }
1032
1033
        // If the connection isn't secured yet, this is the time to retry the
1034
        // connect / accept.
1035
0
        if (!q->isEncrypted()) {
1036
#ifdef QSSLSOCKET_DEBUG
1037
            qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: testing encryption";
1038
#endif
1039
0
            if (startHandshake()) {
1040
#ifdef QSSLSOCKET_DEBUG
1041
                qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: encryption established";
1042
#endif
1043
0
                d->setEncrypted(true);
1044
0
                transmitting = true;
1045
0
            } else if (plainSocket->state() != QAbstractSocket::ConnectedState) {
1046
#ifdef QSSLSOCKET_DEBUG
1047
                qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: connection lost";
1048
#endif
1049
0
                break;
1050
0
            } else if (d->isPaused()) {
1051
                // just wait until the user continues
1052
0
                return;
1053
0
            } else {
1054
#ifdef QSSLSOCKET_DEBUG
1055
                qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: encryption not done yet";
1056
#endif
1057
0
            }
1058
0
        }
1059
1060
        // If the request is small and the remote host closes the transmission
1061
        // after sending, there's a chance that startHandshake() will already
1062
        // have triggered a shutdown.
1063
0
        if (!ssl)
1064
0
            continue;
1065
1066
        // We always read everything from the SSL decryption buffers, even if
1067
        // we have a readBufferMaxSize. There's no point in leaving data there
1068
        // just so that readBuffer.size() == readBufferMaxSize.
1069
0
        int readBytes = 0;
1070
0
        const int bytesToRead = 4096;
1071
0
        do {
1072
0
            if (q->readChannelCount() == 0) {
1073
                // The read buffer is deallocated, don't try resize or write to it.
1074
0
                break;
1075
0
            }
1076
            // Don't use SSL_pending(). It's very unreliable.
1077
0
            inSslRead = true;
1078
0
            readBytes = q_SSL_read(ssl, buffer.reserve(bytesToRead), bytesToRead);
1079
0
            inSslRead = false;
1080
0
            if (renegotiated) {
1081
0
                renegotiated = false;
1082
0
                X509 *x509 = q_SSL_get_peer_certificate(ssl);
1083
0
                const auto peerCertificate =
1084
0
                        QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1085
                // Fail the renegotiate if the certificate has changed, else: continue.
1086
0
                if (peerCertificate != q->peerCertificate()) {
1087
0
                    const ScopedBool bg(inSetAndEmitError, true);
1088
0
                    setErrorAndEmit(
1089
0
                            d, QAbstractSocket::RemoteHostClosedError,
1090
0
                            QSslSocket::tr(
1091
0
                                    "TLS certificate unexpectedly changed during renegotiation!"));
1092
0
                    q->abort();
1093
0
                    return;
1094
0
                }
1095
0
            }
1096
0
            if (readBytes > 0) {
1097
#ifdef QSSLSOCKET_DEBUG
1098
                qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: decrypted" << readBytes << "bytes";
1099
#endif
1100
0
                buffer.chop(bytesToRead - readBytes);
1101
1102
0
                if (bool *readyReadEmittedPointer = d->readyReadPointer())
1103
0
                    *readyReadEmittedPointer = true;
1104
0
                emit q->readyRead();
1105
0
                emit q->channelReadyRead(0);
1106
0
                transmitting = true;
1107
0
                continue;
1108
0
            }
1109
0
            buffer.chop(bytesToRead);
1110
1111
            // Error.
1112
0
            switch (q_SSL_get_error(ssl, readBytes)) {
1113
0
            case SSL_ERROR_WANT_READ:
1114
0
            case SSL_ERROR_WANT_WRITE:
1115
                // Out of data.
1116
0
                break;
1117
0
            case SSL_ERROR_ZERO_RETURN:
1118
                // The remote host closed the connection.
1119
#ifdef QSSLSOCKET_DEBUG
1120
                qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: remote disconnect";
1121
#endif
1122
0
                shutdown = true; // the other side shut down, make sure we do not send shutdown ourselves
1123
0
                {
1124
0
                    const ScopedBool bg(inSetAndEmitError, true);
1125
0
                    setErrorAndEmit(d, QAbstractSocket::RemoteHostClosedError,
1126
0
                                    QSslSocket::tr("The TLS/SSL connection has been closed"));
1127
0
                }
1128
0
                return;
1129
0
            case SSL_ERROR_SYSCALL: // some IO error
1130
0
            case SSL_ERROR_SSL: // error in the SSL library
1131
                // we do not know exactly what the error is, nor whether we can recover from it,
1132
                // so just return to prevent an endless loop in the outer "while" statement
1133
0
                systemOrSslErrorDetected = true;
1134
0
                {
1135
0
                    const ScopedBool bg(inSetAndEmitError, true);
1136
0
                    setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1137
0
                                    QSslSocket::tr("Error while reading: %1")
1138
0
                                    .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1139
0
                }
1140
0
                return;
1141
0
            default:
1142
                // SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT: can only happen with a
1143
                // BIO_s_connect() or BIO_s_accept(), which we do not call.
1144
                // SSL_ERROR_WANT_X509_LOOKUP: can only happen with a
1145
                // SSL_CTX_set_client_cert_cb(), which we do not call.
1146
                // So this default case should never be triggered.
1147
0
                {
1148
0
                    const ScopedBool bg(inSetAndEmitError, true);
1149
0
                    setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1150
0
                                    QSslSocket::tr("Error while reading: %1")
1151
0
                                    .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1152
0
                }
1153
0
                break;
1154
0
            }
1155
0
        } while (ssl && readBytes > 0);
1156
0
    } while (ssl && transmitting);
1157
0
}
1158
1159
void TlsCryptographOpenSSL::disconnectFromHost()
1160
0
{
1161
0
    if (ssl) {
1162
0
        if (!shutdown && !q_SSL_in_init(ssl) && !systemOrSslErrorDetected) {
1163
0
            if (q_SSL_shutdown(ssl) != 1) {
1164
                // Some error may be queued, clear it.
1165
0
                QTlsBackendOpenSSL::clearErrorQueue();
1166
0
            }
1167
0
            shutdown = true;
1168
0
            transmit();
1169
0
        }
1170
0
    }
1171
0
    Q_ASSERT(d);
1172
0
    auto *plainSocket = d->plainTcpSocket();
1173
0
    Q_ASSERT(plainSocket);
1174
0
    plainSocket->disconnectFromHost();
1175
0
}
1176
1177
void TlsCryptographOpenSSL::disconnected()
1178
0
{
1179
0
    Q_ASSERT(d);
1180
0
    auto *plainSocket = d->plainTcpSocket();
1181
0
    Q_ASSERT(plainSocket);
1182
0
    d->setEncrypted(false);
1183
1184
0
    if (plainSocket->bytesAvailable() <= 0) {
1185
0
        destroySslContext();
1186
0
    } else {
1187
        // Move all bytes into the plain buffer.
1188
0
        const qint64 tmpReadBufferMaxSize = d->maxReadBufferSize();
1189
        // Reset temporarily, so the plain socket buffer is completely drained:
1190
0
        d->setMaxReadBufferSize(0);
1191
0
        transmit();
1192
0
        d->setMaxReadBufferSize(tmpReadBufferMaxSize);
1193
0
    }
1194
    //if there is still buffered data in the plain socket, don't destroy the ssl context yet.
1195
    //it will be destroyed when the socket is deleted.
1196
0
}
1197
1198
QSslCipher TlsCryptographOpenSSL::sessionCipher() const
1199
0
{
1200
0
    if (!ssl)
1201
0
        return {};
1202
1203
0
    const SSL_CIPHER *sessionCipher = q_SSL_get_current_cipher(ssl);
1204
0
    return sessionCipher ? QTlsBackendOpenSSL::qt_OpenSSL_cipher_to_QSslCipher(sessionCipher) : QSslCipher{};
1205
0
}
1206
1207
QSsl::SslProtocol TlsCryptographOpenSSL::sessionProtocol() const
1208
0
{
1209
0
    if (!ssl)
1210
0
        return QSsl::UnknownProtocol;
1211
1212
0
    const int ver = q_SSL_version(ssl);
1213
0
    switch (ver) {
1214
0
QT_WARNING_PUSH
1215
0
QT_WARNING_DISABLE_DEPRECATED
1216
0
    case 0x301:
1217
0
        return QSsl::TlsV1_0;
1218
0
    case 0x302:
1219
0
        return QSsl::TlsV1_1;
1220
0
QT_WARNING_POP
1221
0
    case 0x303:
1222
0
        return QSsl::TlsV1_2;
1223
0
    case 0x304:
1224
0
        return QSsl::TlsV1_3;
1225
0
    }
1226
1227
0
    return QSsl::UnknownProtocol;
1228
0
}
1229
1230
QList<QOcspResponse> TlsCryptographOpenSSL::ocsps() const
1231
0
{
1232
0
    return ocspResponses;
1233
0
}
1234
1235
bool TlsCryptographOpenSSL::checkSslErrors()
1236
0
{
1237
0
    Q_ASSERT(q);
1238
0
    Q_ASSERT(d);
1239
1240
0
    if (sslErrors.isEmpty())
1241
0
        return true;
1242
1243
0
    emit q->sslErrors(sslErrors);
1244
1245
0
    const auto vfyMode = q->peerVerifyMode();
1246
0
    const auto mode = d->tlsMode();
1247
1248
0
    bool doVerifyPeer = vfyMode == QSslSocket::VerifyPeer || (vfyMode == QSslSocket::AutoVerifyPeer
1249
0
                                                               && mode == QSslSocket::SslClientMode);
1250
0
    bool doEmitSslError = !d->verifyErrorsHaveBeenIgnored();
1251
    // check whether we need to emit an SSL handshake error
1252
0
    if (doVerifyPeer && doEmitSslError) {
1253
0
        if (q->pauseMode() & QAbstractSocket::PauseOnSslErrors) {
1254
0
            QSslSocketPrivate::pauseSocketNotifiers(q);
1255
0
            d->setPaused(true);
1256
0
        } else {
1257
0
            setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, sslErrors.constFirst().errorString());
1258
0
            auto *plainSocket = d->plainTcpSocket();
1259
0
            Q_ASSERT(plainSocket);
1260
0
            plainSocket->disconnectFromHost();
1261
0
        }
1262
0
        return false;
1263
0
    }
1264
0
    return true;
1265
0
}
1266
1267
int TlsCryptographOpenSSL::handleNewSessionTicket(SSL *connection)
1268
0
{
1269
    // If we return 1, this means we own the session, but we don't.
1270
    // 0 would tell OpenSSL to deref (but they still have it in the
1271
    // internal cache).
1272
0
    Q_ASSERT(connection);
1273
1274
0
    Q_ASSERT(q);
1275
0
    Q_ASSERT(d);
1276
1277
0
    if (q->sslConfiguration().testSslOption(QSsl::SslOptionDisableSessionPersistence)) {
1278
        // We silently ignore, do nothing, remove from cache.
1279
0
        return 0;
1280
0
    }
1281
1282
0
    SSL_SESSION *currentSession = q_SSL_get_session(connection);
1283
0
    if (!currentSession) {
1284
0
        qCWarning(lcTlsBackend,
1285
0
                  "New session ticket callback, the session is invalid (nullptr)");
1286
0
        return 0;
1287
0
    }
1288
1289
0
    if (q_SSL_version(connection) < 0x304) {
1290
        // We only rely on this mechanics with TLS >= 1.3
1291
0
        return 0;
1292
0
    }
1293
1294
0
#ifdef TLS1_3_VERSION
1295
0
    if (!q_SSL_SESSION_is_resumable(currentSession)) {
1296
0
        qCDebug(lcTlsBackend, "New session ticket, but the session is non-resumable");
1297
0
        return 0;
1298
0
    }
1299
0
#endif // TLS1_3_VERSION
1300
1301
0
    const int sessionSize = q_i2d_SSL_SESSION(currentSession, nullptr);
1302
0
    if (sessionSize <= 0) {
1303
0
        qCWarning(lcTlsBackend, "could not store persistent version of SSL session");
1304
0
        return 0;
1305
0
    }
1306
1307
    // We have somewhat perverse naming, it's not a ticket, it's a session.
1308
0
    QByteArray sessionTicket(sessionSize, 0);
1309
0
    auto data = reinterpret_cast<unsigned char *>(sessionTicket.data());
1310
0
    if (!q_i2d_SSL_SESSION(currentSession, &data)) {
1311
0
        qCWarning(lcTlsBackend, "could not store persistent version of SSL session");
1312
0
        return 0;
1313
0
    }
1314
1315
0
    QTlsBackend::setSessionAsn1(d, sessionTicket);
1316
0
    QTlsBackend::setSessionLifetimeHint(d, q_SSL_SESSION_get_ticket_lifetime_hint(currentSession));
1317
1318
0
    emit q->newSessionTicketReceived();
1319
0
    return 0;
1320
0
}
1321
1322
void TlsCryptographOpenSSL::alertMessageSent(int value)
1323
0
{
1324
0
    Q_ASSERT(q);
1325
0
    Q_ASSERT(d);
1326
1327
0
    const auto level = tlsAlertLevel(value);
1328
0
    if (level == QSsl::AlertLevel::Fatal && !q->isEncrypted()) {
1329
        // Note, this logic is handshake-time only:
1330
0
        pendingFatalAlert = true;
1331
0
    }
1332
1333
0
    emit q->alertSent(level, tlsAlertType(value), tlsAlertDescription(value));
1334
1335
0
}
1336
1337
void TlsCryptographOpenSSL::alertMessageReceived(int value)
1338
0
{
1339
0
    Q_ASSERT(q);
1340
1341
0
    emit q->alertReceived(tlsAlertLevel(value), tlsAlertType(value), tlsAlertDescription(value));
1342
0
}
1343
1344
int TlsCryptographOpenSSL::emitErrorFromCallback(X509_STORE_CTX *ctx)
1345
0
{
1346
    // Returns 0 to abort verification, 1 to continue despite error (as
1347
    // OpenSSL expects from the verification callback).
1348
0
    Q_ASSERT(q);
1349
0
    Q_ASSERT(ctx);
1350
1351
0
    using ScopedBool = QScopedValueRollback<bool>;
1352
    // While we are not setting, we are emitting and in general -
1353
    // we want to prevent accidental recursive startHandshake()
1354
    // calls:
1355
0
    const ScopedBool bg(inSetAndEmitError, true);
1356
1357
0
    X509 *x509 = q_X509_STORE_CTX_get_current_cert(ctx);
1358
0
    if (!x509) {
1359
0
        qCWarning(lcTlsBackend, "Could not obtain the certificate (that failed to verify)");
1360
0
        return 0;
1361
0
    }
1362
1363
0
    const QSslCertificate certificate = QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1364
0
    const auto errorAndDepth = QTlsPrivate::X509CertificateOpenSSL::errorEntryFromStoreContext(ctx);
1365
0
    const QSslError tlsError = QTlsPrivate::X509CertificateOpenSSL::openSSLErrorToQSslError(errorAndDepth.code, certificate);
1366
1367
0
    errorsReportedFromCallback = true;
1368
0
    handshakeInterrupted = true;
1369
0
    emit q->handshakeInterruptedOnError(tlsError);
1370
1371
    // Conveniently so, we also can access 'lastErrors' external data set
1372
    // in startHandshake, we store it for the case an application later
1373
    // wants to check errors (ignored or not):
1374
0
    const auto offset = QTlsBackendOpenSSL::s_indexForSSLExtraData
1375
0
                        + TlsCryptographOpenSSL::errorOffsetInExData;
1376
0
    if (auto errorList = static_cast<QList<QSslErrorEntry> *>(q_SSL_get_ex_data(ssl, offset)))
1377
0
        errorList->append(errorAndDepth);
1378
1379
    // An application is expected to ignore this error (by calling ignoreSslErrors)
1380
    // in its directly connected slot:
1381
0
    return !handshakeInterrupted;
1382
0
}
1383
1384
void TlsCryptographOpenSSL::trySendFatalAlert()
1385
0
{
1386
0
    Q_ASSERT(pendingFatalAlert);
1387
0
    Q_ASSERT(d);
1388
1389
0
    auto *plainSocket = d->plainTcpSocket();
1390
1391
0
    pendingFatalAlert = false;
1392
0
    QVarLengthArray<char, 4096> data;
1393
0
    int pendingBytes = 0;
1394
0
    while (plainSocket->isValid() && (pendingBytes = q_BIO_pending(writeBio)) > 0
1395
0
           && plainSocket->openMode() != QIODevice::NotOpen) {
1396
        // Read encrypted data from the write BIO into a buffer.
1397
0
        data.resize(pendingBytes);
1398
0
        const int bioReadBytes = q_BIO_read(writeBio, data.data(), pendingBytes);
1399
1400
        // Write encrypted data from the buffer to the socket.
1401
0
        qint64 actualWritten = plainSocket->write(data.constData(), bioReadBytes);
1402
0
        if (actualWritten < 0)
1403
0
            return;
1404
0
        plainSocket->flush();
1405
0
    }
1406
0
}
1407
1408
bool TlsCryptographOpenSSL::initSslContext()
1409
0
{
1410
0
    Q_ASSERT(q);
1411
0
    Q_ASSERT(d);
1412
1413
    // If no external context was set (e.g. by QHttpNetworkConnection) we will
1414
    // create a new one.
1415
0
    const auto mode = d->tlsMode();
1416
0
    const auto configuration = q->sslConfiguration();
1417
0
    if (!sslContextPointer)
1418
0
        sslContextPointer = QSslContext::sharedFromConfiguration(mode, configuration, d->isRootsOnDemandAllowed());
1419
1420
0
    if (sslContextPointer->error() != QSslError::NoError) {
1421
0
        setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError, sslContextPointer->errorString());
1422
0
        sslContextPointer.reset();
1423
0
        return false;
1424
0
    }
1425
1426
    // Create and initialize SSL session
1427
0
    if (!(ssl = sslContextPointer->createSsl())) {
1428
0
        setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1429
0
                        QSslSocket::tr("Error creating SSL session, %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1430
0
        return false;
1431
0
    }
1432
1433
0
    if (configuration.protocol() != QSsl::UnknownProtocol && mode == QSslSocket::SslClientMode) {
1434
0
        const auto verificationPeerName = d->verificationName();
1435
        // Set server hostname on TLS extension. RFC4366 section 3.1 requires it in ACE format.
1436
0
        QString tlsHostName = verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName;
1437
0
        if (tlsHostName.isEmpty())
1438
0
            tlsHostName = d->tlsHostName();
1439
0
        QByteArray ace = QUrl::toAce(tlsHostName);
1440
        // only send the SNI header if the URL is valid and not an IP
1441
0
        if (!ace.isEmpty()
1442
0
            && !QHostAddress().setAddress(tlsHostName)
1443
0
            && !(configuration.testSslOption(QSsl::SslOptionDisableServerNameIndication))) {
1444
            // We don't send the trailing dot from the host header if present see
1445
            // https://tools.ietf.org/html/rfc6066#section-3
1446
0
            if (ace.endsWith('.'))
1447
0
                ace.chop(1);
1448
0
            if (!q_SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, ace.data()))
1449
0
                qCWarning(lcTlsBackend, "could not set SSL_CTRL_SET_TLSEXT_HOSTNAME, Server Name Indication disabled");
1450
0
        }
1451
0
    }
1452
1453
    // Clear the session.
1454
0
    errorList.clear();
1455
1456
    // Initialize memory BIOs for encryption and decryption.
1457
0
    readBio = q_BIO_new(q_BIO_s_mem());
1458
0
    writeBio = q_BIO_new(q_BIO_s_mem());
1459
0
    if (!readBio || !writeBio) {
1460
0
        setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1461
0
                        QSslSocket::tr("Error creating SSL session: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1462
0
        if (readBio)
1463
0
            q_BIO_free(readBio);
1464
0
        if (writeBio)
1465
0
            q_BIO_free(writeBio);
1466
0
        return false;
1467
0
    }
1468
1469
    // Assign the bios.
1470
0
    q_SSL_set_bio(ssl, readBio, writeBio);
1471
1472
0
    if (mode == QSslSocket::SslClientMode)
1473
0
        q_SSL_set_connect_state(ssl);
1474
0
    else
1475
0
        q_SSL_set_accept_state(ssl);
1476
1477
0
    q_SSL_set_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData, this);
1478
1479
0
#ifndef OPENSSL_NO_PSK
1480
    // Set the client callback for PSK
1481
0
    if (mode == QSslSocket::SslClientMode)
1482
0
        q_SSL_set_psk_client_callback(ssl, &q_ssl_psk_client_callback);
1483
0
    else if (mode == QSslSocket::SslServerMode)
1484
0
        q_SSL_set_psk_server_callback(ssl, &q_ssl_psk_server_callback);
1485
1486
0
#if OPENSSL_VERSION_NUMBER >= 0x10101006L
1487
    // Set the client callback for TLSv1.3 PSK
1488
0
    if (mode == QSslSocket::SslClientMode
1489
0
        && QSslSocket::sslLibraryBuildVersionNumber() >= 0x10101006L) {
1490
0
        q_SSL_set_psk_use_session_callback(ssl, &q_ssl_psk_use_session_callback);
1491
0
    }
1492
0
#endif // openssl version >= 0x10101006L
1493
1494
0
#endif // OPENSSL_NO_PSK
1495
1496
0
#if QT_CONFIG(ocsp)
1497
0
    if (configuration.ocspStaplingEnabled()) {
1498
0
        if (mode == QSslSocket::SslServerMode) {
1499
0
            setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError,
1500
0
                            QSslSocket::tr("Server-side QSslSocket does not support OCSP stapling"));
1501
0
            return false;
1502
0
        }
1503
0
        if (q_SSL_set_tlsext_status_type(ssl, TLSEXT_STATUSTYPE_ocsp) != 1) {
1504
0
            setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1505
0
                            QSslSocket::tr("Failed to enable OCSP stapling"));
1506
0
            return false;
1507
0
        }
1508
0
    }
1509
1510
0
    ocspResponseDer.clear();
1511
0
    const auto backendConfig = configuration.backendConfiguration();
1512
0
    auto responsePos = backendConfig.find("Qt-OCSP-response");
1513
0
    if (responsePos != backendConfig.end()) {
1514
        // This is our private, undocumented 'API' we use for the auto-testing of
1515
        // OCSP-stapling. It must be a der-encoded OCSP response, presumably set
1516
        // by tst_QOcsp.
1517
0
        const QVariant data(responsePos.value());
1518
0
        if (data.canConvert<QByteArray>())
1519
0
            ocspResponseDer = data.toByteArray();
1520
0
    }
1521
1522
0
    if (ocspResponseDer.size()) {
1523
0
        if (mode != QSslSocket::SslServerMode) {
1524
0
            setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError,
1525
0
                            QSslSocket::tr("Client-side sockets do not send OCSP responses"));
1526
0
            return false;
1527
0
        }
1528
0
    }
1529
0
#endif // ocsp
1530
1531
0
    return true;
1532
0
}
1533
1534
void TlsCryptographOpenSSL::destroySslContext()
1535
0
{
1536
0
    if (ssl) {
1537
0
        if (!q_SSL_in_init(ssl) && !systemOrSslErrorDetected) {
1538
            // We do not send a shutdown alert here. Just mark the session as
1539
            // resumable for qhttpnetworkconnection's "optimization", otherwise
1540
            // OpenSSL won't start a session resumption.
1541
0
            if (q_SSL_shutdown(ssl) != 1) {
1542
                // Some error may be queued, clear it.
1543
0
                const auto errors = QTlsBackendOpenSSL::getErrorsFromOpenSsl();
1544
0
                Q_UNUSED(errors);
1545
0
            }
1546
0
        }
1547
0
        q_SSL_free(ssl);
1548
0
        ssl = nullptr;
1549
0
    }
1550
0
    sslContextPointer.reset();
1551
0
}
1552
1553
void TlsCryptographOpenSSL::storePeerCertificates()
1554
0
{
1555
0
    Q_ASSERT(d);
1556
1557
    // Store the peer certificate and chain. For clients, the peer certificate
1558
    // chain includes the peer certificate; for servers, it doesn't. Both the
1559
    // peer certificate and the chain may be empty if the peer didn't present
1560
    // any certificate.
1561
0
    X509 *x509 = q_SSL_get_peer_certificate(ssl);
1562
1563
0
    const auto peerCertificate = QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1564
0
    QTlsBackend::storePeerCertificate(d, peerCertificate);
1565
0
    q_X509_free(x509);
1566
0
    auto peerCertificateChain = q->peerCertificateChain();
1567
0
    if (peerCertificateChain.isEmpty()) {
1568
0
        peerCertificateChain = QTlsPrivate::X509CertificateOpenSSL::stackOfX509ToQSslCertificates(q_SSL_get_peer_cert_chain(ssl));
1569
0
        if (!peerCertificate.isNull() && d->tlsMode() == QSslSocket::SslServerMode)
1570
0
            peerCertificateChain.prepend(peerCertificate);
1571
0
        QTlsBackend::storePeerCertificateChain(d, peerCertificateChain);
1572
0
    }
1573
0
}
1574
1575
#if QT_CONFIG(ocsp)
1576
1577
bool TlsCryptographOpenSSL::checkOcspStatus()
1578
0
{
1579
0
    Q_ASSERT(ssl);
1580
0
    Q_ASSERT(d);
1581
1582
0
    const auto &configuration = q->sslConfiguration();
1583
0
    Q_ASSERT(d->tlsMode() == QSslSocket::SslClientMode); // See initSslContext() for SslServerMode
1584
0
    Q_ASSERT(configuration.peerVerifyMode() != QSslSocket::VerifyNone);
1585
1586
0
    const auto clearErrorQueue = qScopeGuard([] {
1587
0
        QTlsBackendOpenSSL::logAndClearErrorQueue();
1588
0
    });
1589
1590
0
    ocspResponses.clear();
1591
0
    ocspErrorDescription.clear();
1592
0
    ocspErrors.clear();
1593
1594
0
    const unsigned char *responseData = nullptr;
1595
0
    const long responseLength = q_SSL_get_tlsext_status_ocsp_resp(ssl, &responseData);
1596
0
    if (responseLength <= 0 || !responseData) {
1597
0
        ocspErrors.push_back(QSslError(QSslError::OcspNoResponseFound));
1598
0
        return false;
1599
0
    }
1600
1601
0
    OCSP_RESPONSE *response = q_d2i_OCSP_RESPONSE(nullptr, &responseData, responseLength);
1602
0
    if (!response) {
1603
        // Treat this as a fatal SslHandshakeError.
1604
0
        ocspErrorDescription = QSslSocket::tr("Failed to decode OCSP response");
1605
0
        return false;
1606
0
    }
1607
0
    const QSharedPointer<OCSP_RESPONSE> responseGuard(response, q_OCSP_RESPONSE_free);
1608
1609
0
    const int ocspStatus = q_OCSP_response_status(response);
1610
0
    if (ocspStatus != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1611
        // It's not a definitive response, it's an error message (not signed by the responder).
1612
0
        ocspErrors.push_back(QSslError(qt_OCSP_response_status_to_SslError(ocspStatus)));
1613
0
        return false;
1614
0
    }
1615
1616
0
    OCSP_BASICRESP *basicResponse = q_OCSP_response_get1_basic(response);
1617
0
    if (!basicResponse) {
1618
        // SslHandshakeError.
1619
0
        ocspErrorDescription = QSslSocket::tr("Failed to extract basic OCSP response");
1620
0
        return false;
1621
0
    }
1622
0
    const QSharedPointer<OCSP_BASICRESP> basicResponseGuard(basicResponse, q_OCSP_BASICRESP_free);
1623
1624
0
    SSL_CTX *ctx = q_SSL_get_SSL_CTX(ssl); // Does not increment refcount.
1625
0
    Q_ASSERT(ctx);
1626
0
    X509_STORE *store = q_SSL_CTX_get_cert_store(ctx); // Does not increment refcount.
1627
0
    if (!store) {
1628
        // SslHandshakeError.
1629
0
        ocspErrorDescription = QSslSocket::tr("No certificate verification store, cannot verify OCSP response");
1630
0
        return false;
1631
0
    }
1632
1633
0
    STACK_OF(X509) *peerChain = q_SSL_get_peer_cert_chain(ssl); // Does not increment refcount.
1634
0
    X509 *peerX509 = q_SSL_get_peer_certificate(ssl);
1635
0
    Q_ASSERT(peerChain || peerX509);
1636
0
    const QSharedPointer<X509> peerX509Guard(peerX509, q_X509_free);
1637
    // OCSP_basic_verify with 0 as verificationFlags:
1638
    //
1639
    // 0) Tries to find the OCSP responder's certificate in either peerChain
1640
    // or basicResponse->certs. If not found, verification fails.
1641
    // 1) It checks the signature using the responder's public key.
1642
    // 2) Then it tries to validate the responder's cert (building a chain
1643
    //    etc.)
1644
    // 3) It checks CertID in response.
1645
    // 4) Ensures the responder is authorized to sign the status respond.
1646
    //
1647
    // Note, OpenSSL prior to 1.0.2b would only use bs->certs to
1648
    // verify the responder's chain (see their commit 4ba9a4265bd).
1649
    // Working this around - is too much fuss for ancient versions we
1650
    // are dropping quite soon anyway.
1651
0
    const unsigned long verificationFlags = 0;
1652
0
    const int success = q_OCSP_basic_verify(basicResponse, peerChain, store, verificationFlags);
1653
0
    if (success <= 0)
1654
0
        ocspErrors.push_back(QSslError(QSslError::OcspResponseCannotBeTrusted));
1655
1656
0
    if (q_OCSP_resp_count(basicResponse) != 1) {
1657
0
        ocspErrors.push_back(QSslError(QSslError::OcspMalformedResponse));
1658
0
        return false;
1659
0
    }
1660
1661
0
    OCSP_SINGLERESP *singleResponse = q_OCSP_resp_get0(basicResponse, 0);
1662
0
    if (!singleResponse) {
1663
0
        ocspErrors.clear();
1664
        // A fatal problem -> SslHandshakeError.
1665
0
        ocspErrorDescription = QSslSocket::tr("Failed to decode a SingleResponse from OCSP status response");
1666
0
        return false;
1667
0
    }
1668
1669
    // Let's make sure the response is for the correct certificate - we
1670
    // can re-create this CertID using our peer's certificate and its
1671
    // issuer's public key.
1672
0
    ocspResponses.push_back(QOcspResponse());
1673
0
    QOcspResponsePrivate *dResponse = ocspResponses.back().d.data();
1674
0
    dResponse->subjectCert = configuration.peerCertificate();
1675
0
    bool matchFound = false;
1676
0
    if (dResponse->subjectCert.isSelfSigned()) {
1677
0
        dResponse->signerCert = configuration.peerCertificate();
1678
0
        matchFound = qt_OCSP_certificate_match(singleResponse, peerX509, peerX509);
1679
0
    } else {
1680
0
        const STACK_OF(X509) *certs = q_SSL_get_peer_cert_chain(ssl);
1681
0
        if (!certs) // Oh, what a cataclysm! Last try:
1682
0
            certs = q_OCSP_resp_get0_certs(basicResponse);
1683
0
        if (certs) {
1684
            // It could be the first certificate in 'certs' is our peer's
1685
            // certificate. Since it was not captured by the 'self-signed' branch
1686
            // above, the CertID will not match and we'll just iterate on to the
1687
            // next certificate. So we start from 0, not 1.
1688
0
            for (int i = 0, e = q_sk_X509_num(certs); i < e; ++i) {
1689
0
                X509 *issuer = q_sk_X509_value(certs, i);
1690
0
                matchFound = qt_OCSP_certificate_match(singleResponse, peerX509, issuer);
1691
0
                if (matchFound) {
1692
0
                    if (q_X509_check_issued(issuer, peerX509) == X509_V_OK) {
1693
0
                        dResponse->signerCert =  QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(issuer);
1694
0
                        break;
1695
0
                    }
1696
0
                    matchFound = false;
1697
0
                }
1698
0
            }
1699
0
        }
1700
0
    }
1701
1702
0
    if (!matchFound) {
1703
0
        dResponse->signerCert.clear();
1704
0
        ocspErrors.push_back({QSslError::OcspResponseCertIdUnknown, configuration.peerCertificate()});
1705
0
    }
1706
1707
    // Check if the response is valid time-wise:
1708
0
    ASN1_GENERALIZEDTIME *revTime = nullptr;
1709
0
    ASN1_GENERALIZEDTIME *thisUpdate = nullptr;
1710
0
    ASN1_GENERALIZEDTIME *nextUpdate = nullptr;
1711
0
    int reason;
1712
0
    const int certStatus = q_OCSP_single_get0_status(singleResponse, &reason, &revTime, &thisUpdate, &nextUpdate);
1713
0
    if (!thisUpdate) {
1714
        // This is unexpected, treat as SslHandshakeError, OCSP_check_validity assumes this pointer
1715
        // to be != nullptr.
1716
0
        ocspErrors.clear();
1717
0
        ocspResponses.clear();
1718
0
        ocspErrorDescription = QSslSocket::tr("Failed to extract 'this update time' from the SingleResponse");
1719
0
        return false;
1720
0
    }
1721
1722
    // OCSP_check_validity(this, next, nsec, maxsec) does this check:
1723
    // this <= now <= next. They allow some freedom to account
1724
    // for delays/time inaccuracy.
1725
    // this > now + nsec ? -> NOT_YET_VALID
1726
    // if maxsec >= 0:
1727
    //     now - maxsec > this ? -> TOO_OLD
1728
    // now - nsec > next ? -> EXPIRED
1729
    // next < this ? -> NEXT_BEFORE_THIS
1730
    // OK.
1731
0
    if (!q_OCSP_check_validity(thisUpdate, nextUpdate, 60, -1))
1732
0
        ocspErrors.push_back({QSslError::OcspResponseExpired, configuration.peerCertificate()});
1733
1734
    // And finally, the status:
1735
0
    switch (certStatus) {
1736
0
    case V_OCSP_CERTSTATUS_GOOD:
1737
        // This certificate was not found among the revoked ones.
1738
0
        dResponse->certificateStatus = QOcspCertificateStatus::Good;
1739
0
        break;
1740
0
    case V_OCSP_CERTSTATUS_REVOKED:
1741
0
        dResponse->certificateStatus = QOcspCertificateStatus::Revoked;
1742
0
        dResponse->revocationReason = qt_OCSP_revocation_reason(reason);
1743
0
        ocspErrors.push_back({QSslError::CertificateRevoked, configuration.peerCertificate()});
1744
0
        break;
1745
0
    case V_OCSP_CERTSTATUS_UNKNOWN:
1746
0
        dResponse->certificateStatus = QOcspCertificateStatus::Unknown;
1747
0
        ocspErrors.push_back({QSslError::OcspStatusUnknown, configuration.peerCertificate()});
1748
0
    }
1749
1750
0
    return !ocspErrors.size();
1751
0
}
1752
1753
#endif // QT_CONFIG(ocsp)
1754
1755
1756
unsigned TlsCryptographOpenSSL::pskClientTlsCallback(const char *hint, char *identity,
1757
                                                     unsigned max_identity_len,
1758
                                                     unsigned char *psk, unsigned max_psk_len)
1759
0
{
1760
0
    Q_ASSERT(q);
1761
1762
0
    QSslPreSharedKeyAuthenticator authenticator;
1763
    // Fill in some read-only fields (for the user)
1764
0
    const int hintLength = hint ? int(std::strlen(hint)) : 0;
1765
0
    QTlsBackend::setupClientPskAuth(&authenticator, hint, hintLength, max_identity_len, max_psk_len);
1766
    // Let the client provide the remaining bits...
1767
0
    emit q->preSharedKeyAuthenticationRequired(&authenticator);
1768
1769
    // No PSK set? Return now to make the handshake fail
1770
0
    if (authenticator.preSharedKey().isEmpty())
1771
0
        return 0;
1772
1773
    // Copy data back into OpenSSL
1774
0
    const int identityLength = qMin(authenticator.identity().size(), authenticator.maximumIdentityLength());
1775
0
    std::memcpy(identity, authenticator.identity().constData(), identityLength);
1776
0
    identity[identityLength] = 0;
1777
1778
0
    const int pskLength = qMin(authenticator.preSharedKey().size(), authenticator.maximumPreSharedKeyLength());
1779
0
    std::memcpy(psk, authenticator.preSharedKey().constData(), pskLength);
1780
0
    return pskLength;
1781
0
}
1782
1783
unsigned TlsCryptographOpenSSL::pskServerTlsCallback(const char *identity, unsigned char *psk,
1784
                                                     unsigned max_psk_len)
1785
0
{
1786
0
    Q_ASSERT(q);
1787
1788
0
    QSslPreSharedKeyAuthenticator authenticator;
1789
1790
    // Fill in some read-only fields (for the user)
1791
0
    QTlsBackend::setupServerPskAuth(&authenticator, identity, q->sslConfiguration().preSharedKeyIdentityHint(),
1792
0
                                    max_psk_len);
1793
0
    emit q->preSharedKeyAuthenticationRequired(&authenticator);
1794
1795
    // No PSK set? Return now to make the handshake fail
1796
0
    if (authenticator.preSharedKey().isEmpty())
1797
0
        return 0;
1798
1799
    // Copy data back into OpenSSL
1800
0
    const int pskLength = qMin(authenticator.preSharedKey().size(), authenticator.maximumPreSharedKeyLength());
1801
0
    std::memcpy(psk, authenticator.preSharedKey().constData(), pskLength);
1802
0
    return pskLength;
1803
0
}
1804
1805
bool TlsCryptographOpenSSL::isInSslRead() const
1806
0
{
1807
0
    return inSslRead;
1808
0
}
1809
1810
void TlsCryptographOpenSSL::setRenegotiated(bool renegotiated)
1811
0
{
1812
0
    this->renegotiated = renegotiated;
1813
0
}
1814
1815
#ifdef Q_OS_WIN
1816
1817
void TlsCryptographOpenSSL::fetchCaRootForCert(const QSslCertificate &cert)
1818
{
1819
    Q_ASSERT(d);
1820
    Q_ASSERT(q);
1821
1822
    //The root certificate is downloaded from windows update, which blocks for 15 seconds in the worst case
1823
    //so the request is done in a worker thread.
1824
    QList<QSslCertificate> customRoots;
1825
    if (fetchAuthorityInformation)
1826
        customRoots = q->sslConfiguration().caCertificates();
1827
1828
    //Remember we are fetching and what we are fetching:
1829
    caToFetch = cert;
1830
1831
    QWindowsCaRootFetcher *fetcher = new QWindowsCaRootFetcher(cert, d->tlsMode(), customRoots,
1832
                                                               q->peerVerifyName());
1833
    connect(fetcher,  &QWindowsCaRootFetcher::finished, this, &TlsCryptographOpenSSL::caRootLoaded,
1834
            Qt::QueuedConnection);
1835
    QMetaObject::invokeMethod(fetcher, "start", Qt::QueuedConnection);
1836
    QSslSocketPrivate::pauseSocketNotifiers(q);
1837
    d->setPaused(true);
1838
}
1839
1840
void TlsCryptographOpenSSL::caRootLoaded(QSslCertificate cert, QSslCertificate trustedRoot)
1841
{
1842
    if (caToFetch != cert) {
1843
        //Ooops, something from the previous connection attempt, ignore!
1844
        return;
1845
    }
1846
1847
    Q_ASSERT(d);
1848
    Q_ASSERT(q);
1849
1850
    //Done, fetched already:
1851
    caToFetch.reset();
1852
1853
    if (fetchAuthorityInformation) {
1854
        if (!q->sslConfiguration().caCertificates().contains(trustedRoot))
1855
            trustedRoot = QSslCertificate{};
1856
        fetchAuthorityInformation = false;
1857
    }
1858
1859
    if (!trustedRoot.isNull() && !trustedRoot.isBlacklisted()) {
1860
        if (QSslSocketPrivate::rootCertOnDemandLoadingSupported()) {
1861
            //Add the new root cert to default cert list for use by future sockets
1862
            auto defaultConfig = QSslConfiguration::defaultConfiguration();
1863
            defaultConfig.addCaCertificate(trustedRoot);
1864
            QSslConfiguration::setDefaultConfiguration(defaultConfig);
1865
        }
1866
        //Add the new root cert to this socket for future connections
1867
        QTlsBackend::addTrustedRoot(d, trustedRoot);
1868
        //Remove the broken chain ssl errors (as chain is verified by windows)
1869
        for (int i=sslErrors.count() - 1; i >= 0; --i) {
1870
            if (sslErrors.at(i).certificate() == cert) {
1871
                switch (sslErrors.at(i).error()) {
1872
                case QSslError::UnableToGetLocalIssuerCertificate:
1873
                case QSslError::CertificateUntrusted:
1874
                case QSslError::UnableToVerifyFirstCertificate:
1875
                case QSslError::SelfSignedCertificateInChain:
1876
                    // error can be ignored if OS says the chain is trusted
1877
                    sslErrors.removeAt(i);
1878
                    break;
1879
                default:
1880
                    // error cannot be ignored
1881
                    break;
1882
                }
1883
            }
1884
        }
1885
    }
1886
1887
    auto *plainSocket = d->plainTcpSocket();
1888
    Q_ASSERT(plainSocket);
1889
    // Continue with remaining errors
1890
    if (plainSocket)
1891
        plainSocket->resume();
1892
    d->setPaused(false);
1893
    if (checkSslErrors() && ssl) {
1894
        bool willClose = (d->isAutoStartingHandshake() && d->isPendingClose());
1895
        continueHandshake();
1896
        if (!willClose)
1897
            transmit();
1898
    }
1899
}
1900
1901
#endif // Q_OS_WIN
1902
1903
} // namespace QTlsPrivate
1904
1905
QT_END_NAMESPACE