1/****************************************************************************
2**
3** Copyright (C) 2017 The Qt Company Ltd.
4** Copyright (C) 2014 Governikus GmbH & Co. KG
5** Contact: https://www.qt.io/licensing/
6**
7** This file is part of the QtNetwork module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial License Usage
11** Licensees holding valid commercial Qt licenses may use this file in
12** accordance with the commercial license agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and The Qt Company. For licensing terms
15** and conditions see https://www.qt.io/terms-conditions. For further
16** information use the contact form at https://www.qt.io/contact-us.
17**
18** GNU Lesser General Public License Usage
19** Alternatively, this file may be used under the terms of the GNU Lesser
20** General Public License version 3 as published by the Free Software
21** Foundation and appearing in the file LICENSE.LGPL3 included in the
22** packaging of this file. Please review the following information to
23** ensure the GNU Lesser General Public License version 3 requirements
24** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25**
26** GNU General Public License Usage
27** Alternatively, this file may be used under the terms of the GNU
28** General Public License version 2.0 or (at your option) the GNU General
29** Public license version 3 or any later version approved by the KDE Free
30** Qt Foundation. The licenses are as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
32** included in the packaging of this file. Please review the following
33** information to ensure the GNU General Public License requirements will
34** be met: https://www.gnu.org/licenses/gpl-2.0.html and
35** https://www.gnu.org/licenses/gpl-3.0.html.
36**
37** $QT_END_LICENSE$
38**
39****************************************************************************/
40
41/****************************************************************************
42**
43** In addition, as a special exception, the copyright holders listed above give
44** permission to link the code of its release of Qt with the OpenSSL project's
45** "OpenSSL" library (or modified versions of the "OpenSSL" library that use the
46** same license as the original version), and distribute the linked executables.
47**
48** You must comply with the GNU General Public License version 2 in all
49** respects for all of the code used other than the "OpenSSL" code. If you
50** modify this file, you may extend this exception to your version of the file,
51** but you are not obligated to do so. If you do not wish to do so, delete
52** this exception statement from your version of this file.
53**
54****************************************************************************/
55
56//#define QSSLSOCKET_DEBUG
57
58#include "qssl_p.h"
59#include "qsslsocket_openssl_p.h"
60#include "qsslsocket_openssl_symbols_p.h"
61#include "qsslsocket.h"
62#include "qsslcertificate_p.h"
63#include "qsslcipher_p.h"
64#include "qsslkey_p.h"
65#include "qsslellipticcurve.h"
66#include "qsslpresharedkeyauthenticator.h"
67#include "qsslpresharedkeyauthenticator_p.h"
68#include "qocspresponse_p.h"
69#include "qsslkey.h"
70
71#ifdef Q_OS_WIN
72#include "qwindowscarootfetcher_p.h"
73#endif
74
75#include <QtCore/qdatetime.h>
76#include <QtCore/qdebug.h>
77#include <QtCore/qdir.h>
78#include <QtCore/qdiriterator.h>
79#include <QtCore/qelapsedtimer.h>
80#include <QtCore/qfile.h>
81#include <QtCore/qfileinfo.h>
82#include <QtCore/qmutex.h>
83#include <QtCore/qthread.h>
84#include <QtCore/qurl.h>
85#include <QtCore/qvarlengtharray.h>
86#include <QtCore/qscopedvaluerollback.h>
87#include <QtCore/qscopeguard.h>
88#include <QtCore/qlibrary.h>
89#include <QtCore/qoperatingsystemversion.h>
90
91#if QT_CONFIG(ocsp)
92#include "qocsp_p.h"
93#endif
94
95#include <algorithm>
96#include <memory>
97
98#include <string.h>
99
100QT_BEGIN_NAMESPACE
101
102#ifdef Q_OS_WIN
103
104namespace {
105
106QSslCertificate findCertificateToFetch(const QList<QSslError> &tlsErrors, bool checkAIA)
107{
108 QSslCertificate certToFetch;
109
110 for (const auto &tlsError : tlsErrors) {
111 switch (tlsError.error()) {
112 case QSslError::UnableToGetLocalIssuerCertificate: // site presented intermediate cert, but root is unknown
113 case QSslError::SelfSignedCertificateInChain: // site presented a complete chain, but root is unknown
114 certToFetch = tlsError.certificate();
115 break;
116 case QSslError::SelfSignedCertificate:
117 case QSslError::CertificateBlacklisted:
118 //With these errors, we know it will be untrusted so save time by not asking windows
119 return QSslCertificate{};
120 default:
121#ifdef QSSLSOCKET_DEBUG
122 qCDebug(lcSsl) << tlsError.errorString();
123#endif
124 //TODO - this part is strange.
125 break;
126 }
127 }
128
129 if (checkAIA) {
130 const auto extensions = certToFetch.extensions();
131 for (const auto &ext : extensions) {
132 if (ext.oid() == QStringLiteral("1.3.6.1.5.5.7.1.1")) // See RFC 4325
133 return certToFetch;
134 }
135 //The only reason we check this extensions is because an application set trusted
136 //CA certificates explicitly, thus technically disabling CA fetch. So, if it's
137 //the case and an intermediate certificate is missing, and no extensions is
138 //present on the leaf certificate - we fail the handshake immediately.
139 return QSslCertificate{};
140 }
141
142 return certToFetch;
143}
144
145} // Unnamed namespace
146
147#endif // Q_OS_WIN
148
149Q_GLOBAL_STATIC(QRecursiveMutex, qt_opensslInitMutex)
150
151bool QSslSocketPrivate::s_libraryLoaded = false;
152bool QSslSocketPrivate::s_loadedCiphersAndCerts = false;
153bool QSslSocketPrivate::s_loadRootCertsOnDemand = false;
154int QSslSocketBackendPrivate::s_indexForSSLExtraData = -1;
155
156QString QSslSocketBackendPrivate::getErrorsFromOpenSsl()
157{
158 QString errorString;
159 char buf[256] = {}; // OpenSSL docs claim both 120 and 256; use the larger.
160 unsigned long errNum;
161 while ((errNum = q_ERR_get_error())) {
162 if (!errorString.isEmpty())
163 errorString.append(s: QLatin1String(", "));
164 q_ERR_error_string_n(e: errNum, buf, len: sizeof buf);
165 errorString.append(s: QString::fromLatin1(str: buf)); // error is ascii according to man ERR_error_string
166 }
167 return errorString;
168}
169
170void QSslSocketBackendPrivate::logAndClearErrorQueue()
171{
172 const auto errors = getErrorsFromOpenSsl();
173 if (errors.size())
174 qCWarning(lcSsl) << "Discarding errors:" << errors;
175}
176
177extern "C" {
178
179#ifndef OPENSSL_NO_PSK
180static unsigned int q_ssl_psk_client_callback(SSL *ssl,
181 const char *hint,
182 char *identity, unsigned int max_identity_len,
183 unsigned char *psk, unsigned int max_psk_len)
184{
185 QSslSocketBackendPrivate *d = reinterpret_cast<QSslSocketBackendPrivate *>(q_SSL_get_ex_data(ssl, idx: QSslSocketBackendPrivate::s_indexForSSLExtraData));
186 Q_ASSERT(d);
187 return d->tlsPskClientCallback(hint, identity, max_identity_len, psk, max_psk_len);
188}
189
190static unsigned int q_ssl_psk_server_callback(SSL *ssl,
191 const char *identity,
192 unsigned char *psk, unsigned int max_psk_len)
193{
194 QSslSocketBackendPrivate *d = reinterpret_cast<QSslSocketBackendPrivate *>(q_SSL_get_ex_data(ssl, idx: QSslSocketBackendPrivate::s_indexForSSLExtraData));
195 Q_ASSERT(d);
196 return d->tlsPskServerCallback(identity, psk, max_psk_len);
197}
198
199#ifdef TLS1_3_VERSION
200static unsigned int q_ssl_psk_restore_client(SSL *ssl,
201 const char *hint,
202 char *identity, unsigned int max_identity_len,
203 unsigned char *psk, unsigned int max_psk_len)
204{
205 Q_UNUSED(hint);
206 Q_UNUSED(identity);
207 Q_UNUSED(max_identity_len);
208 Q_UNUSED(psk);
209 Q_UNUSED(max_psk_len);
210
211#ifdef QT_DEBUG
212 QSslSocketBackendPrivate *d = reinterpret_cast<QSslSocketBackendPrivate *>(q_SSL_get_ex_data(ssl, idx: QSslSocketBackendPrivate::s_indexForSSLExtraData));
213 Q_ASSERT(d);
214 Q_ASSERT(d->mode == QSslSocket::SslClientMode);
215#endif
216 unsigned retVal = 0;
217
218 // Let developers opt-in to having the normal PSK callback get called for TLS 1.3
219 // PSK (which works differently in a few ways, and is called at the start of every connection).
220 // When they do opt-in we just call the old callback from here.
221 if (qEnvironmentVariableIsSet(varName: "QT_USE_TLS_1_3_PSK"))
222 retVal = q_ssl_psk_client_callback(ssl, hint, identity, max_identity_len, psk, max_psk_len);
223
224 q_SSL_set_psk_client_callback(ssl, callback: &q_ssl_psk_client_callback);
225
226 return retVal;
227}
228
229static int q_ssl_psk_use_session_callback(SSL *ssl, const EVP_MD *md, const unsigned char **id,
230 size_t *idlen, SSL_SESSION **sess)
231{
232 Q_UNUSED(md);
233 Q_UNUSED(id);
234 Q_UNUSED(idlen);
235 Q_UNUSED(sess);
236
237#ifdef QT_DEBUG
238 QSslSocketBackendPrivate *d = reinterpret_cast<QSslSocketBackendPrivate *>(q_SSL_get_ex_data(ssl, idx: QSslSocketBackendPrivate::s_indexForSSLExtraData));
239 Q_ASSERT(d);
240 Q_ASSERT(d->mode == QSslSocket::SslClientMode);
241#endif
242
243 // Temporarily rebind the psk because it will be called next. The function will restore it.
244 q_SSL_set_psk_client_callback(ssl, callback: &q_ssl_psk_restore_client);
245
246 return 1; // need to return 1 or else "the connection setup fails."
247}
248
249int q_ssl_sess_set_new_cb(SSL *ssl, SSL_SESSION *session)
250{
251 if (!ssl) {
252 qCWarning(lcSsl, "Invalid SSL (nullptr)");
253 return 0;
254 }
255 if (!session) {
256 qCWarning(lcSsl, "Invalid SSL_SESSION (nullptr)");
257 return 0;
258 }
259
260 auto socketPrivate = static_cast<QSslSocketBackendPrivate *>(q_SSL_get_ex_data(ssl,
261 idx: QSslSocketBackendPrivate::s_indexForSSLExtraData));
262 return socketPrivate->handleNewSessionTicket(context: ssl);
263}
264#endif // TLS1_3_VERSION
265
266#endif // !OPENSSL_NO_PSK
267
268#if QT_CONFIG(ocsp)
269
270int qt_OCSP_status_server_callback(SSL *ssl, void *ocspRequest)
271{
272 Q_UNUSED(ocspRequest)
273 if (!ssl)
274 return SSL_TLSEXT_ERR_ALERT_FATAL;
275
276 auto d = static_cast<QSslSocketBackendPrivate *>(q_SSL_get_ex_data(ssl, idx: QSslSocketBackendPrivate::s_indexForSSLExtraData));
277 if (!d)
278 return SSL_TLSEXT_ERR_ALERT_FATAL;
279
280 Q_ASSERT(d->mode == QSslSocket::SslServerMode);
281 const QByteArray &response = d->ocspResponseDer;
282 Q_ASSERT(response.size());
283
284 unsigned char *derCopy = static_cast<unsigned char *>(q_OPENSSL_malloc(size_t(response.size())));
285 if (!derCopy)
286 return SSL_TLSEXT_ERR_ALERT_FATAL;
287
288 std::copy(first: response.data(), last: response.data() + response.size(), result: derCopy);
289 // We don't check the return value: internally OpenSSL simply assignes the
290 // pointer (it assumes it now owns this memory btw!) and the length.
291 q_SSL_set_tlsext_status_ocsp_resp(ssl, derCopy, response.size());
292
293 return SSL_TLSEXT_ERR_OK;
294}
295
296#endif // ocsp
297
298} // extern "C"
299
300QSslSocketBackendPrivate::QSslSocketBackendPrivate()
301 : ssl(nullptr),
302 readBio(nullptr),
303 writeBio(nullptr),
304 session(nullptr)
305{
306 // Calls SSL_library_init().
307 ensureInitialized();
308}
309
310QSslSocketBackendPrivate::~QSslSocketBackendPrivate()
311{
312 destroySslContext();
313}
314
315QSslCipher QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(const SSL_CIPHER *cipher)
316{
317 QSslCipher ciph;
318
319 char buf [256];
320 QString descriptionOneLine = QString::fromLatin1(str: q_SSL_CIPHER_description(a: cipher, b: buf, c: sizeof(buf)));
321
322 const auto descriptionList = descriptionOneLine.splitRef(sep: QLatin1Char(' '), behavior: Qt::SkipEmptyParts);
323 if (descriptionList.size() > 5) {
324 // ### crude code.
325 ciph.d->isNull = false;
326 ciph.d->name = descriptionList.at(i: 0).toString();
327
328 QString protoString = descriptionList.at(i: 1).toString();
329 ciph.d->protocolString = protoString;
330 ciph.d->protocol = QSsl::UnknownProtocol;
331 if (protoString == QLatin1String("SSLv3"))
332 ciph.d->protocol = QSsl::SslV3;
333 else if (protoString == QLatin1String("SSLv2"))
334 ciph.d->protocol = QSsl::SslV2;
335 else if (protoString == QLatin1String("TLSv1"))
336 ciph.d->protocol = QSsl::TlsV1_0;
337 else if (protoString == QLatin1String("TLSv1.1"))
338 ciph.d->protocol = QSsl::TlsV1_1;
339 else if (protoString == QLatin1String("TLSv1.2"))
340 ciph.d->protocol = QSsl::TlsV1_2;
341 else if (protoString == QLatin1String("TLSv1.3"))
342 ciph.d->protocol = QSsl::TlsV1_3;
343
344 if (descriptionList.at(i: 2).startsWith(s: QLatin1String("Kx=")))
345 ciph.d->keyExchangeMethod = descriptionList.at(i: 2).mid(pos: 3).toString();
346 if (descriptionList.at(i: 3).startsWith(s: QLatin1String("Au=")))
347 ciph.d->authenticationMethod = descriptionList.at(i: 3).mid(pos: 3).toString();
348 if (descriptionList.at(i: 4).startsWith(s: QLatin1String("Enc=")))
349 ciph.d->encryptionMethod = descriptionList.at(i: 4).mid(pos: 4).toString();
350 ciph.d->exportable = (descriptionList.size() > 6 && descriptionList.at(i: 6) == QLatin1String("export"));
351
352 ciph.d->bits = q_SSL_CIPHER_get_bits(a: cipher, b: &ciph.d->supportedBits);
353 }
354 return ciph;
355}
356
357QSslErrorEntry QSslErrorEntry::fromStoreContext(X509_STORE_CTX *ctx)
358{
359 return {
360 .code: q_X509_STORE_CTX_get_error(ctx),
361 .depth: q_X509_STORE_CTX_get_error_depth(ctx)
362 };
363}
364
365#if QT_CONFIG(ocsp)
366
367QSslError qt_OCSP_response_status_to_QSslError(long code)
368{
369 switch (code) {
370 case OCSP_RESPONSE_STATUS_MALFORMEDREQUEST:
371 return QSslError::OcspMalformedRequest;
372 case OCSP_RESPONSE_STATUS_INTERNALERROR:
373 return QSslError::OcspInternalError;
374 case OCSP_RESPONSE_STATUS_TRYLATER:
375 return QSslError::OcspTryLater;
376 case OCSP_RESPONSE_STATUS_SIGREQUIRED:
377 return QSslError::OcspSigRequred;
378 case OCSP_RESPONSE_STATUS_UNAUTHORIZED:
379 return QSslError::OcspUnauthorized;
380 case OCSP_RESPONSE_STATUS_SUCCESSFUL:
381 default:
382 return {};
383 }
384 Q_UNREACHABLE();
385}
386
387QOcspRevocationReason qt_OCSP_revocation_reason(int reason)
388{
389 switch (reason) {
390 case OCSP_REVOKED_STATUS_NOSTATUS:
391 return QOcspRevocationReason::None;
392 case OCSP_REVOKED_STATUS_UNSPECIFIED:
393 return QOcspRevocationReason::Unspecified;
394 case OCSP_REVOKED_STATUS_KEYCOMPROMISE:
395 return QOcspRevocationReason::KeyCompromise;
396 case OCSP_REVOKED_STATUS_CACOMPROMISE:
397 return QOcspRevocationReason::CACompromise;
398 case OCSP_REVOKED_STATUS_AFFILIATIONCHANGED:
399 return QOcspRevocationReason::AffiliationChanged;
400 case OCSP_REVOKED_STATUS_SUPERSEDED:
401 return QOcspRevocationReason::Superseded;
402 case OCSP_REVOKED_STATUS_CESSATIONOFOPERATION:
403 return QOcspRevocationReason::CessationOfOperation;
404 case OCSP_REVOKED_STATUS_CERTIFICATEHOLD:
405 return QOcspRevocationReason::CertificateHold;
406 case OCSP_REVOKED_STATUS_REMOVEFROMCRL:
407 return QOcspRevocationReason::RemoveFromCRL;
408 default:
409 return QOcspRevocationReason::None;
410 }
411
412 Q_UNREACHABLE();
413}
414
415bool qt_OCSP_certificate_match(OCSP_SINGLERESP *singleResponse, X509 *peerCert, X509 *issuer)
416{
417 // OCSP_basic_verify does verify that the responder is legit, the response is
418 // correctly signed, CertID is correct. But it does not know which certificate
419 // we were presented with by our peer, so it does not check if it's a response
420 // for our peer's certificate.
421 Q_ASSERT(singleResponse && peerCert && issuer);
422
423 const OCSP_CERTID *certId = q_OCSP_SINGLERESP_get0_id(x: singleResponse); // Does not increment refcount.
424 if (!certId) {
425 qCWarning(lcSsl, "A SingleResponse without CertID");
426 return false;
427 }
428
429 ASN1_OBJECT *md = nullptr;
430 ASN1_INTEGER *reportedSerialNumber = nullptr;
431 const int result = q_OCSP_id_get0_info(piNameHash: nullptr, pmd: &md, pikeyHash: nullptr, pserial: &reportedSerialNumber, cid: const_cast<OCSP_CERTID *>(certId));
432 if (result != 1 || !md || !reportedSerialNumber) {
433 qCWarning(lcSsl, "Failed to extract a hash and serial number from CertID structure");
434 return false;
435 }
436
437 if (!q_X509_get_serialNumber(a: peerCert)) {
438 // Is this possible at all? But we have to check this,
439 // ASN1_INTEGER_cmp (called from OCSP_id_cmp) dereferences
440 // without any checks at all.
441 qCWarning(lcSsl, "No serial number in peer's ceritificate");
442 return false;
443 }
444
445 const int nid = q_OBJ_obj2nid(a: md);
446 if (nid == NID_undef) {
447 qCWarning(lcSsl, "Unknown hash algorithm in CertID");
448 return false;
449 }
450
451 const EVP_MD *digest = q_EVP_get_digestbynid(nid); // Does not increment refcount.
452 if (!digest) {
453 qCWarning(lcSsl) << "No digest for nid" << nid;
454 return false;
455 }
456
457 OCSP_CERTID *recreatedId = q_OCSP_cert_to_id(dgst: digest, subject: peerCert, issuer);
458 if (!recreatedId) {
459 qCWarning(lcSsl, "Failed to re-create CertID");
460 return false;
461 }
462 const QSharedPointer<OCSP_CERTID> guard(recreatedId, q_OCSP_CERTID_free);
463
464 if (q_OCSP_id_cmp(a: const_cast<OCSP_CERTID *>(certId), b: recreatedId)) {
465 qCDebug(lcSsl, "Certificate ID mismatch");
466 return false;
467 }
468 // Bingo!
469 return true;
470}
471
472#endif // ocsp
473
474int q_X509Callback(int ok, X509_STORE_CTX *ctx)
475{
476 if (!ok) {
477 // Store the error and at which depth the error was detected.
478
479 using ErrorListPtr = QVector<QSslErrorEntry>*;
480 ErrorListPtr errors = nullptr;
481
482 // Error list is attached to either 'SSL' or 'X509_STORE'.
483 if (X509_STORE *store = q_X509_STORE_CTX_get0_store(ctx)) // We try store first:
484 errors = ErrorListPtr(q_X509_STORE_get_ex_data(r: store, idx: 0));
485
486 if (!errors) {
487 // Not found on store? Try SSL and its external data then. According to the OpenSSL's
488 // documentation:
489 //
490 // "Whenever a X509_STORE_CTX object is created for the verification of the peers certificate
491 // during a handshake, a pointer to the SSL object is stored into the X509_STORE_CTX object
492 // to identify the connection affected. To retrieve this pointer the X509_STORE_CTX_get_ex_data()
493 // function can be used with the correct index."
494 if (SSL *ssl = static_cast<SSL *>(q_X509_STORE_CTX_get_ex_data(
495 ctx, idx: q_SSL_get_ex_data_X509_STORE_CTX_idx()))) {
496
497 // We may be in a renegotiation, check if we are inside a call to SSL_read:
498 const auto tlsOffset = QSslSocketBackendPrivate::s_indexForSSLExtraData;
499 auto tls = static_cast<QSslSocketBackendPrivate *>(q_SSL_get_ex_data(ssl, idx: tlsOffset));
500 Q_ASSERT(tls);
501 if (tls->isInSslRead()) {
502 // We are in a renegotiation, make a note of this for later.
503 // We'll check that the certificate is the same as the one we got during
504 // the initial handshake
505 tls->setRenegotiated(true);
506 return 1;
507 }
508
509 errors = ErrorListPtr(q_SSL_get_ex_data(ssl, idx: QSslSocketBackendPrivate::s_indexForSSLExtraData + 1));
510 }
511 }
512
513 if (!errors) {
514 qCWarning(lcSsl, "Neither X509_STORE, nor SSL contains error list, handshake failure");
515 return 0;
516 }
517
518 errors->append(t: QSslErrorEntry::fromStoreContext(ctx));
519 }
520 // Always return OK to allow verification to continue. We handle the
521 // errors gracefully after collecting all errors, after verification has
522 // completed.
523 return 1;
524}
525
526static void q_loadCiphersForConnection(SSL *connection, QList<QSslCipher> &ciphers,
527 QList<QSslCipher> &defaultCiphers)
528{
529 Q_ASSERT(connection);
530
531 STACK_OF(SSL_CIPHER) *supportedCiphers = q_SSL_get_ciphers(a: connection);
532 for (int i = 0; i < q_sk_SSL_CIPHER_num(supportedCiphers); ++i) {
533 if (SSL_CIPHER *cipher = q_sk_SSL_CIPHER_value(supportedCiphers, i)) {
534 QSslCipher ciph = QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(cipher);
535 if (!ciph.isNull()) {
536 // Unconditionally exclude ADH and AECDH ciphers since they offer no MITM protection
537 if (!ciph.name().toLower().startsWith(s: QLatin1String("adh")) &&
538 !ciph.name().toLower().startsWith(s: QLatin1String("exp-adh")) &&
539 !ciph.name().toLower().startsWith(s: QLatin1String("aecdh"))) {
540 ciphers << ciph;
541
542 if (ciph.usedBits() >= 128)
543 defaultCiphers << ciph;
544 }
545 }
546 }
547 }
548}
549
550// Defined in qsslsocket.cpp
551void q_setDefaultDtlsCiphers(const QList<QSslCipher> &ciphers);
552
553long QSslSocketBackendPrivate::setupOpenSslOptions(QSsl::SslProtocol protocol, QSsl::SslOptions sslOptions)
554{
555 long options;
556 if (protocol == QSsl::TlsV1SslV3)
557 options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3;
558 else if (protocol == QSsl::SecureProtocols)
559 options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3;
560 else if (protocol == QSsl::TlsV1_0OrLater)
561 options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3;
562 else if (protocol == QSsl::TlsV1_1OrLater)
563 options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1;
564 else if (protocol == QSsl::TlsV1_2OrLater)
565 options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1|SSL_OP_NO_TLSv1_1;
566 else if (protocol == QSsl::TlsV1_3OrLater)
567 options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2;
568 else
569 options = SSL_OP_ALL;
570
571 // This option is disabled by default, so we need to be able to clear it
572 if (sslOptions & QSsl::SslOptionDisableEmptyFragments)
573 options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
574 else
575 options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
576
577#ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
578 // This option is disabled by default, so we need to be able to clear it
579 if (sslOptions & QSsl::SslOptionDisableLegacyRenegotiation)
580 options &= ~SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
581 else
582 options |= SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
583#endif
584
585#ifdef SSL_OP_NO_TICKET
586 if (sslOptions & QSsl::SslOptionDisableSessionTickets)
587 options |= SSL_OP_NO_TICKET;
588#endif
589#ifdef SSL_OP_NO_COMPRESSION
590 if (sslOptions & QSsl::SslOptionDisableCompression)
591 options |= SSL_OP_NO_COMPRESSION;
592#endif
593
594 if (!(sslOptions & QSsl::SslOptionDisableServerCipherPreference))
595 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
596
597 return options;
598}
599
600bool QSslSocketBackendPrivate::initSslContext()
601{
602 Q_Q(QSslSocket);
603
604 // If no external context was set (e.g. by QHttpNetworkConnection) we will
605 // create a default context
606 if (!sslContextPointer) {
607 // create a deep copy of our configuration
608 QSslConfigurationPrivate *configurationCopy = new QSslConfigurationPrivate(configuration);
609 configurationCopy->ref.storeRelaxed(newValue: 0); // the QSslConfiguration constructor refs up
610 sslContextPointer = QSslContext::sharedFromConfiguration(mode, configuration: configurationCopy, allowRootCertOnDemandLoading);
611 }
612
613 if (sslContextPointer->error() != QSslError::NoError) {
614 setErrorAndEmit(errorCode: QAbstractSocket::SslInvalidUserDataError, errorString: sslContextPointer->errorString());
615 sslContextPointer.clear(); // deletes the QSslContext
616 return false;
617 }
618
619 // Create and initialize SSL session
620 if (!(ssl = sslContextPointer->createSsl())) {
621 // ### Bad error code
622 setErrorAndEmit(errorCode: QAbstractSocket::SslInternalError,
623 errorString: QSslSocket::tr(s: "Error creating SSL session, %1").arg(a: getErrorsFromOpenSsl()));
624 return false;
625 }
626
627 if (configuration.protocol != QSsl::SslV2 &&
628 configuration.protocol != QSsl::SslV3 &&
629 configuration.protocol != QSsl::UnknownProtocol &&
630 mode == QSslSocket::SslClientMode) {
631 // Set server hostname on TLS extension. RFC4366 section 3.1 requires it in ACE format.
632 QString tlsHostName = verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName;
633 if (tlsHostName.isEmpty())
634 tlsHostName = hostName;
635 QByteArray ace = QUrl::toAce(tlsHostName);
636 // only send the SNI header if the URL is valid and not an IP
637 if (!ace.isEmpty()
638 && !QHostAddress().setAddress(tlsHostName)
639 && !(configuration.sslOptions & QSsl::SslOptionDisableServerNameIndication)) {
640 // We don't send the trailing dot from the host header if present see
641 // https://tools.ietf.org/html/rfc6066#section-3
642 if (ace.endsWith(c: '.'))
643 ace.chop(n: 1);
644 if (!q_SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, parg: ace.data()))
645 qCWarning(lcSsl, "could not set SSL_CTRL_SET_TLSEXT_HOSTNAME, Server Name Indication disabled");
646 }
647 }
648
649 // Clear the session.
650 errorList.clear();
651
652 // Initialize memory BIOs for encryption and decryption.
653 readBio = q_BIO_new(a: q_BIO_s_mem());
654 writeBio = q_BIO_new(a: q_BIO_s_mem());
655 if (!readBio || !writeBio) {
656 setErrorAndEmit(errorCode: QAbstractSocket::SslInternalError,
657 errorString: QSslSocket::tr(s: "Error creating SSL session: %1").arg(a: getErrorsFromOpenSsl()));
658 return false;
659 }
660
661 // Assign the bios.
662 q_SSL_set_bio(a: ssl, b: readBio, c: writeBio);
663
664 if (mode == QSslSocket::SslClientMode)
665 q_SSL_set_connect_state(a: ssl);
666 else
667 q_SSL_set_accept_state(a: ssl);
668
669 q_SSL_set_ex_data(ssl, idx: s_indexForSSLExtraData, arg: this);
670
671#ifndef OPENSSL_NO_PSK
672 // Set the client callback for PSK
673 if (mode == QSslSocket::SslClientMode)
674 q_SSL_set_psk_client_callback(ssl, callback: &q_ssl_psk_client_callback);
675 else if (mode == QSslSocket::SslServerMode)
676 q_SSL_set_psk_server_callback(ssl, callback: &q_ssl_psk_server_callback);
677
678#if OPENSSL_VERSION_NUMBER >= 0x10101006L
679 // Set the client callback for TLSv1.3 PSK
680 if (mode == QSslSocket::SslClientMode
681 && QSslSocket::sslLibraryBuildVersionNumber() >= 0x10101006L) {
682 q_SSL_set_psk_use_session_callback(s: ssl, &q_ssl_psk_use_session_callback);
683 }
684#endif // openssl version >= 0x10101006L
685
686#endif // OPENSSL_NO_PSK
687
688
689#if QT_CONFIG(ocsp)
690 if (configuration.ocspStaplingEnabled) {
691 if (mode == QSslSocket::SslServerMode) {
692 setErrorAndEmit(errorCode: QAbstractSocket::SslInvalidUserDataError,
693 errorString: QSslSocket::tr(s: "Server-side QSslSocket does not support OCSP stapling"));
694 return false;
695 }
696 if (q_SSL_set_tlsext_status_type(ssl, TLSEXT_STATUSTYPE_ocsp) != 1) {
697 setErrorAndEmit(errorCode: QAbstractSocket::SslInternalError,
698 errorString: QSslSocket::tr(s: "Failed to enable OCSP stapling"));
699 return false;
700 }
701 }
702
703 ocspResponseDer.clear();
704 auto responsePos = configuration.backendConfig.find(akey: "Qt-OCSP-response");
705 if (responsePos != configuration.backendConfig.end()) {
706 // This is our private, undocumented 'API' we use for the auto-testing of
707 // OCSP-stapling. It must be a der-encoded OCSP response, presumably set
708 // by tst_QOcsp.
709 const QVariant data(responsePos.value());
710 if (data.canConvert<QByteArray>())
711 ocspResponseDer = data.toByteArray();
712 }
713
714 if (ocspResponseDer.size()) {
715 if (mode != QSslSocket::SslServerMode) {
716 setErrorAndEmit(errorCode: QAbstractSocket::SslInvalidUserDataError,
717 errorString: QSslSocket::tr(s: "Client-side sockets do not send OCSP responses"));
718 return false;
719 }
720 }
721#endif // ocsp
722
723 return true;
724}
725
726void QSslSocketBackendPrivate::destroySslContext()
727{
728 if (ssl) {
729 if (!q_SSL_in_init(s: ssl) && !systemOrSslErrorDetected) {
730 // We do not send a shutdown alert here. Just mark the session as
731 // resumable for qhttpnetworkconnection's "optimization", otherwise
732 // OpenSSL won't start a session resumption.
733 if (q_SSL_shutdown(a: ssl) != 1) {
734 // Some error may be queued, clear it.
735 const auto errors = getErrorsFromOpenSsl();
736 Q_UNUSED(errors);
737 }
738 }
739 q_SSL_free(a: ssl);
740 ssl = nullptr;
741 }
742 sslContextPointer.clear();
743}
744
745/*!
746 \internal
747
748 Does the minimum amount of initialization to determine whether SSL
749 is supported or not.
750*/
751
752bool QSslSocketPrivate::supportsSsl()
753{
754 return ensureLibraryLoaded();
755}
756
757
758/*!
759 \internal
760
761 Returns the version number of the SSL library in use. Note that
762 this is the version of the library in use at run-time, not compile
763 time.
764*/
765long QSslSocketPrivate::sslLibraryVersionNumber()
766{
767 if (!supportsSsl())
768 return 0;
769
770 return q_OpenSSL_version_num();
771}
772
773/*!
774 \internal
775
776 Returns the version string of the SSL library in use. Note that
777 this is the version of the library in use at run-time, not compile
778 time. If no SSL support is available then this will return an empty value.
779*/
780QString QSslSocketPrivate::sslLibraryVersionString()
781{
782 if (!supportsSsl())
783 return QString();
784
785 const char *versionString = q_OpenSSL_version(OPENSSL_VERSION);
786 if (!versionString)
787 return QString();
788
789 return QString::fromLatin1(str: versionString);
790}
791
792/*!
793 \internal
794
795 Declared static in QSslSocketPrivate, makes sure the SSL libraries have
796 been initialized.
797*/
798void QSslSocketPrivate::ensureInitialized()
799{
800 if (!supportsSsl())
801 return;
802
803 ensureCiphersAndCertsLoaded();
804}
805
806/*!
807 \internal
808
809 Returns the version number of the SSL library in use at compile
810 time.
811*/
812long QSslSocketPrivate::sslLibraryBuildVersionNumber()
813{
814 return OPENSSL_VERSION_NUMBER;
815}
816
817/*!
818 \internal
819
820 Returns the version string of the SSL library in use at compile
821 time.
822*/
823QString QSslSocketPrivate::sslLibraryBuildVersionString()
824{
825 // Using QStringLiteral to store the version string as unicode and
826 // avoid false positives from Google searching the playstore for old
827 // SSL versions. See QTBUG-46265
828 return QStringLiteral(OPENSSL_VERSION_TEXT);
829}
830
831/*!
832 \internal
833
834 Declared static in QSslSocketPrivate, backend-dependent loading of
835 application-wide global ciphers.
836*/
837void QSslSocketPrivate::resetDefaultCiphers()
838{
839 SSL_CTX *myCtx = q_SSL_CTX_new(a: q_TLS_client_method());
840 // Note, we assert, not just silently return/bail out early:
841 // this should never happen and problems with OpenSSL's initialization
842 // must be caught before this (see supportsSsl()).
843 Q_ASSERT(myCtx);
844 SSL *mySsl = q_SSL_new(a: myCtx);
845 Q_ASSERT(mySsl);
846
847 QList<QSslCipher> ciphers;
848 QList<QSslCipher> defaultCiphers;
849
850 q_loadCiphersForConnection(connection: mySsl, ciphers, defaultCiphers);
851
852 q_SSL_CTX_free(a: myCtx);
853 q_SSL_free(a: mySsl);
854
855 setDefaultSupportedCiphers(ciphers);
856 setDefaultCiphers(defaultCiphers);
857
858#if QT_CONFIG(dtls)
859 ciphers.clear();
860 defaultCiphers.clear();
861 myCtx = q_SSL_CTX_new(a: q_DTLS_client_method());
862 if (myCtx) {
863 mySsl = q_SSL_new(a: myCtx);
864 if (mySsl) {
865 q_loadCiphersForConnection(connection: mySsl, ciphers, defaultCiphers);
866 q_setDefaultDtlsCiphers(ciphers: defaultCiphers);
867 q_SSL_free(a: mySsl);
868 }
869 q_SSL_CTX_free(a: myCtx);
870 }
871#endif // dtls
872}
873
874void QSslSocketPrivate::resetDefaultEllipticCurves()
875{
876 QVector<QSslEllipticCurve> curves;
877
878#ifndef OPENSSL_NO_EC
879 const size_t curveCount = q_EC_get_builtin_curves(r: nullptr, nitems: 0);
880
881 QVarLengthArray<EC_builtin_curve> builtinCurves(static_cast<int>(curveCount));
882
883 if (q_EC_get_builtin_curves(r: builtinCurves.data(), nitems: curveCount) == curveCount) {
884 curves.reserve(asize: int(curveCount));
885 for (size_t i = 0; i < curveCount; ++i) {
886 QSslEllipticCurve curve;
887 curve.id = builtinCurves[int(i)].nid;
888 curves.append(t: curve);
889 }
890 }
891#endif // OPENSSL_NO_EC
892
893 // set the list of supported ECs, but not the list
894 // of *default* ECs. OpenSSL doesn't like forcing an EC for the wrong
895 // ciphersuite, so don't try it -- leave the empty list to mean
896 // "the implementation will choose the most suitable one".
897 setDefaultSupportedEllipticCurves(curves);
898}
899
900#ifndef Q_OS_DARWIN // Apple implementation in qsslsocket_mac_shared.cpp
901QList<QSslCertificate> QSslSocketPrivate::systemCaCertificates()
902{
903 ensureInitialized();
904#ifdef QSSLSOCKET_DEBUG
905 QElapsedTimer timer;
906 timer.start();
907#endif
908 QList<QSslCertificate> systemCerts;
909#if defined(Q_OS_WIN)
910 HCERTSTORE hSystemStore;
911 hSystemStore = CertOpenSystemStoreW(0, L"ROOT");
912 if (hSystemStore) {
913 PCCERT_CONTEXT pc = nullptr;
914 while (1) {
915 pc = CertFindCertificateInStore(hSystemStore, X509_ASN_ENCODING, 0, CERT_FIND_ANY, nullptr, pc);
916 if (!pc)
917 break;
918 QByteArray der(reinterpret_cast<const char *>(pc->pbCertEncoded),
919 static_cast<int>(pc->cbCertEncoded));
920 QSslCertificate cert(der, QSsl::Der);
921 systemCerts.append(cert);
922 }
923 CertCloseStore(hSystemStore, 0);
924 }
925#elif defined(Q_OS_UNIX)
926 QSet<QString> certFiles;
927 QDir currentDir;
928 QStringList nameFilters;
929 QList<QByteArray> directories;
930 QSsl::EncodingFormat platformEncodingFormat;
931# ifndef Q_OS_ANDROID
932 directories = unixRootCertDirectories();
933 nameFilters << QLatin1String("*.pem") << QLatin1String("*.crt");
934 platformEncodingFormat = QSsl::Pem;
935# else
936 // Q_OS_ANDROID
937 QByteArray ministroPath = qgetenv("MINISTRO_SSL_CERTS_PATH"); // Set by Ministro
938 directories << ministroPath;
939 nameFilters << QLatin1String("*.der");
940 platformEncodingFormat = QSsl::Der;
941# ifndef Q_OS_ANDROID_EMBEDDED
942 if (ministroPath.isEmpty()) {
943 QList<QByteArray> certificateData = fetchSslCertificateData();
944 for (int i = 0; i < certificateData.size(); ++i) {
945 systemCerts.append(QSslCertificate::fromData(certificateData.at(i), QSsl::Der));
946 }
947 } else
948# endif //Q_OS_ANDROID_EMBEDDED
949# endif //Q_OS_ANDROID
950 {
951 currentDir.setNameFilters(nameFilters);
952 for (int a = 0; a < directories.count(); a++) {
953 currentDir.setPath(QLatin1String(directories.at(i: a)));
954 QDirIterator it(currentDir);
955 while (it.hasNext()) {
956 it.next();
957 // use canonical path here to not load the same certificate twice if symlinked
958 certFiles.insert(value: it.fileInfo().canonicalFilePath());
959 }
960 }
961 for (const QString& file : qAsConst(t&: certFiles))
962 systemCerts.append(t: QSslCertificate::fromPath(path: file, format: platformEncodingFormat));
963# ifndef Q_OS_ANDROID
964 systemCerts.append(t: QSslCertificate::fromPath(path: QLatin1String("/etc/pki/tls/certs/ca-bundle.crt"), format: QSsl::Pem)); // Fedora, Mandriva
965 systemCerts.append(t: QSslCertificate::fromPath(path: QLatin1String("/usr/local/share/certs/ca-root-nss.crt"), format: QSsl::Pem)); // FreeBSD's ca_root_nss
966# endif
967 }
968#endif
969#ifdef QSSLSOCKET_DEBUG
970 qCDebug(lcSsl) << "systemCaCertificates retrieval time " << timer.elapsed() << "ms";
971 qCDebug(lcSsl) << "imported " << systemCerts.count() << " certificates";
972#endif
973
974 return systemCerts;
975}
976#endif // Q_OS_DARWIN
977
978void QSslSocketBackendPrivate::startClientEncryption()
979{
980 if (!initSslContext()) {
981 setErrorAndEmit(errorCode: QAbstractSocket::SslInternalError,
982 errorString: QSslSocket::tr(s: "Unable to init SSL Context: %1").arg(a: getErrorsFromOpenSsl()));
983 return;
984 }
985
986 // Start connecting. This will place outgoing data in the BIO, so we
987 // follow up with calling transmit().
988 startHandshake();
989 transmit();
990}
991
992void QSslSocketBackendPrivate::startServerEncryption()
993{
994 if (!initSslContext()) {
995 setErrorAndEmit(errorCode: QAbstractSocket::SslInternalError,
996 errorString: QSslSocket::tr(s: "Unable to init SSL Context: %1").arg(a: getErrorsFromOpenSsl()));
997 return;
998 }
999
1000 // Start connecting. This will place outgoing data in the BIO, so we
1001 // follow up with calling transmit().
1002 startHandshake();
1003 transmit();
1004}
1005
1006/*!
1007 \internal
1008
1009 Transmits encrypted data between the BIOs and the socket.
1010*/
1011void QSslSocketBackendPrivate::transmit()
1012{
1013 Q_Q(QSslSocket);
1014
1015 using ScopedBool = QScopedValueRollback<bool>;
1016
1017 if (inSetAndEmitError)
1018 return;
1019
1020 // If we don't have any SSL context, don't bother transmitting.
1021 if (!ssl)
1022 return;
1023
1024 bool transmitting;
1025 do {
1026 transmitting = false;
1027
1028 // If the connection is secure, we can transfer data from the write
1029 // buffer (in plain text) to the write BIO through SSL_write.
1030 if (connectionEncrypted && !writeBuffer.isEmpty()) {
1031 qint64 totalBytesWritten = 0;
1032 int nextDataBlockSize;
1033 while ((nextDataBlockSize = writeBuffer.nextDataBlockSize()) > 0) {
1034 int writtenBytes = q_SSL_write(a: ssl, b: writeBuffer.readPointer(), c: nextDataBlockSize);
1035 if (writtenBytes <= 0) {
1036 int error = q_SSL_get_error(a: ssl, b: writtenBytes);
1037 //write can result in a want_write_error - not an error - continue transmitting
1038 if (error == SSL_ERROR_WANT_WRITE) {
1039 transmitting = true;
1040 break;
1041 } else if (error == SSL_ERROR_WANT_READ) {
1042 //write can result in a want_read error, possibly due to renegotiation - not an error - stop transmitting
1043 transmitting = false;
1044 break;
1045 } else {
1046 // ### Better error handling.
1047 const ScopedBool bg(inSetAndEmitError, true);
1048 setErrorAndEmit(errorCode: QAbstractSocket::SslInternalError,
1049 errorString: QSslSocket::tr(s: "Unable to write data: %1").arg(
1050 a: getErrorsFromOpenSsl()));
1051 return;
1052 }
1053 }
1054#ifdef QSSLSOCKET_DEBUG
1055 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: encrypted" << writtenBytes << "bytes";
1056#endif
1057 writeBuffer.free(bytes: writtenBytes);
1058 totalBytesWritten += writtenBytes;
1059
1060 if (writtenBytes < nextDataBlockSize) {
1061 // break out of the writing loop and try again after we had read
1062 transmitting = true;
1063 break;
1064 }
1065 }
1066
1067 if (totalBytesWritten > 0) {
1068 // Don't emit bytesWritten() recursively.
1069 if (!emittedBytesWritten) {
1070 emittedBytesWritten = true;
1071 emit q->bytesWritten(bytes: totalBytesWritten);
1072 emittedBytesWritten = false;
1073 }
1074 emit q->channelBytesWritten(channel: 0, bytes: totalBytesWritten);
1075 }
1076 }
1077
1078 // Check if we've got any data to be written to the socket.
1079 QVarLengthArray<char, 4096> data;
1080 int pendingBytes;
1081 while (plainSocket->isValid() && (pendingBytes = q_BIO_pending(writeBio)) > 0
1082 && plainSocket->openMode() != QIODevice::NotOpen) {
1083 // Read encrypted data from the write BIO into a buffer.
1084 data.resize(asize: pendingBytes);
1085 int encryptedBytesRead = q_BIO_read(a: writeBio, b: data.data(), c: pendingBytes);
1086
1087 // Write encrypted data from the buffer to the socket.
1088 qint64 actualWritten = plainSocket->write(data: data.constData(), len: encryptedBytesRead);
1089#ifdef QSSLSOCKET_DEBUG
1090 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: wrote" << encryptedBytesRead << "encrypted bytes to the socket" << actualWritten << "actual.";
1091#endif
1092 if (actualWritten < 0) {
1093 //plain socket write fails if it was in the pending close state.
1094 const ScopedBool bg(inSetAndEmitError, true);
1095 setErrorAndEmit(errorCode: plainSocket->error(), errorString: plainSocket->errorString());
1096 return;
1097 }
1098 transmitting = true;
1099 }
1100
1101 // Check if we've got any data to be read from the socket.
1102 if (!connectionEncrypted || !readBufferMaxSize || buffer.size() < readBufferMaxSize)
1103 while ((pendingBytes = plainSocket->bytesAvailable()) > 0) {
1104 // Read encrypted data from the socket into a buffer.
1105 data.resize(asize: pendingBytes);
1106 // just peek() here because q_BIO_write could write less data than expected
1107 int encryptedBytesRead = plainSocket->peek(data: data.data(), maxlen: pendingBytes);
1108
1109#ifdef QSSLSOCKET_DEBUG
1110 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: read" << encryptedBytesRead << "encrypted bytes from the socket";
1111#endif
1112 // Write encrypted data from the buffer into the read BIO.
1113 int writtenToBio = q_BIO_write(a: readBio, b: data.constData(), c: encryptedBytesRead);
1114
1115 // Throw away the results.
1116 if (writtenToBio > 0) {
1117 plainSocket->skip(maxSize: writtenToBio);
1118 } else {
1119 // ### Better error handling.
1120 const ScopedBool bg(inSetAndEmitError, true);
1121 setErrorAndEmit(errorCode: QAbstractSocket::SslInternalError,
1122 errorString: QSslSocket::tr(s: "Unable to decrypt data: %1").arg(
1123 a: getErrorsFromOpenSsl()));
1124 return;
1125 }
1126
1127 transmitting = true;
1128 }
1129
1130 // If the connection isn't secured yet, this is the time to retry the
1131 // connect / accept.
1132 if (!connectionEncrypted) {
1133#ifdef QSSLSOCKET_DEBUG
1134 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: testing encryption";
1135#endif
1136 if (startHandshake()) {
1137#ifdef QSSLSOCKET_DEBUG
1138 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: encryption established";
1139#endif
1140 connectionEncrypted = true;
1141 transmitting = true;
1142 } else if (plainSocket->state() != QAbstractSocket::ConnectedState) {
1143#ifdef QSSLSOCKET_DEBUG
1144 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: connection lost";
1145#endif
1146 break;
1147 } else if (paused) {
1148 // just wait until the user continues
1149 return;
1150 } else {
1151#ifdef QSSLSOCKET_DEBUG
1152 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: encryption not done yet";
1153#endif
1154 }
1155 }
1156
1157 // If the request is small and the remote host closes the transmission
1158 // after sending, there's a chance that startHandshake() will already
1159 // have triggered a shutdown.
1160 if (!ssl)
1161 continue;
1162
1163 // We always read everything from the SSL decryption buffers, even if
1164 // we have a readBufferMaxSize. There's no point in leaving data there
1165 // just so that readBuffer.size() == readBufferMaxSize.
1166 int readBytes = 0;
1167 const int bytesToRead = 4096;
1168 do {
1169 if (readChannelCount == 0) {
1170 // The read buffer is deallocated, don't try resize or write to it.
1171 break;
1172 }
1173 // Don't use SSL_pending(). It's very unreliable.
1174 inSslRead = true;
1175 readBytes = q_SSL_read(a: ssl, b: buffer.reserve(bytes: bytesToRead), c: bytesToRead);
1176 inSslRead = false;
1177 if (renegotiated) {
1178 renegotiated = false;
1179 X509 *x509 = q_SSL_get_peer_certificate(a: ssl);
1180 const auto peerCertificate =
1181 QSslCertificatePrivate::QSslCertificate_from_X509(x509);
1182 // Fail the renegotiate if the certificate has changed, else: continue.
1183 if (peerCertificate != q->peerCertificate()) {
1184 const ScopedBool bg(inSetAndEmitError, true);
1185 setErrorAndEmit(
1186 errorCode: QAbstractSocket::RemoteHostClosedError,
1187 errorString: QSslSocket::tr(
1188 s: "TLS certificate unexpectedly changed during renegotiation!"));
1189 q->abort();
1190 return;
1191 }
1192 }
1193 if (readBytes > 0) {
1194#ifdef QSSLSOCKET_DEBUG
1195 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: decrypted" << readBytes << "bytes";
1196#endif
1197 buffer.chop(bytes: bytesToRead - readBytes);
1198
1199 if (readyReadEmittedPointer)
1200 *readyReadEmittedPointer = true;
1201 emit q->readyRead();
1202 emit q->channelReadyRead(channel: 0);
1203 transmitting = true;
1204 continue;
1205 }
1206 buffer.chop(bytes: bytesToRead);
1207
1208 // Error.
1209 switch (q_SSL_get_error(a: ssl, b: readBytes)) {
1210 case SSL_ERROR_WANT_READ:
1211 case SSL_ERROR_WANT_WRITE:
1212 // Out of data.
1213 break;
1214 case SSL_ERROR_ZERO_RETURN:
1215 // The remote host closed the connection.
1216#ifdef QSSLSOCKET_DEBUG
1217 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: remote disconnect";
1218#endif
1219 shutdown = true; // the other side shut down, make sure we do not send shutdown ourselves
1220 {
1221 const ScopedBool bg(inSetAndEmitError, true);
1222 setErrorAndEmit(errorCode: QAbstractSocket::RemoteHostClosedError,
1223 errorString: QSslSocket::tr(s: "The TLS/SSL connection has been closed"));
1224 }
1225 return;
1226 case SSL_ERROR_SYSCALL: // some IO error
1227 case SSL_ERROR_SSL: // error in the SSL library
1228 // we do not know exactly what the error is, nor whether we can recover from it,
1229 // so just return to prevent an endless loop in the outer "while" statement
1230 systemOrSslErrorDetected = true;
1231 {
1232 const ScopedBool bg(inSetAndEmitError, true);
1233 setErrorAndEmit(errorCode: QAbstractSocket::SslInternalError,
1234 errorString: QSslSocket::tr(s: "Error while reading: %1").arg(a: getErrorsFromOpenSsl()));
1235 }
1236 return;
1237 default:
1238 // SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT: can only happen with a
1239 // BIO_s_connect() or BIO_s_accept(), which we do not call.
1240 // SSL_ERROR_WANT_X509_LOOKUP: can only happen with a
1241 // SSL_CTX_set_client_cert_cb(), which we do not call.
1242 // So this default case should never be triggered.
1243 {
1244 const ScopedBool bg(inSetAndEmitError, true);
1245 setErrorAndEmit(errorCode: QAbstractSocket::SslInternalError,
1246 errorString: QSslSocket::tr(s: "Error while reading: %1").arg(a: getErrorsFromOpenSsl()));
1247 }
1248 break;
1249 }
1250 } while (ssl && readBytes > 0);
1251 } while (ssl && transmitting);
1252}
1253
1254QSslError _q_OpenSSL_to_QSslError(int errorCode, const QSslCertificate &cert)
1255{
1256 QSslError error;
1257 switch (errorCode) {
1258 case X509_V_OK:
1259 // X509_V_OK is also reported if the peer had no certificate.
1260 break;
1261 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1262 error = QSslError(QSslError::UnableToGetIssuerCertificate, cert); break;
1263 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1264 error = QSslError(QSslError::UnableToDecryptCertificateSignature, cert); break;
1265 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1266 error = QSslError(QSslError::UnableToDecodeIssuerPublicKey, cert); break;
1267 case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1268 error = QSslError(QSslError::CertificateSignatureFailed, cert); break;
1269 case X509_V_ERR_CERT_NOT_YET_VALID:
1270 error = QSslError(QSslError::CertificateNotYetValid, cert); break;
1271 case X509_V_ERR_CERT_HAS_EXPIRED:
1272 error = QSslError(QSslError::CertificateExpired, cert); break;
1273 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1274 error = QSslError(QSslError::InvalidNotBeforeField, cert); break;
1275 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1276 error = QSslError(QSslError::InvalidNotAfterField, cert); break;
1277 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1278 error = QSslError(QSslError::SelfSignedCertificate, cert); break;
1279 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1280 error = QSslError(QSslError::SelfSignedCertificateInChain, cert); break;
1281 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1282 error = QSslError(QSslError::UnableToGetLocalIssuerCertificate, cert); break;
1283 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1284 error = QSslError(QSslError::UnableToVerifyFirstCertificate, cert); break;
1285 case X509_V_ERR_CERT_REVOKED:
1286 error = QSslError(QSslError::CertificateRevoked, cert); break;
1287 case X509_V_ERR_INVALID_CA:
1288 error = QSslError(QSslError::InvalidCaCertificate, cert); break;
1289 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1290 error = QSslError(QSslError::PathLengthExceeded, cert); break;
1291 case X509_V_ERR_INVALID_PURPOSE:
1292 error = QSslError(QSslError::InvalidPurpose, cert); break;
1293 case X509_V_ERR_CERT_UNTRUSTED:
1294 error = QSslError(QSslError::CertificateUntrusted, cert); break;
1295 case X509_V_ERR_CERT_REJECTED:
1296 error = QSslError(QSslError::CertificateRejected, cert); break;
1297 default:
1298 error = QSslError(QSslError::UnspecifiedError, cert); break;
1299 }
1300 return error;
1301}
1302
1303QString QSslSocketBackendPrivate::msgErrorsDuringHandshake()
1304{
1305 return QSslSocket::tr(s: "Error during SSL handshake: %1")
1306 .arg(a: QSslSocketBackendPrivate::getErrorsFromOpenSsl());
1307}
1308
1309bool QSslSocketBackendPrivate::startHandshake()
1310{
1311 Q_Q(QSslSocket);
1312
1313 // Check if the connection has been established. Get all errors from the
1314 // verification stage.
1315
1316 using ScopedBool = QScopedValueRollback<bool>;
1317
1318 if (inSetAndEmitError)
1319 return false;
1320
1321 QVector<QSslErrorEntry> lastErrors;
1322 q_SSL_set_ex_data(ssl, idx: s_indexForSSLExtraData + 1, arg: &lastErrors);
1323 int result = (mode == QSslSocket::SslClientMode) ? q_SSL_connect(a: ssl) : q_SSL_accept(a: ssl);
1324 q_SSL_set_ex_data(ssl, idx: s_indexForSSLExtraData + 1, arg: nullptr);
1325
1326 if (!lastErrors.isEmpty())
1327 storePeerCertificates();
1328 for (const auto &currentError : qAsConst(t&: lastErrors)) {
1329 emit q->peerVerifyError(error: _q_OpenSSL_to_QSslError(errorCode: currentError.code,
1330 cert: configuration.peerCertificateChain.value(i: currentError.depth)));
1331 if (q->state() != QAbstractSocket::ConnectedState)
1332 break;
1333 }
1334
1335 errorList << lastErrors;
1336
1337 // Connection aborted during handshake phase.
1338 if (q->state() != QAbstractSocket::ConnectedState)
1339 return false;
1340
1341 // Check if we're encrypted or not.
1342 if (result <= 0) {
1343 switch (q_SSL_get_error(a: ssl, b: result)) {
1344 case SSL_ERROR_WANT_READ:
1345 case SSL_ERROR_WANT_WRITE:
1346 // The handshake is not yet complete.
1347 break;
1348 default:
1349 QString errorString = QSslSocketBackendPrivate::msgErrorsDuringHandshake();
1350#ifdef QSSLSOCKET_DEBUG
1351 qCDebug(lcSsl) << "QSslSocketBackendPrivate::startHandshake: error!" << errorString;
1352#endif
1353 {
1354 const ScopedBool bg(inSetAndEmitError, true);
1355 setErrorAndEmit(errorCode: QAbstractSocket::SslHandshakeFailedError, errorString);
1356 }
1357 q->abort();
1358 }
1359 return false;
1360 }
1361
1362 // store peer certificate chain
1363 storePeerCertificates();
1364
1365 // Start translating errors.
1366 QList<QSslError> errors;
1367
1368 // check the whole chain for blacklisting (including root, as we check for subjectInfo and issuer)
1369 for (const QSslCertificate &cert : qAsConst(t&: configuration.peerCertificateChain)) {
1370 if (QSslCertificatePrivate::isBlacklisted(certificate: cert)) {
1371 QSslError error(QSslError::CertificateBlacklisted, cert);
1372 errors << error;
1373 emit q->peerVerifyError(error);
1374 if (q->state() != QAbstractSocket::ConnectedState)
1375 return false;
1376 }
1377 }
1378
1379 const bool doVerifyPeer = configuration.peerVerifyMode == QSslSocket::VerifyPeer
1380 || (configuration.peerVerifyMode == QSslSocket::AutoVerifyPeer
1381 && mode == QSslSocket::SslClientMode);
1382
1383#if QT_CONFIG(ocsp)
1384 // For now it's always QSslSocket::SslClientMode - initSslContext() will bail out early,
1385 // if it's enabled in QSslSocket::SslServerMode. This can change.
1386 if (!configuration.peerCertificate.isNull() && configuration.ocspStaplingEnabled && doVerifyPeer) {
1387 if (!checkOcspStatus()) {
1388 if (ocspErrors.isEmpty()) {
1389 {
1390 const ScopedBool bg(inSetAndEmitError, true);
1391 setErrorAndEmit(errorCode: QAbstractSocket::SslHandshakeFailedError, errorString: ocspErrorDescription);
1392 }
1393 q->abort();
1394 return false;
1395 }
1396
1397 for (const QSslError &error : ocspErrors) {
1398 errors << error;
1399 emit q->peerVerifyError(error);
1400 if (q->state() != QAbstractSocket::ConnectedState)
1401 return false;
1402 }
1403 }
1404 }
1405#endif // ocsp
1406
1407 // Check the peer certificate itself. First try the subject's common name
1408 // (CN) as a wildcard, then try all alternate subject name DNS entries the
1409 // same way.
1410 if (!configuration.peerCertificate.isNull()) {
1411 // but only if we're a client connecting to a server
1412 // if we're the server, don't check CN
1413 if (mode == QSslSocket::SslClientMode) {
1414 QString peerName = (verificationPeerName.isEmpty () ? q->peerName() : verificationPeerName);
1415
1416 if (!isMatchingHostname(cert: configuration.peerCertificate, peerName)) {
1417 // No matches in common names or alternate names.
1418 QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate);
1419 errors << error;
1420 emit q->peerVerifyError(error);
1421 if (q->state() != QAbstractSocket::ConnectedState)
1422 return false;
1423 }
1424 }
1425 } else {
1426 // No peer certificate presented. Report as error if the socket
1427 // expected one.
1428 if (doVerifyPeer) {
1429 QSslError error(QSslError::NoPeerCertificate);
1430 errors << error;
1431 emit q->peerVerifyError(error);
1432 if (q->state() != QAbstractSocket::ConnectedState)
1433 return false;
1434 }
1435 }
1436
1437 // Translate errors from the error list into QSslErrors.
1438 errors.reserve(alloc: errors.size() + errorList.size());
1439 for (const auto &error : qAsConst(t&: errorList))
1440 errors << _q_OpenSSL_to_QSslError(errorCode: error.code, cert: configuration.peerCertificateChain.value(i: error.depth));
1441
1442 if (!errors.isEmpty()) {
1443 sslErrors = errors;
1444
1445#ifdef Q_OS_WIN
1446 const bool fetchEnabled = s_loadRootCertsOnDemand
1447 && allowRootCertOnDemandLoading;
1448 // !fetchEnabled is a special case scenario, when we potentially have a missing
1449 // intermediate certificate and a recoverable chain, but on demand cert loading
1450 // was disabled by setCaCertificates call. For this scenario we check if "Authority
1451 // Information Access" is present - wincrypt can deal with such certificates.
1452 QSslCertificate certToFetch;
1453 if (doVerifyPeer && !verifyErrorsHaveBeenIgnored())
1454 certToFetch = findCertificateToFetch(sslErrors, !fetchEnabled);
1455
1456 //Skip this if not using system CAs, or if the SSL errors are configured in advance to be ignorable
1457 if (!certToFetch.isNull()) {
1458 fetchAuthorityInformation = !fetchEnabled;
1459 //Windows desktop versions starting from vista ship with minimal set of roots and download on demand
1460 //from the windows update server CA roots that are trusted by MS. It also can fetch a missing intermediate
1461 //in case "Authority Information Access" extension is present.
1462 //
1463 //However, this is only transparent if using WinINET - we have to trigger it
1464 //ourselves.
1465 fetchCaRootForCert(certToFetch);
1466 return false;
1467 }
1468#endif
1469 if (!checkSslErrors())
1470 return false;
1471 // A slot, attached to sslErrors signal can call
1472 // abort/close/disconnetFromHost/etc; no need to
1473 // continue handshake then.
1474 if (q->state() != QAbstractSocket::ConnectedState)
1475 return false;
1476 } else {
1477 sslErrors.clear();
1478 }
1479
1480 continueHandshake();
1481 return true;
1482}
1483
1484void QSslSocketBackendPrivate::storePeerCertificates()
1485{
1486 // Store the peer certificate and chain. For clients, the peer certificate
1487 // chain includes the peer certificate; for servers, it doesn't. Both the
1488 // peer certificate and the chain may be empty if the peer didn't present
1489 // any certificate.
1490 X509 *x509 = q_SSL_get_peer_certificate(a: ssl);
1491 configuration.peerCertificate = QSslCertificatePrivate::QSslCertificate_from_X509(x509);
1492 q_X509_free(a: x509);
1493 if (configuration.peerCertificateChain.isEmpty()) {
1494 configuration.peerCertificateChain = STACKOFX509_to_QSslCertificates(x509: q_SSL_get_peer_cert_chain(a: ssl));
1495 if (!configuration.peerCertificate.isNull() && mode == QSslSocket::SslServerMode)
1496 configuration.peerCertificateChain.prepend(t: configuration.peerCertificate);
1497 }
1498}
1499
1500int QSslSocketBackendPrivate::handleNewSessionTicket(SSL *connection)
1501{
1502 // If we return 1, this means we own the session, but we don't.
1503 // 0 would tell OpenSSL to deref (but they still have it in the
1504 // internal cache).
1505 Q_Q(QSslSocket);
1506
1507 Q_ASSERT(connection);
1508
1509 if (q->sslConfiguration().testSslOption(option: QSsl::SslOptionDisableSessionPersistence)) {
1510 // We silently ignore, do nothing, remove from cache.
1511 return 0;
1512 }
1513
1514 SSL_SESSION *currentSession = q_SSL_get_session(ssl: connection);
1515 if (!currentSession) {
1516 qCWarning(lcSsl,
1517 "New session ticket callback, the session is invalid (nullptr)");
1518 return 0;
1519 }
1520
1521 if (q_SSL_version(a: connection) < 0x304) {
1522 // We only rely on this mechanics with TLS >= 1.3
1523 return 0;
1524 }
1525
1526#ifdef TLS1_3_VERSION
1527 if (!q_SSL_SESSION_is_resumable(s: currentSession)) {
1528 qCDebug(lcSsl, "New session ticket, but the session is non-resumable");
1529 return 0;
1530 }
1531#endif // TLS1_3_VERSION
1532
1533 const int sessionSize = q_i2d_SSL_SESSION(in: currentSession, pp: nullptr);
1534 if (sessionSize <= 0) {
1535 qCWarning(lcSsl, "could not store persistent version of SSL session");
1536 return 0;
1537 }
1538
1539 // We have somewhat perverse naming, it's not a ticket, it's a session.
1540 QByteArray sessionTicket(sessionSize, 0);
1541 auto data = reinterpret_cast<unsigned char *>(sessionTicket.data());
1542 if (!q_i2d_SSL_SESSION(in: currentSession, pp: &data)) {
1543 qCWarning(lcSsl, "could not store persistent version of SSL session");
1544 return 0;
1545 }
1546
1547 configuration.sslSession = sessionTicket;
1548 configuration.sslSessionTicketLifeTimeHint = int(q_SSL_SESSION_get_ticket_lifetime_hint(session: currentSession));
1549
1550 emit q->newSessionTicketReceived();
1551 return 0;
1552}
1553
1554bool QSslSocketBackendPrivate::checkSslErrors()
1555{
1556 Q_Q(QSslSocket);
1557 if (sslErrors.isEmpty())
1558 return true;
1559
1560 emit q->sslErrors(errors: sslErrors);
1561
1562 bool doVerifyPeer = configuration.peerVerifyMode == QSslSocket::VerifyPeer
1563 || (configuration.peerVerifyMode == QSslSocket::AutoVerifyPeer
1564 && mode == QSslSocket::SslClientMode);
1565 bool doEmitSslError = !verifyErrorsHaveBeenIgnored();
1566 // check whether we need to emit an SSL handshake error
1567 if (doVerifyPeer && doEmitSslError) {
1568 if (q->pauseMode() & QAbstractSocket::PauseOnSslErrors) {
1569 pauseSocketNotifiers(q);
1570 paused = true;
1571 } else {
1572 setErrorAndEmit(errorCode: QAbstractSocket::SslHandshakeFailedError, errorString: sslErrors.constFirst().errorString());
1573 plainSocket->disconnectFromHost();
1574 }
1575 return false;
1576 }
1577 return true;
1578}
1579
1580unsigned int QSslSocketBackendPrivate::tlsPskClientCallback(const char *hint,
1581 char *identity, unsigned int max_identity_len,
1582 unsigned char *psk, unsigned int max_psk_len)
1583{
1584 QSslPreSharedKeyAuthenticator authenticator;
1585
1586 // Fill in some read-only fields (for the user)
1587 if (hint)
1588 authenticator.d->identityHint = QByteArray::fromRawData(hint, size: int(::strlen(s: hint))); // it's NUL terminated, but do not include the NUL
1589
1590 authenticator.d->maximumIdentityLength = int(max_identity_len) - 1; // needs to be NUL terminated
1591 authenticator.d->maximumPreSharedKeyLength = int(max_psk_len);
1592
1593 // Let the client provide the remaining bits...
1594 Q_Q(QSslSocket);
1595 emit q->preSharedKeyAuthenticationRequired(authenticator: &authenticator);
1596
1597 // No PSK set? Return now to make the handshake fail
1598 if (authenticator.preSharedKey().isEmpty())
1599 return 0;
1600
1601 // Copy data back into OpenSSL
1602 const int identityLength = qMin(a: authenticator.identity().length(), b: authenticator.maximumIdentityLength());
1603 ::memcpy(dest: identity, src: authenticator.identity().constData(), n: identityLength);
1604 identity[identityLength] = 0;
1605
1606 const int pskLength = qMin(a: authenticator.preSharedKey().length(), b: authenticator.maximumPreSharedKeyLength());
1607 ::memcpy(dest: psk, src: authenticator.preSharedKey().constData(), n: pskLength);
1608 return pskLength;
1609}
1610
1611unsigned int QSslSocketBackendPrivate::tlsPskServerCallback(const char *identity,
1612 unsigned char *psk, unsigned int max_psk_len)
1613{
1614 QSslPreSharedKeyAuthenticator authenticator;
1615
1616 // Fill in some read-only fields (for the user)
1617 authenticator.d->identityHint = configuration.preSharedKeyIdentityHint;
1618 authenticator.d->identity = identity;
1619 authenticator.d->maximumIdentityLength = 0; // user cannot set an identity
1620 authenticator.d->maximumPreSharedKeyLength = int(max_psk_len);
1621
1622 // Let the client provide the remaining bits...
1623 Q_Q(QSslSocket);
1624 emit q->preSharedKeyAuthenticationRequired(authenticator: &authenticator);
1625
1626 // No PSK set? Return now to make the handshake fail
1627 if (authenticator.preSharedKey().isEmpty())
1628 return 0;
1629
1630 // Copy data back into OpenSSL
1631 const int pskLength = qMin(a: authenticator.preSharedKey().length(), b: authenticator.maximumPreSharedKeyLength());
1632 ::memcpy(dest: psk, src: authenticator.preSharedKey().constData(), n: pskLength);
1633 return pskLength;
1634}
1635
1636bool QSslSocketBackendPrivate::isInSslRead() const
1637{
1638 return inSslRead;
1639}
1640
1641void QSslSocketBackendPrivate::setRenegotiated(bool renegotiated)
1642{
1643 this->renegotiated = renegotiated;
1644}
1645
1646#ifdef Q_OS_WIN
1647
1648void QSslSocketBackendPrivate::fetchCaRootForCert(const QSslCertificate &cert)
1649{
1650 Q_Q(QSslSocket);
1651 //The root certificate is downloaded from windows update, which blocks for 15 seconds in the worst case
1652 //so the request is done in a worker thread.
1653 QList<QSslCertificate> customRoots;
1654 if (fetchAuthorityInformation)
1655 customRoots = configuration.caCertificates;
1656
1657 QWindowsCaRootFetcher *fetcher = new QWindowsCaRootFetcher(cert, mode, customRoots, q->peerVerifyName());
1658 QObject::connect(fetcher, SIGNAL(finished(QSslCertificate,QSslCertificate)), q, SLOT(_q_caRootLoaded(QSslCertificate,QSslCertificate)), Qt::QueuedConnection);
1659 QMetaObject::invokeMethod(fetcher, "start", Qt::QueuedConnection);
1660 pauseSocketNotifiers(q);
1661 paused = true;
1662}
1663
1664//This is the callback from QWindowsCaRootFetcher, trustedRoot will be invalid (default constructed) if it failed.
1665void QSslSocketBackendPrivate::_q_caRootLoaded(QSslCertificate cert, QSslCertificate trustedRoot)
1666{
1667 if (fetchAuthorityInformation) {
1668 if (!configuration.caCertificates.contains(trustedRoot))
1669 trustedRoot = QSslCertificate{};
1670 fetchAuthorityInformation = false;
1671 }
1672
1673 if (!trustedRoot.isNull() && !trustedRoot.isBlacklisted()) {
1674 if (s_loadRootCertsOnDemand) {
1675 //Add the new root cert to default cert list for use by future sockets
1676 QSslSocket::addDefaultCaCertificate(trustedRoot);
1677 }
1678 //Add the new root cert to this socket for future connections
1679 if (!configuration.caCertificates.contains(trustedRoot))
1680 configuration.caCertificates += trustedRoot;
1681 //Remove the broken chain ssl errors (as chain is verified by windows)
1682 for (int i=sslErrors.count() - 1; i >= 0; --i) {
1683 if (sslErrors.at(i).certificate() == cert) {
1684 switch (sslErrors.at(i).error()) {
1685 case QSslError::UnableToGetLocalIssuerCertificate:
1686 case QSslError::CertificateUntrusted:
1687 case QSslError::UnableToVerifyFirstCertificate:
1688 case QSslError::SelfSignedCertificateInChain:
1689 // error can be ignored if OS says the chain is trusted
1690 sslErrors.removeAt(i);
1691 break;
1692 default:
1693 // error cannot be ignored
1694 break;
1695 }
1696 }
1697 }
1698 }
1699
1700 // Continue with remaining errors
1701 if (plainSocket)
1702 plainSocket->resume();
1703 paused = false;
1704 if (checkSslErrors() && ssl) {
1705 bool willClose = (autoStartHandshake && pendingClose);
1706 continueHandshake();
1707 if (!willClose)
1708 transmit();
1709 }
1710}
1711
1712#endif
1713
1714#if QT_CONFIG(ocsp)
1715
1716bool QSslSocketBackendPrivate::checkOcspStatus()
1717{
1718 Q_ASSERT(ssl);
1719 Q_ASSERT(mode == QSslSocket::SslClientMode); // See initSslContext() for SslServerMode
1720 Q_ASSERT(configuration.peerVerifyMode != QSslSocket::VerifyNone);
1721
1722 const auto clearErrorQueue = qScopeGuard(f: [] {
1723 logAndClearErrorQueue();
1724 });
1725
1726 ocspResponses.clear();
1727 ocspErrorDescription.clear();
1728 ocspErrors.clear();
1729
1730 const unsigned char *responseData = nullptr;
1731 const long responseLength = q_SSL_get_tlsext_status_ocsp_resp(ssl, &responseData);
1732 if (responseLength <= 0 || !responseData) {
1733 ocspErrors.push_back(t: QSslError::OcspNoResponseFound);
1734 return false;
1735 }
1736
1737 OCSP_RESPONSE *response = q_d2i_OCSP_RESPONSE(a: nullptr, in: &responseData, len: responseLength);
1738 if (!response) {
1739 // Treat this as a fatal SslHandshakeError.
1740 ocspErrorDescription = QSslSocket::tr(s: "Failed to decode OCSP response");
1741 return false;
1742 }
1743 const QSharedPointer<OCSP_RESPONSE> responseGuard(response, q_OCSP_RESPONSE_free);
1744
1745 const int ocspStatus = q_OCSP_response_status(resp: response);
1746 if (ocspStatus != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1747 // It's not a definitive response, it's an error message (not signed by the responder).
1748 ocspErrors.push_back(t: qt_OCSP_response_status_to_QSslError(code: ocspStatus));
1749 return false;
1750 }
1751
1752 OCSP_BASICRESP *basicResponse = q_OCSP_response_get1_basic(resp: response);
1753 if (!basicResponse) {
1754 // SslHandshakeError.
1755 ocspErrorDescription = QSslSocket::tr(s: "Failed to extract basic OCSP response");
1756 return false;
1757 }
1758 const QSharedPointer<OCSP_BASICRESP> basicResponseGuard(basicResponse, q_OCSP_BASICRESP_free);
1759
1760 SSL_CTX *ctx = q_SSL_get_SSL_CTX(a: ssl); // Does not increment refcount.
1761 Q_ASSERT(ctx);
1762 X509_STORE *store = q_SSL_CTX_get_cert_store(a: ctx); // Does not increment refcount.
1763 if (!store) {
1764 // SslHandshakeError.
1765 ocspErrorDescription = QSslSocket::tr(s: "No certificate verification store, cannot verify OCSP response");
1766 return false;
1767 }
1768
1769 STACK_OF(X509) *peerChain = q_SSL_get_peer_cert_chain(a: ssl); // Does not increment refcount.
1770 X509 *peerX509 = q_SSL_get_peer_certificate(a: ssl);
1771 Q_ASSERT(peerChain || peerX509);
1772 const QSharedPointer<X509> peerX509Guard(peerX509, q_X509_free);
1773 // OCSP_basic_verify with 0 as verificationFlags:
1774 //
1775 // 0) Tries to find the OCSP responder's certificate in either peerChain
1776 // or basicResponse->certs. If not found, verification fails.
1777 // 1) It checks the signature using the responder's public key.
1778 // 2) Then it tries to validate the responder's cert (building a chain
1779 // etc.)
1780 // 3) It checks CertID in response.
1781 // 4) Ensures the responder is authorized to sign the status respond.
1782 //
1783 // Note, OpenSSL prior to 1.0.2b would only use bs->certs to
1784 // verify the responder's chain (see their commit 4ba9a4265bd).
1785 // Working this around - is too much fuss for ancient versions we
1786 // are dropping quite soon anyway.
1787 const unsigned long verificationFlags = 0;
1788 const int success = q_OCSP_basic_verify(bs: basicResponse, certs: peerChain, st: store, flags: verificationFlags);
1789 if (success <= 0)
1790 ocspErrors.push_back(t: QSslError::OcspResponseCannotBeTrusted);
1791
1792 if (q_OCSP_resp_count(bs: basicResponse) != 1) {
1793 ocspErrors.push_back(t: QSslError::OcspMalformedResponse);
1794 return false;
1795 }
1796
1797 OCSP_SINGLERESP *singleResponse = q_OCSP_resp_get0(bs: basicResponse, idx: 0);
1798 if (!singleResponse) {
1799 ocspErrors.clear();
1800 // A fatal problem -> SslHandshakeError.
1801 ocspErrorDescription = QSslSocket::tr(s: "Failed to decode a SingleResponse from OCSP status response");
1802 return false;
1803 }
1804
1805 // Let's make sure the response is for the correct certificate - we
1806 // can re-create this CertID using our peer's certificate and its
1807 // issuer's public key.
1808 ocspResponses.push_back(t: QOcspResponse());
1809 QOcspResponsePrivate *dResponse = ocspResponses.back().d.data();
1810 dResponse->subjectCert = configuration.peerCertificate;
1811 bool matchFound = false;
1812 if (configuration.peerCertificate.isSelfSigned()) {
1813 dResponse->signerCert = configuration.peerCertificate;
1814 matchFound = qt_OCSP_certificate_match(singleResponse, peerCert: peerX509, issuer: peerX509);
1815 } else {
1816 const STACK_OF(X509) *certs = q_SSL_get_peer_cert_chain(a: ssl);
1817 if (!certs) // Oh, what a cataclysm! Last try:
1818 certs = q_OCSP_resp_get0_certs(bs: basicResponse);
1819 if (certs) {
1820 // It could be the first certificate in 'certs' is our peer's
1821 // certificate. Since it was not captured by the 'self-signed' branch
1822 // above, the CertID will not match and we'll just iterate on to the
1823 // next certificate. So we start from 0, not 1.
1824 for (int i = 0, e = q_sk_X509_num(certs); i < e; ++i) {
1825 X509 *issuer = q_sk_X509_value(certs, i);
1826 matchFound = qt_OCSP_certificate_match(singleResponse, peerCert: peerX509, issuer);
1827 if (matchFound) {
1828 if (q_X509_check_issued(a: issuer, b: peerX509) == X509_V_OK) {
1829 dResponse->signerCert = QSslCertificatePrivate::QSslCertificate_from_X509(x509: issuer);
1830 break;
1831 }
1832 matchFound = false;
1833 }
1834 }
1835 }
1836 }
1837
1838 if (!matchFound) {
1839 dResponse->signerCert.clear();
1840 ocspErrors.push_back(t: {QSslError::OcspResponseCertIdUnknown, configuration.peerCertificate});
1841 }
1842
1843 // Check if the response is valid time-wise:
1844 ASN1_GENERALIZEDTIME *revTime = nullptr;
1845 ASN1_GENERALIZEDTIME *thisUpdate = nullptr;
1846 ASN1_GENERALIZEDTIME *nextUpdate = nullptr;
1847 int reason;
1848 const int certStatus = q_OCSP_single_get0_status(single: singleResponse, reason: &reason, revtime: &revTime, thisupd: &thisUpdate, nextupd: &nextUpdate);
1849 if (!thisUpdate) {
1850 // This is unexpected, treat as SslHandshakeError, OCSP_check_validity assumes this pointer
1851 // to be != nullptr.
1852 ocspErrors.clear();
1853 ocspResponses.clear();
1854 ocspErrorDescription = QSslSocket::tr(s: "Failed to extract 'this update time' from the SingleResponse");
1855 return false;
1856 }
1857
1858 // OCSP_check_validity(this, next, nsec, maxsec) does this check:
1859 // this <= now <= next. They allow some freedom to account
1860 // for delays/time inaccuracy.
1861 // this > now + nsec ? -> NOT_YET_VALID
1862 // if maxsec >= 0:
1863 // now - maxsec > this ? -> TOO_OLD
1864 // now - nsec > next ? -> EXPIRED
1865 // next < this ? -> NEXT_BEFORE_THIS
1866 // OK.
1867 if (!q_OCSP_check_validity(thisupd: thisUpdate, nextupd: nextUpdate, nsec: 60, maxsec: -1))
1868 ocspErrors.push_back(t: {QSslError::OcspResponseExpired, configuration.peerCertificate});
1869
1870 // And finally, the status:
1871 switch (certStatus) {
1872 case V_OCSP_CERTSTATUS_GOOD:
1873 // This certificate was not found among the revoked ones.
1874 dResponse->certificateStatus = QOcspCertificateStatus::Good;
1875 break;
1876 case V_OCSP_CERTSTATUS_REVOKED:
1877 dResponse->certificateStatus = QOcspCertificateStatus::Revoked;
1878 dResponse->revocationReason = qt_OCSP_revocation_reason(reason);
1879 ocspErrors.push_back(t: {QSslError::CertificateRevoked, configuration.peerCertificate});
1880 break;
1881 case V_OCSP_CERTSTATUS_UNKNOWN:
1882 dResponse->certificateStatus = QOcspCertificateStatus::Unknown;
1883 ocspErrors.push_back(t: {QSslError::OcspStatusUnknown, configuration.peerCertificate});
1884 }
1885
1886 return !ocspErrors.size();
1887}
1888
1889#endif // ocsp
1890
1891void QSslSocketBackendPrivate::disconnectFromHost()
1892{
1893 if (ssl) {
1894 if (!shutdown && !q_SSL_in_init(s: ssl) && !systemOrSslErrorDetected) {
1895 if (q_SSL_shutdown(a: ssl) != 1) {
1896 // Some error may be queued, clear it.
1897 const auto errors = getErrorsFromOpenSsl();
1898 Q_UNUSED(errors);
1899 }
1900 shutdown = true;
1901 transmit();
1902 }
1903 }
1904 plainSocket->disconnectFromHost();
1905}
1906
1907void QSslSocketBackendPrivate::disconnected()
1908{
1909 if (plainSocket->bytesAvailable() <= 0)
1910 destroySslContext();
1911 else {
1912 // Move all bytes into the plain buffer
1913 qint64 tmpReadBufferMaxSize = readBufferMaxSize;
1914 readBufferMaxSize = 0; // reset temporarily so the plain socket buffer is completely drained
1915 transmit();
1916 readBufferMaxSize = tmpReadBufferMaxSize;
1917 }
1918 //if there is still buffered data in the plain socket, don't destroy the ssl context yet.
1919 //it will be destroyed when the socket is deleted.
1920}
1921
1922QSslCipher QSslSocketBackendPrivate::sessionCipher() const
1923{
1924 if (!ssl)
1925 return QSslCipher();
1926
1927 const SSL_CIPHER *sessionCipher = q_SSL_get_current_cipher(a: ssl);
1928 return sessionCipher ? QSslCipher_from_SSL_CIPHER(cipher: sessionCipher) : QSslCipher();
1929}
1930
1931QSsl::SslProtocol QSslSocketBackendPrivate::sessionProtocol() const
1932{
1933 if (!ssl)
1934 return QSsl::UnknownProtocol;
1935 int ver = q_SSL_version(a: ssl);
1936
1937 switch (ver) {
1938 case 0x2:
1939 return QSsl::SslV2;
1940 case 0x300:
1941 return QSsl::SslV3;
1942 case 0x301:
1943 return QSsl::TlsV1_0;
1944 case 0x302:
1945 return QSsl::TlsV1_1;
1946 case 0x303:
1947 return QSsl::TlsV1_2;
1948 case 0x304:
1949 return QSsl::TlsV1_3;
1950 }
1951
1952 return QSsl::UnknownProtocol;
1953}
1954
1955
1956void QSslSocketBackendPrivate::continueHandshake()
1957{
1958 Q_Q(QSslSocket);
1959 // if we have a max read buffer size, reset the plain socket's to match
1960 if (readBufferMaxSize)
1961 plainSocket->setReadBufferSize(readBufferMaxSize);
1962
1963 if (q_SSL_session_reused(a: ssl))
1964 configuration.peerSessionShared = true;
1965
1966#ifdef QT_DECRYPT_SSL_TRAFFIC
1967 if (q_SSL_get_session(ssl)) {
1968 size_t master_key_len = q_SSL_SESSION_get_master_key(q_SSL_get_session(ssl), 0, 0);
1969 size_t client_random_len = q_SSL_get_client_random(ssl, 0, 0);
1970 QByteArray masterKey(int(master_key_len), 0); // Will not overflow
1971 QByteArray clientRandom(int(client_random_len), 0); // Will not overflow
1972
1973 q_SSL_SESSION_get_master_key(q_SSL_get_session(ssl),
1974 reinterpret_cast<unsigned char*>(masterKey.data()),
1975 masterKey.size());
1976 q_SSL_get_client_random(ssl, reinterpret_cast<unsigned char *>(clientRandom.data()),
1977 clientRandom.size());
1978
1979 QByteArray debugLineClientRandom("CLIENT_RANDOM ");
1980 debugLineClientRandom.append(clientRandom.toHex().toUpper());
1981 debugLineClientRandom.append(" ");
1982 debugLineClientRandom.append(masterKey.toHex().toUpper());
1983 debugLineClientRandom.append("\n");
1984
1985 QString sslKeyFile = QDir::tempPath() + QLatin1String("/qt-ssl-keys");
1986 QFile file(sslKeyFile);
1987 if (!file.open(QIODevice::Append))
1988 qCWarning(lcSsl) << "could not open file" << sslKeyFile << "for appending";
1989 if (!file.write(debugLineClientRandom))
1990 qCWarning(lcSsl) << "could not write to file" << sslKeyFile;
1991 file.close();
1992 } else {
1993 qCWarning(lcSsl, "could not decrypt SSL traffic");
1994 }
1995#endif
1996
1997 // Cache this SSL session inside the QSslContext
1998 if (!(configuration.sslOptions & QSsl::SslOptionDisableSessionSharing)) {
1999 if (!sslContextPointer->cacheSession(ssl)) {
2000 sslContextPointer.clear(); // we could not cache the session
2001 } else {
2002 // Cache the session for permanent usage as well
2003 if (!(configuration.sslOptions & QSsl::SslOptionDisableSessionPersistence)) {
2004 if (!sslContextPointer->sessionASN1().isEmpty())
2005 configuration.sslSession = sslContextPointer->sessionASN1();
2006 configuration.sslSessionTicketLifeTimeHint = sslContextPointer->sessionTicketLifeTimeHint();
2007 }
2008 }
2009 }
2010
2011#if !defined(OPENSSL_NO_NEXTPROTONEG)
2012
2013 configuration.nextProtocolNegotiationStatus = sslContextPointer->npnContext().status;
2014 if (sslContextPointer->npnContext().status == QSslConfiguration::NextProtocolNegotiationUnsupported) {
2015 // we could not agree -> be conservative and use HTTP/1.1
2016 configuration.nextNegotiatedProtocol = QByteArrayLiteral("http/1.1");
2017 } else {
2018 const unsigned char *proto = nullptr;
2019 unsigned int proto_len = 0;
2020
2021 q_SSL_get0_alpn_selected(ssl, data: &proto, len: &proto_len);
2022 if (proto_len && mode == QSslSocket::SslClientMode) {
2023 // Client does not have a callback that sets it ...
2024 configuration.nextProtocolNegotiationStatus = QSslConfiguration::NextProtocolNegotiationNegotiated;
2025 }
2026
2027 if (!proto_len) { // Test if NPN was more lucky ...
2028 q_SSL_get0_next_proto_negotiated(s: ssl, data: &proto, len: &proto_len);
2029 }
2030
2031 if (proto_len)
2032 configuration.nextNegotiatedProtocol = QByteArray(reinterpret_cast<const char *>(proto), proto_len);
2033 else
2034 configuration.nextNegotiatedProtocol.clear();
2035 }
2036#endif // !defined(OPENSSL_NO_NEXTPROTONEG)
2037
2038 if (mode == QSslSocket::SslClientMode) {
2039 EVP_PKEY *key;
2040 if (q_SSL_get_server_tmp_key(ssl, &key))
2041 configuration.ephemeralServerKey = QSslKey(key, QSsl::PublicKey);
2042 }
2043
2044 connectionEncrypted = true;
2045 emit q->encrypted();
2046 if (autoStartHandshake && pendingClose) {
2047 pendingClose = false;
2048 q->disconnectFromHost();
2049 }
2050}
2051
2052bool QSslSocketPrivate::ensureLibraryLoaded()
2053{
2054 if (!q_resolveOpenSslSymbols())
2055 return false;
2056
2057 const QMutexLocker locker(qt_opensslInitMutex);
2058
2059 if (!s_libraryLoaded) {
2060 // Initialize OpenSSL.
2061 if (q_OPENSSL_init_ssl(opts: 0, settings: nullptr) != 1)
2062 return false;
2063
2064 if (q_OpenSSL_version_num() < 0x10101000L) {
2065 qCWarning(lcSsl, "QSslSocket: OpenSSL >= 1.1.1 is required; %s was found instead", q_OpenSSL_version(OPENSSL_VERSION));
2066 return false;
2067 }
2068
2069 q_SSL_load_error_strings();
2070 q_OpenSSL_add_all_algorithms();
2071
2072 QSslSocketBackendPrivate::s_indexForSSLExtraData
2073 = q_CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, argl: 0L, argp: nullptr, new_func: nullptr,
2074 dup_func: nullptr, free_func: nullptr);
2075
2076 // Initialize OpenSSL's random seed.
2077 if (!q_RAND_status()) {
2078 qWarning(msg: "Random number generator not seeded, disabling SSL support");
2079 return false;
2080 }
2081
2082 s_libraryLoaded = true;
2083 }
2084 return true;
2085}
2086
2087void QSslSocketPrivate::ensureCiphersAndCertsLoaded()
2088{
2089 const QMutexLocker locker(qt_opensslInitMutex);
2090
2091 if (s_loadedCiphersAndCerts)
2092 return;
2093 s_loadedCiphersAndCerts = true;
2094
2095 resetDefaultCiphers();
2096 resetDefaultEllipticCurves();
2097
2098#if QT_CONFIG(library)
2099 //load symbols needed to receive certificates from system store
2100#if defined(Q_OS_QNX)
2101 s_loadRootCertsOnDemand = true;
2102#elif defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN)
2103 // check whether we can enable on-demand root-cert loading (i.e. check whether the sym links are there)
2104 QList<QByteArray> dirs = unixRootCertDirectories();
2105 QStringList symLinkFilter;
2106 symLinkFilter << QLatin1String("[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f].[0-9]");
2107 for (int a = 0; a < dirs.count(); ++a) {
2108 QDirIterator iterator(QLatin1String(dirs.at(i: a)), symLinkFilter, QDir::Files);
2109 if (iterator.hasNext()) {
2110 s_loadRootCertsOnDemand = true;
2111 break;
2112 }
2113 }
2114#endif
2115#endif // QT_CONFIG(library)
2116 // if on-demand loading was not enabled, load the certs now
2117 if (!s_loadRootCertsOnDemand)
2118 setDefaultCaCertificates(systemCaCertificates());
2119#ifdef Q_OS_WIN
2120 //Enabled for fetching additional root certs from windows update on windows.
2121 //This flag is set false by setDefaultCaCertificates() indicating the app uses
2122 //its own cert bundle rather than the system one.
2123 //Same logic that disables the unix on demand cert loading.
2124 //Unlike unix, we do preload the certificates from the cert store.
2125 s_loadRootCertsOnDemand = true;
2126#endif
2127}
2128
2129QList<QSslCertificate> QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates(STACK_OF(X509) *x509)
2130{
2131 ensureInitialized();
2132 QList<QSslCertificate> certificates;
2133 for (int i = 0; i < q_sk_X509_num(x509); ++i) {
2134 if (X509 *entry = q_sk_X509_value(x509, i))
2135 certificates << QSslCertificatePrivate::QSslCertificate_from_X509(x509: entry);
2136 }
2137 return certificates;
2138}
2139
2140QList<QSslError> QSslSocketBackendPrivate::verify(const QList<QSslCertificate> &certificateChain,
2141 const QString &hostName)
2142{
2143 auto roots = QSslConfiguration::defaultConfiguration().caCertificates();
2144#ifndef Q_OS_WIN
2145 // On Windows, system CA certificates are already set as default ones.
2146 // No need to add them again (and again) and also, if the default configuration
2147 // has its own set of CAs, this probably should not be amended by the ones
2148 // from the 'ROOT' store, since it's not what an application chose to trust.
2149 if (s_loadRootCertsOnDemand)
2150 roots.append(t: systemCaCertificates());
2151#endif // Q_OS_WIN
2152 return verify(cas: roots, certificateChain, hostName);
2153}
2154
2155QList<QSslError> QSslSocketBackendPrivate::verify(const QList<QSslCertificate> &caCertificates,
2156 const QList<QSslCertificate> &certificateChain,
2157 const QString &hostName)
2158{
2159 if (certificateChain.count() <= 0)
2160 return {QSslError(QSslError::UnspecifiedError)};
2161
2162 QList<QSslError> errors;
2163 // Setup the store with the default CA certificates
2164 X509_STORE *certStore = q_X509_STORE_new();
2165 if (!certStore) {
2166 qCWarning(lcSsl) << "Unable to create certificate store";
2167 errors << QSslError(QSslError::UnspecifiedError);
2168 return errors;
2169 }
2170 const std::unique_ptr<X509_STORE, decltype(&q_X509_STORE_free)> storeGuard(certStore, q_X509_STORE_free);
2171
2172 const QDateTime now = QDateTime::currentDateTimeUtc();
2173 for (const QSslCertificate &caCertificate : caCertificates) {
2174 // From https://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html:
2175 //
2176 // If several CA certificates matching the name, key identifier, and
2177 // serial number condition are available, only the first one will be
2178 // examined. This may lead to unexpected results if the same CA
2179 // certificate is available with different expiration dates. If a
2180 // ``certificate expired'' verification error occurs, no other
2181 // certificate will be searched. Make sure to not have expired
2182 // certificates mixed with valid ones.
2183 //
2184 // See also: QSslContext::fromConfiguration()
2185 if (caCertificate.expiryDate() >= now) {
2186 q_X509_STORE_add_cert(ctx: certStore, x: reinterpret_cast<X509 *>(caCertificate.handle()));
2187 }
2188 }
2189
2190 QVector<QSslErrorEntry> lastErrors;
2191 if (!q_X509_STORE_set_ex_data(ctx: certStore, idx: 0, data: &lastErrors)) {
2192 qCWarning(lcSsl) << "Unable to attach external data (error list) to a store";
2193 errors << QSslError(QSslError::UnspecifiedError);
2194 return errors;
2195 }
2196
2197 // Register a custom callback to get all verification errors.
2198 q_X509_STORE_set_verify_cb(ctx: certStore, verify_cb: q_X509Callback);
2199
2200 // Build the chain of intermediate certificates
2201 STACK_OF(X509) *intermediates = nullptr;
2202 if (certificateChain.length() > 1) {
2203 intermediates = (STACK_OF(X509) *) q_OPENSSL_sk_new_null();
2204
2205 if (!intermediates) {
2206 errors << QSslError(QSslError::UnspecifiedError);
2207 return errors;
2208 }
2209
2210 bool first = true;
2211 for (const QSslCertificate &cert : certificateChain) {
2212 if (first) {
2213 first = false;
2214 continue;
2215 }
2216
2217 q_OPENSSL_sk_push(st: (OPENSSL_STACK *)intermediates, data: reinterpret_cast<X509 *>(cert.handle()));
2218 }
2219 }
2220
2221 X509_STORE_CTX *storeContext = q_X509_STORE_CTX_new();
2222 if (!storeContext) {
2223 errors << QSslError(QSslError::UnspecifiedError);
2224 return errors;
2225 }
2226 std::unique_ptr<X509_STORE_CTX, decltype(&q_X509_STORE_CTX_free)> ctxGuard(storeContext, q_X509_STORE_CTX_free);
2227
2228 if (!q_X509_STORE_CTX_init(ctx: storeContext, store: certStore, x509: reinterpret_cast<X509 *>(certificateChain[0].handle()), chain: intermediates)) {
2229 errors << QSslError(QSslError::UnspecifiedError);
2230 return errors;
2231 }
2232
2233 // Now we can actually perform the verification of the chain we have built.
2234 // We ignore the result of this function since we process errors via the
2235 // callback.
2236 (void) q_X509_verify_cert(ctx: storeContext);
2237 ctxGuard.reset();
2238 q_OPENSSL_sk_free(a: (OPENSSL_STACK *)intermediates);
2239
2240 // Now process the errors
2241
2242 if (QSslCertificatePrivate::isBlacklisted(certificate: certificateChain[0])) {
2243 QSslError error(QSslError::CertificateBlacklisted, certificateChain[0]);
2244 errors << error;
2245 }
2246
2247 // Check the certificate name against the hostname if one was specified
2248 if ((!hostName.isEmpty()) && (!isMatchingHostname(cert: certificateChain[0], peerName: hostName))) {
2249 // No matches in common names or alternate names.
2250 QSslError error(QSslError::HostNameMismatch, certificateChain[0]);
2251 errors << error;
2252 }
2253
2254 // Translate errors from the error list into QSslErrors.
2255 errors.reserve(alloc: errors.size() + lastErrors.size());
2256 for (const auto &error : qAsConst(t&: lastErrors))
2257 errors << _q_OpenSSL_to_QSslError(errorCode: error.code, cert: certificateChain.value(i: error.depth));
2258
2259 return errors;
2260}
2261
2262bool QSslSocketBackendPrivate::importPkcs12(QIODevice *device,
2263 QSslKey *key, QSslCertificate *cert,
2264 QList<QSslCertificate> *caCertificates,
2265 const QByteArray &passPhrase)
2266{
2267 if (!supportsSsl())
2268 return false;
2269
2270 // These are required
2271 Q_ASSERT(device);
2272 Q_ASSERT(key);
2273 Q_ASSERT(cert);
2274
2275 // Read the file into a BIO
2276 QByteArray pkcs12data = device->readAll();
2277 if (pkcs12data.size() == 0)
2278 return false;
2279
2280 BIO *bio = q_BIO_new_mem_buf(a: const_cast<char *>(pkcs12data.constData()), b: pkcs12data.size());
2281
2282 // Create the PKCS#12 object
2283 PKCS12 *p12 = q_d2i_PKCS12_bio(bio, pkcs12: nullptr);
2284 if (!p12) {
2285 qCWarning(lcSsl, "Unable to read PKCS#12 structure, %s",
2286 q_ERR_error_string(q_ERR_get_error(), nullptr));
2287 q_BIO_free(a: bio);
2288 return false;
2289 }
2290
2291 // Extract the data
2292 EVP_PKEY *pkey = nullptr;
2293 X509 *x509;
2294 STACK_OF(X509) *ca = nullptr;
2295
2296 if (!q_PKCS12_parse(p12, pass: passPhrase.constData(), pkey: &pkey, cert: &x509, ca: &ca)) {
2297 qCWarning(lcSsl, "Unable to parse PKCS#12 structure, %s",
2298 q_ERR_error_string(q_ERR_get_error(), nullptr));
2299 q_PKCS12_free(pkcs12: p12);
2300 q_BIO_free(a: bio);
2301 return false;
2302 }
2303
2304 // Convert to Qt types
2305 if (!key->d->fromEVP_PKEY(pkey)) {
2306 qCWarning(lcSsl, "Unable to convert private key");
2307 q_OPENSSL_sk_pop_free(a: reinterpret_cast<OPENSSL_STACK *>(ca),
2308 b: reinterpret_cast<void (*)(void *)>(q_X509_free));
2309 q_X509_free(a: x509);
2310 q_EVP_PKEY_free(a: pkey);
2311 q_PKCS12_free(pkcs12: p12);
2312 q_BIO_free(a: bio);
2313
2314 return false;
2315 }
2316
2317 *cert = QSslCertificatePrivate::QSslCertificate_from_X509(x509);
2318
2319 if (caCertificates)
2320 *caCertificates = QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates(x509: ca);
2321
2322 // Clean up
2323 q_OPENSSL_sk_pop_free(a: reinterpret_cast<OPENSSL_STACK *>(ca),
2324 b: reinterpret_cast<void (*)(void *)>(q_X509_free));
2325
2326 q_X509_free(a: x509);
2327 q_EVP_PKEY_free(a: pkey);
2328 q_PKCS12_free(pkcs12: p12);
2329 q_BIO_free(a: bio);
2330
2331 return true;
2332}
2333
2334
2335QT_END_NAMESPACE
2336

source code of qtbase/src/network/ssl/qsslsocket_openssl.cpp