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
70#ifdef Q_OS_WIN
71#include "qwindowscarootfetcher_p.h"
72#endif
73
74#if !QT_CONFIG(opensslv11)
75#include <openssl/x509_vfy.h>
76#endif
77
78#include <QtCore/qdatetime.h>
79#include <QtCore/qdebug.h>
80#include <QtCore/qdir.h>
81#include <QtCore/qdiriterator.h>
82#include <QtCore/qelapsedtimer.h>
83#include <QtCore/qfile.h>
84#include <QtCore/qfileinfo.h>
85#include <QtCore/qmutex.h>
86#include <QtCore/qthread.h>
87#include <QtCore/qurl.h>
88#include <QtCore/qvarlengtharray.h>
89#include <QtCore/qscopedvaluerollback.h>
90
91#if QT_CONFIG(ocsp)
92#include "qocsp_p.h"
93#endif
94
95#include <algorithm>
96
97#include <string.h>
98
99QT_BEGIN_NAMESPACE
100
101bool QSslSocketPrivate::s_libraryLoaded = false;
102bool QSslSocketPrivate::s_loadedCiphersAndCerts = false;
103bool QSslSocketPrivate::s_loadRootCertsOnDemand = false;
104
105#if OPENSSL_VERSION_NUMBER >= 0x10001000L
106int QSslSocketBackendPrivate::s_indexForSSLExtraData = -1;
107#endif
108
109QString QSslSocketBackendPrivate::getErrorsFromOpenSsl()
110{
111 QString errorString;
112 char buf[256] = {}; // OpenSSL docs claim both 120 and 256; use the larger.
113 unsigned long errNum;
114 while ((errNum = q_ERR_get_error())) {
115 if (!errorString.isEmpty())
116 errorString.append(QLatin1String(", "));
117 q_ERR_error_string_n(errNum, buf, sizeof buf);
118 errorString.append(QString::fromLatin1(buf)); // error is ascii according to man ERR_error_string
119 }
120 return errorString;
121}
122
123extern "C" {
124
125#if OPENSSL_VERSION_NUMBER >= 0x10001000L && !defined(OPENSSL_NO_PSK)
126static unsigned int q_ssl_psk_client_callback(SSL *ssl,
127 const char *hint,
128 char *identity, unsigned int max_identity_len,
129 unsigned char *psk, unsigned int max_psk_len)
130{
131 QSslSocketBackendPrivate *d = reinterpret_cast<QSslSocketBackendPrivate *>(q_SSL_get_ex_data(ssl, QSslSocketBackendPrivate::s_indexForSSLExtraData));
132 Q_ASSERT(d);
133 return d->tlsPskClientCallback(hint, identity, max_identity_len, psk, max_psk_len);
134}
135
136static unsigned int q_ssl_psk_server_callback(SSL *ssl,
137 const char *identity,
138 unsigned char *psk, unsigned int max_psk_len)
139{
140 QSslSocketBackendPrivate *d = reinterpret_cast<QSslSocketBackendPrivate *>(q_SSL_get_ex_data(ssl, QSslSocketBackendPrivate::s_indexForSSLExtraData));
141 Q_ASSERT(d);
142 return d->tlsPskServerCallback(identity, psk, max_psk_len);
143}
144
145#ifdef TLS1_3_VERSION
146#ifndef OPENSSL_NO_PSK
147static unsigned int q_ssl_psk_restore_client(SSL *ssl,
148 const char *hint,
149 char *identity, unsigned int max_identity_len,
150 unsigned char *psk, unsigned int max_psk_len)
151{
152 Q_UNUSED(hint);
153 Q_UNUSED(identity);
154 Q_UNUSED(max_identity_len);
155 Q_UNUSED(psk);
156 Q_UNUSED(max_psk_len);
157
158#ifdef QT_DEBUG
159 QSslSocketBackendPrivate *d = reinterpret_cast<QSslSocketBackendPrivate *>(q_SSL_get_ex_data(ssl, QSslSocketBackendPrivate::s_indexForSSLExtraData));
160 Q_ASSERT(d);
161 Q_ASSERT(d->mode == QSslSocket::SslClientMode);
162#endif
163 q_SSL_set_psk_client_callback(ssl, &q_ssl_psk_client_callback);
164
165 return 0;
166}
167#endif // !OPENSSL_NO_PSK
168
169static int q_ssl_psk_use_session_callback(SSL *ssl, const EVP_MD *md, const unsigned char **id,
170 size_t *idlen, SSL_SESSION **sess)
171{
172 Q_UNUSED(ssl);
173 Q_UNUSED(md);
174 Q_UNUSED(id);
175 Q_UNUSED(idlen);
176 Q_UNUSED(sess);
177
178#ifndef OPENSSL_NO_PSK
179#ifdef QT_DEBUG
180 QSslSocketBackendPrivate *d = reinterpret_cast<QSslSocketBackendPrivate *>(q_SSL_get_ex_data(ssl, QSslSocketBackendPrivate::s_indexForSSLExtraData));
181 Q_ASSERT(d);
182 Q_ASSERT(d->mode == QSslSocket::SslClientMode);
183#endif
184
185 // Temporarily rebind the psk because it will be called next. The function will restore it.
186 q_SSL_set_psk_client_callback(ssl, &q_ssl_psk_restore_client);
187#endif
188
189 return 1; // need to return 1 or else "the connection setup fails."
190}
191#endif // TLS1_3_VERSION
192
193#endif
194
195#if QT_CONFIG(ocsp)
196
197int qt_OCSP_status_server_callback(SSL *ssl, void *ocspRequest)
198{
199 Q_UNUSED(ocspRequest)
200 if (!ssl)
201 return SSL_TLSEXT_ERR_ALERT_FATAL;
202
203 auto d = static_cast<QSslSocketBackendPrivate *>(q_SSL_get_ex_data(ssl, QSslSocketBackendPrivate::s_indexForSSLExtraData));
204 if (!d)
205 return SSL_TLSEXT_ERR_ALERT_FATAL;
206
207 Q_ASSERT(d->mode == QSslSocket::SslServerMode);
208 const QByteArray &response = d->ocspResponseDer;
209 Q_ASSERT(response.size());
210
211 unsigned char *derCopy = static_cast<unsigned char *>(q_OPENSSL_malloc(size_t(response.size())));
212 if (!derCopy)
213 return SSL_TLSEXT_ERR_ALERT_FATAL;
214
215 std::copy(response.data(), response.data() + response.size(), derCopy);
216 // We don't check the return value: internally OpenSSL simply assignes the
217 // pointer (it assumes it now owns this memory btw!) and the length.
218 q_SSL_set_tlsext_status_ocsp_resp(ssl, derCopy, response.size());
219
220 return SSL_TLSEXT_ERR_OK;
221}
222
223#endif // ocsp
224
225} // extern "C"
226
227QSslSocketBackendPrivate::QSslSocketBackendPrivate()
228 : ssl(nullptr),
229 readBio(nullptr),
230 writeBio(nullptr),
231 session(nullptr)
232{
233 // Calls SSL_library_init().
234 ensureInitialized();
235}
236
237QSslSocketBackendPrivate::~QSslSocketBackendPrivate()
238{
239 destroySslContext();
240}
241
242QSslCipher QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(const SSL_CIPHER *cipher)
243{
244 QSslCipher ciph;
245
246 char buf [256];
247 QString descriptionOneLine = QString::fromLatin1(q_SSL_CIPHER_description(cipher, buf, sizeof(buf)));
248
249 const auto descriptionList = descriptionOneLine.splitRef(QLatin1Char(' '), QString::SkipEmptyParts);
250 if (descriptionList.size() > 5) {
251 // ### crude code.
252 ciph.d->isNull = false;
253 ciph.d->name = descriptionList.at(0).toString();
254
255 QString protoString = descriptionList.at(1).toString();
256 ciph.d->protocolString = protoString;
257 ciph.d->protocol = QSsl::UnknownProtocol;
258 if (protoString == QLatin1String("SSLv3"))
259 ciph.d->protocol = QSsl::SslV3;
260 else if (protoString == QLatin1String("SSLv2"))
261 ciph.d->protocol = QSsl::SslV2;
262 else if (protoString == QLatin1String("TLSv1"))
263 ciph.d->protocol = QSsl::TlsV1_0;
264 else if (protoString == QLatin1String("TLSv1.1"))
265 ciph.d->protocol = QSsl::TlsV1_1;
266 else if (protoString == QLatin1String("TLSv1.2"))
267 ciph.d->protocol = QSsl::TlsV1_2;
268 else if (protoString == QLatin1String("TLSv1.3"))
269 ciph.d->protocol = QSsl::TlsV1_3;
270
271 if (descriptionList.at(2).startsWith(QLatin1String("Kx=")))
272 ciph.d->keyExchangeMethod = descriptionList.at(2).mid(3).toString();
273 if (descriptionList.at(3).startsWith(QLatin1String("Au=")))
274 ciph.d->authenticationMethod = descriptionList.at(3).mid(3).toString();
275 if (descriptionList.at(4).startsWith(QLatin1String("Enc=")))
276 ciph.d->encryptionMethod = descriptionList.at(4).mid(4).toString();
277 ciph.d->exportable = (descriptionList.size() > 6 && descriptionList.at(6) == QLatin1String("export"));
278
279 ciph.d->bits = q_SSL_CIPHER_get_bits(cipher, &ciph.d->supportedBits);
280 }
281 return ciph;
282}
283
284QSslErrorEntry QSslErrorEntry::fromStoreContext(X509_STORE_CTX *ctx)
285{
286 return {
287 q_X509_STORE_CTX_get_error(ctx),
288 q_X509_STORE_CTX_get_error_depth(ctx)
289 };
290}
291
292#if QT_CONFIG(ocsp)
293
294QSslError qt_OCSP_response_status_to_QSslError(long code)
295{
296 switch (code) {
297 case OCSP_RESPONSE_STATUS_MALFORMEDREQUEST:
298 return QSslError::OcspMalformedRequest;
299 case OCSP_RESPONSE_STATUS_INTERNALERROR:
300 return QSslError::OcspInternalError;
301 case OCSP_RESPONSE_STATUS_TRYLATER:
302 return QSslError::OcspTryLater;
303 case OCSP_RESPONSE_STATUS_SIGREQUIRED:
304 return QSslError::OcspSigRequred;
305 case OCSP_RESPONSE_STATUS_UNAUTHORIZED:
306 return QSslError::OcspUnauthorized;
307 case OCSP_RESPONSE_STATUS_SUCCESSFUL:
308 default:
309 return {};
310 }
311 Q_UNREACHABLE();
312}
313
314QOcspRevocationReason qt_OCSP_revocation_reason(int reason)
315{
316 switch (reason) {
317 case OCSP_REVOKED_STATUS_NOSTATUS:
318 return QOcspRevocationReason::None;
319 case OCSP_REVOKED_STATUS_UNSPECIFIED:
320 return QOcspRevocationReason::Unspecified;
321 case OCSP_REVOKED_STATUS_KEYCOMPROMISE:
322 return QOcspRevocationReason::KeyCompromise;
323 case OCSP_REVOKED_STATUS_CACOMPROMISE:
324 return QOcspRevocationReason::CACompromise;
325 case OCSP_REVOKED_STATUS_AFFILIATIONCHANGED:
326 return QOcspRevocationReason::AffiliationChanged;
327 case OCSP_REVOKED_STATUS_SUPERSEDED:
328 return QOcspRevocationReason::Superseded;
329 case OCSP_REVOKED_STATUS_CESSATIONOFOPERATION:
330 return QOcspRevocationReason::CessationOfOperation;
331 case OCSP_REVOKED_STATUS_CERTIFICATEHOLD:
332 return QOcspRevocationReason::CertificateHold;
333 case OCSP_REVOKED_STATUS_REMOVEFROMCRL:
334 return QOcspRevocationReason::RemoveFromCRL;
335 default:
336 return QOcspRevocationReason::None;
337 }
338
339 Q_UNREACHABLE();
340}
341
342bool qt_OCSP_certificate_match(OCSP_SINGLERESP *singleResponse, X509 *peerCert, X509 *issuer)
343{
344 // OCSP_basic_verify does verify that the responder is legit, the response is
345 // correctly signed, CertID is correct. But it does not know which certificate
346 // we were presented with by our peer, so it does not check if it's a response
347 // for our peer's certificate.
348 Q_ASSERT(singleResponse && peerCert && issuer);
349
350 const OCSP_CERTID *certId = q_OCSP_SINGLERESP_get0_id(singleResponse); // Does not increment refcount.
351 if (!certId) {
352 qCWarning(lcSsl, "A SingleResponse without CertID");
353 return false;
354 }
355
356 ASN1_OBJECT *md = nullptr;
357 ASN1_INTEGER *reportedSerialNumber = nullptr;
358 const int result = q_OCSP_id_get0_info(nullptr, &md, nullptr, &reportedSerialNumber, const_cast<OCSP_CERTID *>(certId));
359 if (result != 1 || !md || !reportedSerialNumber) {
360 qCWarning(lcSsl, "Failed to extract a hash and serial number from CertID structure");
361 return false;
362 }
363
364 if (!q_X509_get_serialNumber(peerCert)) {
365 // Is this possible at all? But we have to check this,
366 // ASN1_INTEGER_cmp (called from OCSP_id_cmp) dereferences
367 // without any checks at all.
368 qCWarning(lcSsl, "No serial number in peer's ceritificate");
369 return false;
370 }
371
372 const int nid = q_OBJ_obj2nid(md);
373 if (nid == NID_undef) {
374 qCWarning(lcSsl, "Unknown hash algorithm in CertID");
375 return false;
376 }
377
378 const EVP_MD *digest = q_EVP_get_digestbynid(nid); // Does not increment refcount.
379 if (!digest) {
380 qCWarning(lcSsl) << "No digest for nid" << nid;
381 return false;
382 }
383
384 OCSP_CERTID *recreatedId = q_OCSP_cert_to_id(digest, peerCert, issuer);
385 if (!recreatedId) {
386 qCWarning(lcSsl, "Failed to re-create CertID");
387 return false;
388 }
389 const QSharedPointer<OCSP_CERTID> guard(recreatedId, q_OCSP_CERTID_free);
390
391 if (q_OCSP_id_cmp(const_cast<OCSP_CERTID *>(certId), recreatedId)) {
392 qDebug(lcSsl, "Certificate ID mismatch");
393 return false;
394 }
395 // Bingo!
396 return true;
397}
398
399#endif // ocsp
400
401int q_X509Callback(int ok, X509_STORE_CTX *ctx)
402{
403 if (!ok) {
404 // Store the error and at which depth the error was detected.
405
406 using ErrorListPtr = QVector<QSslErrorEntry>*;
407 ErrorListPtr errors = nullptr;
408
409 // Error list is attached to either 'SSL' or 'X509_STORE'.
410 if (X509_STORE *store = q_X509_STORE_CTX_get0_store(ctx)) { // We try store first:
411#if QT_CONFIG(opensslv11)
412 errors = ErrorListPtr(q_X509_STORE_get_ex_data(store, 0));
413#else
414 errors = ErrorListPtr(q_CRYPTO_get_ex_data(&store->ex_data, 0));
415#endif // opensslv11
416 }
417
418 if (!errors) {
419 // Not found on store? Try SSL and its external data then. According to the OpenSSL's
420 // documentation:
421 //
422 // "Whenever a X509_STORE_CTX object is created for the verification of the peers certificate
423 // during a handshake, a pointer to the SSL object is stored into the X509_STORE_CTX object
424 // to identify the connection affected. To retrieve this pointer the X509_STORE_CTX_get_ex_data()
425 // function can be used with the correct index."
426 if (SSL *ssl = static_cast<SSL *>(q_X509_STORE_CTX_get_ex_data(ctx, q_SSL_get_ex_data_X509_STORE_CTX_idx())))
427 errors = ErrorListPtr(q_SSL_get_ex_data(ssl, QSslSocketBackendPrivate::s_indexForSSLExtraData + 1));
428 }
429
430 if (!errors) {
431 qCWarning(lcSsl, "Neither X509_STORE, nor SSL contains error list, handshake failure");
432 return 0;
433 }
434
435 errors->append(QSslErrorEntry::fromStoreContext(ctx));
436 }
437 // Always return OK to allow verification to continue. We handle the
438 // errors gracefully after collecting all errors, after verification has
439 // completed.
440 return 1;
441}
442
443static void q_loadCiphersForConnection(SSL *connection, QList<QSslCipher> &ciphers,
444 QList<QSslCipher> &defaultCiphers)
445{
446 Q_ASSERT(connection);
447
448 STACK_OF(SSL_CIPHER) *supportedCiphers = q_SSL_get_ciphers(connection);
449 for (int i = 0; i < q_sk_SSL_CIPHER_num(supportedCiphers); ++i) {
450 if (SSL_CIPHER *cipher = q_sk_SSL_CIPHER_value(supportedCiphers, i)) {
451 QSslCipher ciph = QSslSocketBackendPrivate::QSslCipher_from_SSL_CIPHER(cipher);
452 if (!ciph.isNull()) {
453 // Unconditionally exclude ADH and AECDH ciphers since they offer no MITM protection
454 if (!ciph.name().toLower().startsWith(QLatin1String("adh")) &&
455 !ciph.name().toLower().startsWith(QLatin1String("exp-adh")) &&
456 !ciph.name().toLower().startsWith(QLatin1String("aecdh"))) {
457 ciphers << ciph;
458
459 if (ciph.usedBits() >= 128)
460 defaultCiphers << ciph;
461 }
462 }
463 }
464 }
465}
466
467// Defined in qsslsocket.cpp
468void q_setDefaultDtlsCiphers(const QList<QSslCipher> &ciphers);
469
470long QSslSocketBackendPrivate::setupOpenSslOptions(QSsl::SslProtocol protocol, QSsl::SslOptions sslOptions)
471{
472 long options;
473 if (protocol == QSsl::TlsV1SslV3)
474 options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3;
475 else if (protocol == QSsl::SecureProtocols)
476 options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3;
477 else if (protocol == QSsl::TlsV1_0OrLater)
478 options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3;
479#if OPENSSL_VERSION_NUMBER >= 0x10001000L
480 // Choosing Tlsv1_1OrLater or TlsV1_2OrLater on OpenSSL < 1.0.1
481 // will cause an error in QSslContext::fromConfiguration, meaning
482 // we will never get here.
483 else if (protocol == QSsl::TlsV1_1OrLater)
484 options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1;
485 else if (protocol == QSsl::TlsV1_2OrLater)
486 options = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1|SSL_OP_NO_TLSv1_1;
487 else if (protocol == QSsl::TlsV1_3OrLater)
488 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;
489#endif
490 else
491 options = SSL_OP_ALL;
492
493 // This option is disabled by default, so we need to be able to clear it
494 if (sslOptions & QSsl::SslOptionDisableEmptyFragments)
495 options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
496 else
497 options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
498
499#ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
500 // This option is disabled by default, so we need to be able to clear it
501 if (sslOptions & QSsl::SslOptionDisableLegacyRenegotiation)
502 options &= ~SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
503 else
504 options |= SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
505#endif
506
507#ifdef SSL_OP_NO_TICKET
508 if (sslOptions & QSsl::SslOptionDisableSessionTickets)
509 options |= SSL_OP_NO_TICKET;
510#endif
511#ifdef SSL_OP_NO_COMPRESSION
512 if (sslOptions & QSsl::SslOptionDisableCompression)
513 options |= SSL_OP_NO_COMPRESSION;
514#endif
515
516 if (!(sslOptions & QSsl::SslOptionDisableServerCipherPreference))
517 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
518
519 return options;
520}
521
522bool QSslSocketBackendPrivate::initSslContext()
523{
524 Q_Q(QSslSocket);
525
526 // If no external context was set (e.g. by QHttpNetworkConnection) we will
527 // create a default context
528 if (!sslContextPointer) {
529 // create a deep copy of our configuration
530 QSslConfigurationPrivate *configurationCopy = new QSslConfigurationPrivate(configuration);
531 configurationCopy->ref.storeRelaxed(0); // the QSslConfiguration constructor refs up
532 sslContextPointer = QSslContext::sharedFromConfiguration(mode, configurationCopy, allowRootCertOnDemandLoading);
533 }
534
535 if (sslContextPointer->error() != QSslError::NoError) {
536 setErrorAndEmit(QAbstractSocket::SslInvalidUserDataError, sslContextPointer->errorString());
537 sslContextPointer.clear(); // deletes the QSslContext
538 return false;
539 }
540
541 // Create and initialize SSL session
542 if (!(ssl = sslContextPointer->createSsl())) {
543 // ### Bad error code
544 setErrorAndEmit(QAbstractSocket::SslInternalError,
545 QSslSocket::tr("Error creating SSL session, %1").arg(getErrorsFromOpenSsl()));
546 return false;
547 }
548
549 if (configuration.protocol != QSsl::SslV2 &&
550 configuration.protocol != QSsl::SslV3 &&
551 configuration.protocol != QSsl::UnknownProtocol &&
552 mode == QSslSocket::SslClientMode) {
553 // Set server hostname on TLS extension. RFC4366 section 3.1 requires it in ACE format.
554 QString tlsHostName = verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName;
555 if (tlsHostName.isEmpty())
556 tlsHostName = hostName;
557 QByteArray ace = QUrl::toAce(tlsHostName);
558 // only send the SNI header if the URL is valid and not an IP
559 if (!ace.isEmpty()
560 && !QHostAddress().setAddress(tlsHostName)
561 && !(configuration.sslOptions & QSsl::SslOptionDisableServerNameIndication)) {
562 // We don't send the trailing dot from the host header if present see
563 // https://tools.ietf.org/html/rfc6066#section-3
564 if (ace.endsWith('.'))
565 ace.chop(1);
566 if (!q_SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, ace.data()))
567 qCWarning(lcSsl, "could not set SSL_CTRL_SET_TLSEXT_HOSTNAME, Server Name Indication disabled");
568 }
569 }
570
571 // Clear the session.
572 errorList.clear();
573
574 // Initialize memory BIOs for encryption and decryption.
575 readBio = q_BIO_new(q_BIO_s_mem());
576 writeBio = q_BIO_new(q_BIO_s_mem());
577 if (!readBio || !writeBio) {
578 setErrorAndEmit(QAbstractSocket::SslInternalError,
579 QSslSocket::tr("Error creating SSL session: %1").arg(getErrorsFromOpenSsl()));
580 return false;
581 }
582
583 // Assign the bios.
584 q_SSL_set_bio(ssl, readBio, writeBio);
585
586 if (mode == QSslSocket::SslClientMode)
587 q_SSL_set_connect_state(ssl);
588 else
589 q_SSL_set_accept_state(ssl);
590
591 q_SSL_set_ex_data(ssl, s_indexForSSLExtraData, this);
592
593#if OPENSSL_VERSION_NUMBER >= 0x10001000L && !defined(OPENSSL_NO_PSK)
594 // Set the client callback for PSK
595 if (QSslSocket::sslLibraryVersionNumber() >= 0x10001000L) {
596 if (mode == QSslSocket::SslClientMode)
597 q_SSL_set_psk_client_callback(ssl, &q_ssl_psk_client_callback);
598 else if (mode == QSslSocket::SslServerMode)
599 q_SSL_set_psk_server_callback(ssl, &q_ssl_psk_server_callback);
600 }
601#endif
602#if OPENSSL_VERSION_NUMBER >= 0x10101006L
603 // Set the client callback for TLSv1.3 PSK
604 if (mode == QSslSocket::SslClientMode
605 && QSslSocket::sslLibraryBuildVersionNumber() >= 0x10101006L) {
606 q_SSL_set_psk_use_session_callback(ssl, &q_ssl_psk_use_session_callback);
607 }
608#endif // openssl version >= 0x10101006L
609
610#if QT_CONFIG(ocsp)
611 if (configuration.ocspStaplingEnabled) {
612 if (mode == QSslSocket::SslServerMode) {
613 setErrorAndEmit(QAbstractSocket::SslInvalidUserDataError,
614 QSslSocket::tr("Server-side QSslSocket does not support OCSP stapling"));
615 return false;
616 }
617 if (q_SSL_set_tlsext_status_type(ssl, TLSEXT_STATUSTYPE_ocsp) != 1) {
618 setErrorAndEmit(QAbstractSocket::SslInternalError,
619 QSslSocket::tr("Failed to enable OCSP stapling"));
620 return false;
621 }
622 }
623
624 ocspResponseDer.clear();
625 auto responsePos = configuration.backendConfig.find("Qt-OCSP-response");
626 if (responsePos != configuration.backendConfig.end()) {
627 // This is our private, undocumented 'API' we use for the auto-testing of
628 // OCSP-stapling. It must be a der-encoded OCSP response, presumably set
629 // by tst_QOcsp.
630 const QVariant data(responsePos.value());
631 if (data.canConvert<QByteArray>())
632 ocspResponseDer = data.toByteArray();
633 }
634
635 if (ocspResponseDer.size()) {
636 if (mode != QSslSocket::SslServerMode) {
637 setErrorAndEmit(QAbstractSocket::SslInvalidUserDataError,
638 QSslSocket::tr("Client-side sockets do not send OCSP responses"));
639 return false;
640 }
641 }
642#endif // ocsp
643
644 return true;
645}
646
647void QSslSocketBackendPrivate::destroySslContext()
648{
649 if (ssl) {
650 // We do not send a shutdown alert here. Just mark the session as
651 // resumable for qhttpnetworkconnection's "optimization", otherwise
652 // OpenSSL won't start a session resumption.
653 q_SSL_shutdown(ssl);
654 q_SSL_free(ssl);
655 ssl = nullptr;
656 }
657 sslContextPointer.clear();
658}
659
660/*!
661 \internal
662
663 Does the minimum amount of initialization to determine whether SSL
664 is supported or not.
665*/
666
667bool QSslSocketPrivate::supportsSsl()
668{
669 return ensureLibraryLoaded();
670}
671
672
673/*!
674 \internal
675
676 Declared static in QSslSocketPrivate, makes sure the SSL libraries have
677 been initialized.
678*/
679
680void QSslSocketPrivate::ensureInitialized()
681{
682 if (!supportsSsl())
683 return;
684
685 ensureCiphersAndCertsLoaded();
686}
687
688long QSslSocketPrivate::sslLibraryBuildVersionNumber()
689{
690 return OPENSSL_VERSION_NUMBER;
691}
692
693QString QSslSocketPrivate::sslLibraryBuildVersionString()
694{
695 // Using QStringLiteral to store the version string as unicode and
696 // avoid false positives from Google searching the playstore for old
697 // SSL versions. See QTBUG-46265
698 return QStringLiteral(OPENSSL_VERSION_TEXT);
699}
700
701/*!
702 \internal
703
704 Declared static in QSslSocketPrivate, backend-dependent loading of
705 application-wide global ciphers.
706*/
707void QSslSocketPrivate::resetDefaultCiphers()
708{
709#if QT_CONFIG(opensslv11)
710 SSL_CTX *myCtx = q_SSL_CTX_new(q_TLS_client_method());
711#else
712 SSL_CTX *myCtx = q_SSL_CTX_new(q_SSLv23_client_method());
713#endif
714 // Note, we assert, not just silently return/bail out early:
715 // this should never happen and problems with OpenSSL's initialization
716 // must be caught before this (see supportsSsl()).
717 Q_ASSERT(myCtx);
718 SSL *mySsl = q_SSL_new(myCtx);
719 Q_ASSERT(mySsl);
720
721 QList<QSslCipher> ciphers;
722 QList<QSslCipher> defaultCiphers;
723
724 q_loadCiphersForConnection(mySsl, ciphers, defaultCiphers);
725
726 q_SSL_CTX_free(myCtx);
727 q_SSL_free(mySsl);
728
729 setDefaultSupportedCiphers(ciphers);
730 setDefaultCiphers(defaultCiphers);
731
732#if QT_CONFIG(dtls)
733 ciphers.clear();
734 defaultCiphers.clear();
735 myCtx = q_SSL_CTX_new(q_DTLS_client_method());
736 if (myCtx) {
737 mySsl = q_SSL_new(myCtx);
738 if (mySsl) {
739 q_loadCiphersForConnection(mySsl, ciphers, defaultCiphers);
740 q_setDefaultDtlsCiphers(defaultCiphers);
741 q_SSL_free(mySsl);
742 }
743 q_SSL_CTX_free(myCtx);
744 }
745#endif // dtls
746}
747
748void QSslSocketPrivate::resetDefaultEllipticCurves()
749{
750 QVector<QSslEllipticCurve> curves;
751
752#ifndef OPENSSL_NO_EC
753 const size_t curveCount = q_EC_get_builtin_curves(nullptr, 0);
754
755 QVarLengthArray<EC_builtin_curve> builtinCurves(static_cast<int>(curveCount));
756
757 if (q_EC_get_builtin_curves(builtinCurves.data(), curveCount) == curveCount) {
758 curves.reserve(int(curveCount));
759 for (size_t i = 0; i < curveCount; ++i) {
760 QSslEllipticCurve curve;
761 curve.id = builtinCurves[int(i)].nid;
762 curves.append(curve);
763 }
764 }
765#endif // OPENSSL_NO_EC
766
767 // set the list of supported ECs, but not the list
768 // of *default* ECs. OpenSSL doesn't like forcing an EC for the wrong
769 // ciphersuite, so don't try it -- leave the empty list to mean
770 // "the implementation will choose the most suitable one".
771 setDefaultSupportedEllipticCurves(curves);
772}
773
774#ifndef Q_OS_DARWIN // Apple implementation in qsslsocket_mac_shared.cpp
775QList<QSslCertificate> QSslSocketPrivate::systemCaCertificates()
776{
777 ensureInitialized();
778#ifdef QSSLSOCKET_DEBUG
779 QElapsedTimer timer;
780 timer.start();
781#endif
782 QList<QSslCertificate> systemCerts;
783#if defined(Q_OS_WIN)
784 HCERTSTORE hSystemStore;
785 hSystemStore = CertOpenSystemStoreW(0, L"ROOT");
786 if (hSystemStore) {
787 PCCERT_CONTEXT pc = nullptr;
788 while (1) {
789 pc = CertFindCertificateInStore(hSystemStore, X509_ASN_ENCODING, 0, CERT_FIND_ANY, nullptr, pc);
790 if (!pc)
791 break;
792 QByteArray der(reinterpret_cast<const char *>(pc->pbCertEncoded),
793 static_cast<int>(pc->cbCertEncoded));
794 QSslCertificate cert(der, QSsl::Der);
795 systemCerts.append(cert);
796 }
797 CertCloseStore(hSystemStore, 0);
798 }
799#elif defined(Q_OS_UNIX)
800 QSet<QString> certFiles;
801 QDir currentDir;
802 QStringList nameFilters;
803 QList<QByteArray> directories;
804 QSsl::EncodingFormat platformEncodingFormat;
805# ifndef Q_OS_ANDROID
806 directories = unixRootCertDirectories();
807 nameFilters << QLatin1String("*.pem") << QLatin1String("*.crt");
808 platformEncodingFormat = QSsl::Pem;
809# else
810 // Q_OS_ANDROID
811 QByteArray ministroPath = qgetenv("MINISTRO_SSL_CERTS_PATH"); // Set by Ministro
812 directories << ministroPath;
813 nameFilters << QLatin1String("*.der");
814 platformEncodingFormat = QSsl::Der;
815# ifndef Q_OS_ANDROID_EMBEDDED
816 if (ministroPath.isEmpty()) {
817 QList<QByteArray> certificateData = fetchSslCertificateData();
818 for (int i = 0; i < certificateData.size(); ++i) {
819 systemCerts.append(QSslCertificate::fromData(certificateData.at(i), QSsl::Der));
820 }
821 } else
822# endif //Q_OS_ANDROID_EMBEDDED
823# endif //Q_OS_ANDROID
824 {
825 currentDir.setNameFilters(nameFilters);
826 for (int a = 0; a < directories.count(); a++) {
827 currentDir.setPath(QLatin1String(directories.at(a)));
828 QDirIterator it(currentDir);
829 while (it.hasNext()) {
830 it.next();
831 // use canonical path here to not load the same certificate twice if symlinked
832 certFiles.insert(it.fileInfo().canonicalFilePath());
833 }
834 }
835 for (const QString& file : qAsConst(certFiles))
836 systemCerts.append(QSslCertificate::fromPath(file, platformEncodingFormat));
837# ifndef Q_OS_ANDROID
838 systemCerts.append(QSslCertificate::fromPath(QLatin1String("/etc/pki/tls/certs/ca-bundle.crt"), QSsl::Pem)); // Fedora, Mandriva
839 systemCerts.append(QSslCertificate::fromPath(QLatin1String("/usr/local/share/certs/ca-root-nss.crt"), QSsl::Pem)); // FreeBSD's ca_root_nss
840# endif
841 }
842#endif
843#ifdef QSSLSOCKET_DEBUG
844 qCDebug(lcSsl) << "systemCaCertificates retrieval time " << timer.elapsed() << "ms";
845 qCDebug(lcSsl) << "imported " << systemCerts.count() << " certificates";
846#endif
847
848 return systemCerts;
849}
850#endif // Q_OS_DARWIN
851
852void QSslSocketBackendPrivate::startClientEncryption()
853{
854 if (!initSslContext()) {
855 setErrorAndEmit(QAbstractSocket::SslInternalError,
856 QSslSocket::tr("Unable to init SSL Context: %1").arg(getErrorsFromOpenSsl()));
857 return;
858 }
859
860 // Start connecting. This will place outgoing data in the BIO, so we
861 // follow up with calling transmit().
862 startHandshake();
863 transmit();
864}
865
866void QSslSocketBackendPrivate::startServerEncryption()
867{
868 if (!initSslContext()) {
869 setErrorAndEmit(QAbstractSocket::SslInternalError,
870 QSslSocket::tr("Unable to init SSL Context: %1").arg(getErrorsFromOpenSsl()));
871 return;
872 }
873
874 // Start connecting. This will place outgoing data in the BIO, so we
875 // follow up with calling transmit().
876 startHandshake();
877 transmit();
878}
879
880/*!
881 \internal
882
883 Transmits encrypted data between the BIOs and the socket.
884*/
885void QSslSocketBackendPrivate::transmit()
886{
887 Q_Q(QSslSocket);
888
889 using ScopedBool = QScopedValueRollback<bool>;
890
891 if (inSetAndEmitError)
892 return;
893
894 // If we don't have any SSL context, don't bother transmitting.
895 if (!ssl)
896 return;
897
898 bool transmitting;
899 do {
900 transmitting = false;
901
902 // If the connection is secure, we can transfer data from the write
903 // buffer (in plain text) to the write BIO through SSL_write.
904 if (connectionEncrypted && !writeBuffer.isEmpty()) {
905 qint64 totalBytesWritten = 0;
906 int nextDataBlockSize;
907 while ((nextDataBlockSize = writeBuffer.nextDataBlockSize()) > 0) {
908 int writtenBytes = q_SSL_write(ssl, writeBuffer.readPointer(), nextDataBlockSize);
909 if (writtenBytes <= 0) {
910 int error = q_SSL_get_error(ssl, writtenBytes);
911 //write can result in a want_write_error - not an error - continue transmitting
912 if (error == SSL_ERROR_WANT_WRITE) {
913 transmitting = true;
914 break;
915 } else if (error == SSL_ERROR_WANT_READ) {
916 //write can result in a want_read error, possibly due to renegotiation - not an error - stop transmitting
917 transmitting = false;
918 break;
919 } else {
920 // ### Better error handling.
921 const ScopedBool bg(inSetAndEmitError, true);
922 setErrorAndEmit(QAbstractSocket::SslInternalError,
923 QSslSocket::tr("Unable to write data: %1").arg(
924 getErrorsFromOpenSsl()));
925 return;
926 }
927 }
928#ifdef QSSLSOCKET_DEBUG
929 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: encrypted" << writtenBytes << "bytes";
930#endif
931 writeBuffer.free(writtenBytes);
932 totalBytesWritten += writtenBytes;
933
934 if (writtenBytes < nextDataBlockSize) {
935 // break out of the writing loop and try again after we had read
936 transmitting = true;
937 break;
938 }
939 }
940
941 if (totalBytesWritten > 0) {
942 // Don't emit bytesWritten() recursively.
943 if (!emittedBytesWritten) {
944 emittedBytesWritten = true;
945 emit q->bytesWritten(totalBytesWritten);
946 emittedBytesWritten = false;
947 }
948 emit q->channelBytesWritten(0, totalBytesWritten);
949 }
950 }
951
952 // Check if we've got any data to be written to the socket.
953 QVarLengthArray<char, 4096> data;
954 int pendingBytes;
955 while (plainSocket->isValid() && (pendingBytes = q_BIO_pending(writeBio)) > 0
956 && plainSocket->openMode() != QIODevice::NotOpen) {
957 // Read encrypted data from the write BIO into a buffer.
958 data.resize(pendingBytes);
959 int encryptedBytesRead = q_BIO_read(writeBio, data.data(), pendingBytes);
960
961 // Write encrypted data from the buffer to the socket.
962 qint64 actualWritten = plainSocket->write(data.constData(), encryptedBytesRead);
963#ifdef QSSLSOCKET_DEBUG
964 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: wrote" << encryptedBytesRead << "encrypted bytes to the socket" << actualWritten << "actual.";
965#endif
966 if (actualWritten < 0) {
967 //plain socket write fails if it was in the pending close state.
968 const ScopedBool bg(inSetAndEmitError, true);
969 setErrorAndEmit(plainSocket->error(), plainSocket->errorString());
970 return;
971 }
972 transmitting = true;
973 }
974
975 // Check if we've got any data to be read from the socket.
976 if (!connectionEncrypted || !readBufferMaxSize || buffer.size() < readBufferMaxSize)
977 while ((pendingBytes = plainSocket->bytesAvailable()) > 0) {
978 // Read encrypted data from the socket into a buffer.
979 data.resize(pendingBytes);
980 // just peek() here because q_BIO_write could write less data than expected
981 int encryptedBytesRead = plainSocket->peek(data.data(), pendingBytes);
982
983#ifdef QSSLSOCKET_DEBUG
984 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: read" << encryptedBytesRead << "encrypted bytes from the socket";
985#endif
986 // Write encrypted data from the buffer into the read BIO.
987 int writtenToBio = q_BIO_write(readBio, data.constData(), encryptedBytesRead);
988
989 // Throw away the results.
990 if (writtenToBio > 0) {
991 plainSocket->skip(writtenToBio);
992 } else {
993 // ### Better error handling.
994 const ScopedBool bg(inSetAndEmitError, true);
995 setErrorAndEmit(QAbstractSocket::SslInternalError,
996 QSslSocket::tr("Unable to decrypt data: %1").arg(
997 getErrorsFromOpenSsl()));
998 return;
999 }
1000
1001 transmitting = true;
1002 }
1003
1004 // If the connection isn't secured yet, this is the time to retry the
1005 // connect / accept.
1006 if (!connectionEncrypted) {
1007#ifdef QSSLSOCKET_DEBUG
1008 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: testing encryption";
1009#endif
1010 if (startHandshake()) {
1011#ifdef QSSLSOCKET_DEBUG
1012 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: encryption established";
1013#endif
1014 connectionEncrypted = true;
1015 transmitting = true;
1016 } else if (plainSocket->state() != QAbstractSocket::ConnectedState) {
1017#ifdef QSSLSOCKET_DEBUG
1018 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: connection lost";
1019#endif
1020 break;
1021 } else if (paused) {
1022 // just wait until the user continues
1023 return;
1024 } else {
1025#ifdef QSSLSOCKET_DEBUG
1026 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: encryption not done yet";
1027#endif
1028 }
1029 }
1030
1031 // If the request is small and the remote host closes the transmission
1032 // after sending, there's a chance that startHandshake() will already
1033 // have triggered a shutdown.
1034 if (!ssl)
1035 continue;
1036
1037 // We always read everything from the SSL decryption buffers, even if
1038 // we have a readBufferMaxSize. There's no point in leaving data there
1039 // just so that readBuffer.size() == readBufferMaxSize.
1040 int readBytes = 0;
1041 const int bytesToRead = 4096;
1042 do {
1043 if (readChannelCount == 0) {
1044 // The read buffer is deallocated, don't try resize or write to it.
1045 break;
1046 }
1047 // Don't use SSL_pending(). It's very unreliable.
1048 readBytes = q_SSL_read(ssl, buffer.reserve(bytesToRead), bytesToRead);
1049 if (readBytes > 0) {
1050#ifdef QSSLSOCKET_DEBUG
1051 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: decrypted" << readBytes << "bytes";
1052#endif
1053 buffer.chop(bytesToRead - readBytes);
1054
1055 if (readyReadEmittedPointer)
1056 *readyReadEmittedPointer = true;
1057 emit q->readyRead();
1058 emit q->channelReadyRead(0);
1059 transmitting = true;
1060 continue;
1061 }
1062 buffer.chop(bytesToRead);
1063
1064 // Error.
1065 switch (q_SSL_get_error(ssl, readBytes)) {
1066 case SSL_ERROR_WANT_READ:
1067 case SSL_ERROR_WANT_WRITE:
1068 // Out of data.
1069 break;
1070 case SSL_ERROR_ZERO_RETURN:
1071 // The remote host closed the connection.
1072#ifdef QSSLSOCKET_DEBUG
1073 qCDebug(lcSsl) << "QSslSocketBackendPrivate::transmit: remote disconnect";
1074#endif
1075 shutdown = true; // the other side shut down, make sure we do not send shutdown ourselves
1076 {
1077 const ScopedBool bg(inSetAndEmitError, true);
1078 setErrorAndEmit(QAbstractSocket::RemoteHostClosedError,
1079 QSslSocket::tr("The TLS/SSL connection has been closed"));
1080 }
1081 return;
1082 case SSL_ERROR_SYSCALL: // some IO error
1083 case SSL_ERROR_SSL: // error in the SSL library
1084 // we do not know exactly what the error is, nor whether we can recover from it,
1085 // so just return to prevent an endless loop in the outer "while" statement
1086 {
1087 const ScopedBool bg(inSetAndEmitError, true);
1088 setErrorAndEmit(QAbstractSocket::SslInternalError,
1089 QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
1090 }
1091 return;
1092 default:
1093 // SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT: can only happen with a
1094 // BIO_s_connect() or BIO_s_accept(), which we do not call.
1095 // SSL_ERROR_WANT_X509_LOOKUP: can only happen with a
1096 // SSL_CTX_set_client_cert_cb(), which we do not call.
1097 // So this default case should never be triggered.
1098 {
1099 const ScopedBool bg(inSetAndEmitError, true);
1100 setErrorAndEmit(QAbstractSocket::SslInternalError,
1101 QSslSocket::tr("Error while reading: %1").arg(getErrorsFromOpenSsl()));
1102 }
1103 break;
1104 }
1105 } while (ssl && readBytes > 0);
1106 } while (ssl && transmitting);
1107}
1108
1109QSslError _q_OpenSSL_to_QSslError(int errorCode, const QSslCertificate &cert)
1110{
1111 QSslError error;
1112 switch (errorCode) {
1113 case X509_V_OK:
1114 // X509_V_OK is also reported if the peer had no certificate.
1115 break;
1116 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1117 error = QSslError(QSslError::UnableToGetIssuerCertificate, cert); break;
1118 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1119 error = QSslError(QSslError::UnableToDecryptCertificateSignature, cert); break;
1120 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1121 error = QSslError(QSslError::UnableToDecodeIssuerPublicKey, cert); break;
1122 case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1123 error = QSslError(QSslError::CertificateSignatureFailed, cert); break;
1124 case X509_V_ERR_CERT_NOT_YET_VALID:
1125 error = QSslError(QSslError::CertificateNotYetValid, cert); break;
1126 case X509_V_ERR_CERT_HAS_EXPIRED:
1127 error = QSslError(QSslError::CertificateExpired, cert); break;
1128 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1129 error = QSslError(QSslError::InvalidNotBeforeField, cert); break;
1130 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1131 error = QSslError(QSslError::InvalidNotAfterField, cert); break;
1132 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1133 error = QSslError(QSslError::SelfSignedCertificate, cert); break;
1134 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1135 error = QSslError(QSslError::SelfSignedCertificateInChain, cert); break;
1136 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1137 error = QSslError(QSslError::UnableToGetLocalIssuerCertificate, cert); break;
1138 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1139 error = QSslError(QSslError::UnableToVerifyFirstCertificate, cert); break;
1140 case X509_V_ERR_CERT_REVOKED:
1141 error = QSslError(QSslError::CertificateRevoked, cert); break;
1142 case X509_V_ERR_INVALID_CA:
1143 error = QSslError(QSslError::InvalidCaCertificate, cert); break;
1144 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1145 error = QSslError(QSslError::PathLengthExceeded, cert); break;
1146 case X509_V_ERR_INVALID_PURPOSE:
1147 error = QSslError(QSslError::InvalidPurpose, cert); break;
1148 case X509_V_ERR_CERT_UNTRUSTED:
1149 error = QSslError(QSslError::CertificateUntrusted, cert); break;
1150 case X509_V_ERR_CERT_REJECTED:
1151 error = QSslError(QSslError::CertificateRejected, cert); break;
1152 default:
1153 error = QSslError(QSslError::UnspecifiedError, cert); break;
1154 }
1155 return error;
1156}
1157
1158QString QSslSocketBackendPrivate::msgErrorsDuringHandshake()
1159{
1160 return QSslSocket::tr("Error during SSL handshake: %1")
1161 .arg(QSslSocketBackendPrivate::getErrorsFromOpenSsl());
1162}
1163
1164bool QSslSocketBackendPrivate::startHandshake()
1165{
1166 Q_Q(QSslSocket);
1167
1168 // Check if the connection has been established. Get all errors from the
1169 // verification stage.
1170
1171 using ScopedBool = QScopedValueRollback<bool>;
1172
1173 if (inSetAndEmitError)
1174 return false;
1175
1176 QVector<QSslErrorEntry> lastErrors;
1177 q_SSL_set_ex_data(ssl, s_indexForSSLExtraData + 1, &lastErrors);
1178 int result = (mode == QSslSocket::SslClientMode) ? q_SSL_connect(ssl) : q_SSL_accept(ssl);
1179 q_SSL_set_ex_data(ssl, s_indexForSSLExtraData + 1, nullptr);
1180
1181 if (!lastErrors.isEmpty())
1182 storePeerCertificates();
1183 for (const auto &currentError : qAsConst(lastErrors)) {
1184 emit q->peerVerifyError(_q_OpenSSL_to_QSslError(currentError.code,
1185 configuration.peerCertificateChain.value(currentError.depth)));
1186 if (q->state() != QAbstractSocket::ConnectedState)
1187 break;
1188 }
1189
1190 errorList << lastErrors;
1191
1192 // Connection aborted during handshake phase.
1193 if (q->state() != QAbstractSocket::ConnectedState)
1194 return false;
1195
1196 // Check if we're encrypted or not.
1197 if (result <= 0) {
1198 switch (q_SSL_get_error(ssl, result)) {
1199 case SSL_ERROR_WANT_READ:
1200 case SSL_ERROR_WANT_WRITE:
1201 // The handshake is not yet complete.
1202 break;
1203 default:
1204 QString errorString = QSslSocketBackendPrivate::msgErrorsDuringHandshake();
1205#ifdef QSSLSOCKET_DEBUG
1206 qCDebug(lcSsl) << "QSslSocketBackendPrivate::startHandshake: error!" << errorString;
1207#endif
1208 {
1209 const ScopedBool bg(inSetAndEmitError, true);
1210 setErrorAndEmit(QAbstractSocket::SslHandshakeFailedError, errorString);
1211 }
1212 q->abort();
1213 }
1214 return false;
1215 }
1216
1217 // store peer certificate chain
1218 storePeerCertificates();
1219
1220 // Start translating errors.
1221 QList<QSslError> errors;
1222
1223 // check the whole chain for blacklisting (including root, as we check for subjectInfo and issuer)
1224 for (const QSslCertificate &cert : qAsConst(configuration.peerCertificateChain)) {
1225 if (QSslCertificatePrivate::isBlacklisted(cert)) {
1226 QSslError error(QSslError::CertificateBlacklisted, cert);
1227 errors << error;
1228 emit q->peerVerifyError(error);
1229 if (q->state() != QAbstractSocket::ConnectedState)
1230 return false;
1231 }
1232 }
1233
1234 const bool doVerifyPeer = configuration.peerVerifyMode == QSslSocket::VerifyPeer
1235 || (configuration.peerVerifyMode == QSslSocket::AutoVerifyPeer
1236 && mode == QSslSocket::SslClientMode);
1237
1238#if QT_CONFIG(ocsp)
1239 // For now it's always QSslSocket::SslClientMode - initSslContext() will bail out early,
1240 // if it's enabled in QSslSocket::SslServerMode. This can change.
1241 if (!configuration.peerCertificate.isNull() && configuration.ocspStaplingEnabled && doVerifyPeer) {
1242 if (!checkOcspStatus()) {
1243 if (ocspErrors.isEmpty()) {
1244 {
1245 const ScopedBool bg(inSetAndEmitError, true);
1246 setErrorAndEmit(QAbstractSocket::SslHandshakeFailedError, ocspErrorDescription);
1247 }
1248 q->abort();
1249 return false;
1250 }
1251
1252 for (const QSslError &error : ocspErrors) {
1253 errors << error;
1254 emit q->peerVerifyError(error);
1255 if (q->state() != QAbstractSocket::ConnectedState)
1256 return false;
1257 }
1258 }
1259 }
1260#endif // ocsp
1261
1262 // Check the peer certificate itself. First try the subject's common name
1263 // (CN) as a wildcard, then try all alternate subject name DNS entries the
1264 // same way.
1265 if (!configuration.peerCertificate.isNull()) {
1266 // but only if we're a client connecting to a server
1267 // if we're the server, don't check CN
1268 if (mode == QSslSocket::SslClientMode) {
1269 QString peerName = (verificationPeerName.isEmpty () ? q->peerName() : verificationPeerName);
1270
1271 if (!isMatchingHostname(configuration.peerCertificate, peerName)) {
1272 // No matches in common names or alternate names.
1273 QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate);
1274 errors << error;
1275 emit q->peerVerifyError(error);
1276 if (q->state() != QAbstractSocket::ConnectedState)
1277 return false;
1278 }
1279 }
1280 } else {
1281 // No peer certificate presented. Report as error if the socket
1282 // expected one.
1283 if (doVerifyPeer) {
1284 QSslError error(QSslError::NoPeerCertificate);
1285 errors << error;
1286 emit q->peerVerifyError(error);
1287 if (q->state() != QAbstractSocket::ConnectedState)
1288 return false;
1289 }
1290 }
1291
1292 // Translate errors from the error list into QSslErrors.
1293 errors.reserve(errors.size() + errorList.size());
1294 for (const auto &error : qAsConst(errorList))
1295 errors << _q_OpenSSL_to_QSslError(error.code, configuration.peerCertificateChain.value(error.depth));
1296
1297 if (!errors.isEmpty()) {
1298 sslErrors = errors;
1299
1300#ifdef Q_OS_WIN
1301 //Skip this if not using system CAs, or if the SSL errors are configured in advance to be ignorable
1302 if (doVerifyPeer
1303 && s_loadRootCertsOnDemand
1304 && allowRootCertOnDemandLoading
1305 && !verifyErrorsHaveBeenIgnored()) {
1306 //Windows desktop versions starting from vista ship with minimal set of roots
1307 //and download on demand from the windows update server CA roots that are
1308 //trusted by MS.
1309 //However, this is only transparent if using WinINET - we have to trigger it
1310 //ourselves.
1311 QSslCertificate certToFetch;
1312 bool fetchCertificate = true;
1313 for (int i=0; i< sslErrors.count(); i++) {
1314 switch (sslErrors.at(i).error()) {
1315 case QSslError::UnableToGetLocalIssuerCertificate: // site presented intermediate cert, but root is unknown
1316 case QSslError::SelfSignedCertificateInChain: // site presented a complete chain, but root is unknown
1317 certToFetch = sslErrors.at(i).certificate();
1318 break;
1319 case QSslError::SelfSignedCertificate:
1320 case QSslError::CertificateBlacklisted:
1321 //With these errors, we know it will be untrusted so save time by not asking windows
1322 fetchCertificate = false;
1323 break;
1324 default:
1325#ifdef QSSLSOCKET_DEBUG
1326 qCDebug(lcSsl) << sslErrors.at(i).errorString();
1327#endif
1328 break;
1329 }
1330 }
1331 if (fetchCertificate && !certToFetch.isNull()) {
1332 fetchCaRootForCert(certToFetch);
1333 return false;
1334 }
1335 }
1336#endif
1337 if (!checkSslErrors())
1338 return false;
1339 // A slot, attached to sslErrors signal can call
1340 // abort/close/disconnetFromHost/etc; no need to
1341 // continue handshake then.
1342 if (q->state() != QAbstractSocket::ConnectedState)
1343 return false;
1344 } else {
1345 sslErrors.clear();
1346 }
1347
1348 continueHandshake();
1349 return true;
1350}
1351
1352void QSslSocketBackendPrivate::storePeerCertificates()
1353{
1354 // Store the peer certificate and chain. For clients, the peer certificate
1355 // chain includes the peer certificate; for servers, it doesn't. Both the
1356 // peer certificate and the chain may be empty if the peer didn't present
1357 // any certificate.
1358 X509 *x509 = q_SSL_get_peer_certificate(ssl);
1359 configuration.peerCertificate = QSslCertificatePrivate::QSslCertificate_from_X509(x509);
1360 q_X509_free(x509);
1361 if (configuration.peerCertificateChain.isEmpty()) {
1362 configuration.peerCertificateChain = STACKOFX509_to_QSslCertificates(q_SSL_get_peer_cert_chain(ssl));
1363 if (!configuration.peerCertificate.isNull() && mode == QSslSocket::SslServerMode)
1364 configuration.peerCertificateChain.prepend(configuration.peerCertificate);
1365 }
1366}
1367
1368bool QSslSocketBackendPrivate::checkSslErrors()
1369{
1370 Q_Q(QSslSocket);
1371 if (sslErrors.isEmpty())
1372 return true;
1373
1374 emit q->sslErrors(sslErrors);
1375
1376 bool doVerifyPeer = configuration.peerVerifyMode == QSslSocket::VerifyPeer
1377 || (configuration.peerVerifyMode == QSslSocket::AutoVerifyPeer
1378 && mode == QSslSocket::SslClientMode);
1379 bool doEmitSslError = !verifyErrorsHaveBeenIgnored();
1380 // check whether we need to emit an SSL handshake error
1381 if (doVerifyPeer && doEmitSslError) {
1382 if (q->pauseMode() & QAbstractSocket::PauseOnSslErrors) {
1383 pauseSocketNotifiers(q);
1384 paused = true;
1385 } else {
1386 setErrorAndEmit(QAbstractSocket::SslHandshakeFailedError, sslErrors.constFirst().errorString());
1387 plainSocket->disconnectFromHost();
1388 }
1389 return false;
1390 }
1391 return true;
1392}
1393
1394unsigned int QSslSocketBackendPrivate::tlsPskClientCallback(const char *hint,
1395 char *identity, unsigned int max_identity_len,
1396 unsigned char *psk, unsigned int max_psk_len)
1397{
1398 QSslPreSharedKeyAuthenticator authenticator;
1399
1400 // Fill in some read-only fields (for the user)
1401 if (hint)
1402 authenticator.d->identityHint = QByteArray::fromRawData(hint, int(::strlen(hint))); // it's NUL terminated, but do not include the NUL
1403
1404 authenticator.d->maximumIdentityLength = int(max_identity_len) - 1; // needs to be NUL terminated
1405 authenticator.d->maximumPreSharedKeyLength = int(max_psk_len);
1406
1407 // Let the client provide the remaining bits...
1408 Q_Q(QSslSocket);
1409 emit q->preSharedKeyAuthenticationRequired(&authenticator);
1410
1411 // No PSK set? Return now to make the handshake fail
1412 if (authenticator.preSharedKey().isEmpty())
1413 return 0;
1414
1415 // Copy data back into OpenSSL
1416 const int identityLength = qMin(authenticator.identity().length(), authenticator.maximumIdentityLength());
1417 ::memcpy(identity, authenticator.identity().constData(), identityLength);
1418 identity[identityLength] = 0;
1419
1420 const int pskLength = qMin(authenticator.preSharedKey().length(), authenticator.maximumPreSharedKeyLength());
1421 ::memcpy(psk, authenticator.preSharedKey().constData(), pskLength);
1422 return pskLength;
1423}
1424
1425unsigned int QSslSocketBackendPrivate::tlsPskServerCallback(const char *identity,
1426 unsigned char *psk, unsigned int max_psk_len)
1427{
1428 QSslPreSharedKeyAuthenticator authenticator;
1429
1430 // Fill in some read-only fields (for the user)
1431 authenticator.d->identityHint = configuration.preSharedKeyIdentityHint;
1432 authenticator.d->identity = identity;
1433 authenticator.d->maximumIdentityLength = 0; // user cannot set an identity
1434 authenticator.d->maximumPreSharedKeyLength = int(max_psk_len);
1435
1436 // Let the client provide the remaining bits...
1437 Q_Q(QSslSocket);
1438 emit q->preSharedKeyAuthenticationRequired(&authenticator);
1439
1440 // No PSK set? Return now to make the handshake fail
1441 if (authenticator.preSharedKey().isEmpty())
1442 return 0;
1443
1444 // Copy data back into OpenSSL
1445 const int pskLength = qMin(authenticator.preSharedKey().length(), authenticator.maximumPreSharedKeyLength());
1446 ::memcpy(psk, authenticator.preSharedKey().constData(), pskLength);
1447 return pskLength;
1448}
1449
1450#ifdef Q_OS_WIN
1451
1452void QSslSocketBackendPrivate::fetchCaRootForCert(const QSslCertificate &cert)
1453{
1454 Q_Q(QSslSocket);
1455 //The root certificate is downloaded from windows update, which blocks for 15 seconds in the worst case
1456 //so the request is done in a worker thread.
1457 QWindowsCaRootFetcher *fetcher = new QWindowsCaRootFetcher(cert, mode);
1458 QObject::connect(fetcher, SIGNAL(finished(QSslCertificate,QSslCertificate)), q, SLOT(_q_caRootLoaded(QSslCertificate,QSslCertificate)), Qt::QueuedConnection);
1459 QMetaObject::invokeMethod(fetcher, "start", Qt::QueuedConnection);
1460 pauseSocketNotifiers(q);
1461 paused = true;
1462}
1463
1464//This is the callback from QWindowsCaRootFetcher, trustedRoot will be invalid (default constructed) if it failed.
1465void QSslSocketBackendPrivate::_q_caRootLoaded(QSslCertificate cert, QSslCertificate trustedRoot)
1466{
1467 Q_Q(QSslSocket);
1468 if (!trustedRoot.isNull() && !trustedRoot.isBlacklisted()) {
1469 if (s_loadRootCertsOnDemand) {
1470 //Add the new root cert to default cert list for use by future sockets
1471 QSslSocket::addDefaultCaCertificate(trustedRoot);
1472 }
1473 //Add the new root cert to this socket for future connections
1474 q->addCaCertificate(trustedRoot);
1475 //Remove the broken chain ssl errors (as chain is verified by windows)
1476 for (int i=sslErrors.count() - 1; i >= 0; --i) {
1477 if (sslErrors.at(i).certificate() == cert) {
1478 switch (sslErrors.at(i).error()) {
1479 case QSslError::UnableToGetLocalIssuerCertificate:
1480 case QSslError::CertificateUntrusted:
1481 case QSslError::UnableToVerifyFirstCertificate:
1482 case QSslError::SelfSignedCertificateInChain:
1483 // error can be ignored if OS says the chain is trusted
1484 sslErrors.removeAt(i);
1485 break;
1486 default:
1487 // error cannot be ignored
1488 break;
1489 }
1490 }
1491 }
1492 }
1493 // Continue with remaining errors
1494 if (plainSocket)
1495 plainSocket->resume();
1496 paused = false;
1497 if (checkSslErrors() && ssl) {
1498 bool willClose = (autoStartHandshake && pendingClose);
1499 continueHandshake();
1500 if (!willClose)
1501 transmit();
1502 }
1503}
1504
1505#endif
1506
1507#if QT_CONFIG(ocsp)
1508
1509bool QSslSocketBackendPrivate::checkOcspStatus()
1510{
1511 Q_ASSERT(ssl);
1512 Q_ASSERT(mode == QSslSocket::SslClientMode); // See initSslContext() for SslServerMode
1513 Q_ASSERT(configuration.peerVerifyMode != QSslSocket::VerifyNone);
1514
1515 ocspResponses.clear();
1516 ocspErrorDescription.clear();
1517 ocspErrors.clear();
1518
1519 const unsigned char *responseData = nullptr;
1520 const long responseLength = q_SSL_get_tlsext_status_ocsp_resp(ssl, &responseData);
1521 if (responseLength <= 0 || !responseData) {
1522 ocspErrors.push_back(QSslError::OcspNoResponseFound);
1523 return false;
1524 }
1525
1526 OCSP_RESPONSE *response = q_d2i_OCSP_RESPONSE(nullptr, &responseData, responseLength);
1527 if (!response) {
1528 // Treat this as a fatal SslHandshakeError.
1529 ocspErrorDescription = QSslSocket::tr("Failed to decode OCSP response");
1530 return false;
1531 }
1532 const QSharedPointer<OCSP_RESPONSE> responseGuard(response, q_OCSP_RESPONSE_free);
1533
1534 const int ocspStatus = q_OCSP_response_status(response);
1535 if (ocspStatus != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1536 // It's not a definitive response, it's an error message (not signed by the responder).
1537 ocspErrors.push_back(qt_OCSP_response_status_to_QSslError(ocspStatus));
1538 return false;
1539 }
1540
1541 OCSP_BASICRESP *basicResponse = q_OCSP_response_get1_basic(response);
1542 if (!basicResponse) {
1543 // SslHandshakeError.
1544 ocspErrorDescription = QSslSocket::tr("Failed to extract basic OCSP response");
1545 return false;
1546 }
1547 const QSharedPointer<OCSP_BASICRESP> basicResponseGuard(basicResponse, q_OCSP_BASICRESP_free);
1548
1549 SSL_CTX *ctx = q_SSL_get_SSL_CTX(ssl); // Does not increment refcount.
1550 Q_ASSERT(ctx);
1551 X509_STORE *store = q_SSL_CTX_get_cert_store(ctx); // Does not increment refcount.
1552 if (!store) {
1553 // SslHandshakeError.
1554 ocspErrorDescription = QSslSocket::tr("No certificate verification store, cannot verify OCSP response");
1555 return false;
1556 }
1557
1558 STACK_OF(X509) *peerChain = q_SSL_get_peer_cert_chain(ssl); // Does not increment refcount.
1559 X509 *peerX509 = q_SSL_get_peer_certificate(ssl);
1560 Q_ASSERT(peerChain || peerX509);
1561 const QSharedPointer<X509> peerX509Guard(peerX509, q_X509_free);
1562 // OCSP_basic_verify with 0 as verificationFlags:
1563 //
1564 // 0) Tries to find the OCSP responder's certificate in either peerChain
1565 // or basicResponse->certs. If not found, verification fails.
1566 // 1) It checks the signature using the responder's public key.
1567 // 2) Then it tries to validate the responder's cert (building a chain
1568 // etc.)
1569 // 3) It checks CertID in response.
1570 // 4) Ensures the responder is authorized to sign the status respond.
1571 //
1572 // Note, OpenSSL prior to 1.0.2b would only use bs->certs to
1573 // verify the responder's chain (see their commit 4ba9a4265bd).
1574 // Working this around - is too much fuss for ancient versions we
1575 // are dropping quite soon anyway.
1576 const unsigned long verificationFlags = 0;
1577 const int success = q_OCSP_basic_verify(basicResponse, peerChain, store, verificationFlags);
1578 if (success <= 0)
1579 ocspErrors.push_back(QSslError::OcspResponseCannotBeTrusted);
1580
1581 if (q_OCSP_resp_count(basicResponse) != 1) {
1582 ocspErrors.push_back(QSslError::OcspMalformedResponse);
1583 return false;
1584 }
1585
1586 OCSP_SINGLERESP *singleResponse = q_OCSP_resp_get0(basicResponse, 0);
1587 if (!singleResponse) {
1588 ocspErrors.clear();
1589 // A fatal problem -> SslHandshakeError.
1590 ocspErrorDescription = QSslSocket::tr("Failed to decode a SingleResponse from OCSP status response");
1591 return false;
1592 }
1593
1594 // Let's make sure the response is for the correct certificate - we
1595 // can re-create this CertID using our peer's certificate and its
1596 // issuer's public key.
1597 ocspResponses.push_back(QOcspResponse());
1598 QOcspResponsePrivate *dResponse = ocspResponses.back().d.data();
1599 dResponse->subjectCert = configuration.peerCertificate;
1600 bool matchFound = false;
1601 if (configuration.peerCertificate.isSelfSigned()) {
1602 dResponse->signerCert = configuration.peerCertificate;
1603 matchFound = qt_OCSP_certificate_match(singleResponse, peerX509, peerX509);
1604 } else {
1605 const STACK_OF(X509) *certs = q_SSL_get_peer_cert_chain(ssl);
1606 if (!certs) // Oh, what a cataclysm! Last try:
1607 certs = q_OCSP_resp_get0_certs(basicResponse);
1608 if (certs) {
1609 // It could be the first certificate in 'certs' is our peer's
1610 // certificate. Since it was not captured by the 'self-signed' branch
1611 // above, the CertID will not match and we'll just iterate on to the
1612 // next certificate. So we start from 0, not 1.
1613 for (int i = 0, e = q_sk_X509_num(certs); i < e; ++i) {
1614 X509 *issuer = q_sk_X509_value(certs, i);
1615 matchFound = qt_OCSP_certificate_match(singleResponse, peerX509, issuer);
1616 if (matchFound) {
1617 if (q_X509_check_issued(issuer, peerX509) == X509_V_OK) {
1618 dResponse->signerCert = QSslCertificatePrivate::QSslCertificate_from_X509(issuer);
1619 break;
1620 }
1621 matchFound = false;
1622 }
1623 }
1624 }
1625 }
1626
1627 if (!matchFound) {
1628 dResponse->signerCert.clear();
1629 ocspErrors.push_back({QSslError::OcspResponseCertIdUnknown, configuration.peerCertificate});
1630 }
1631
1632 // Check if the response is valid time-wise:
1633 ASN1_GENERALIZEDTIME *revTime = nullptr;
1634 ASN1_GENERALIZEDTIME *thisUpdate = nullptr;
1635 ASN1_GENERALIZEDTIME *nextUpdate = nullptr;
1636 int reason;
1637 const int certStatus = q_OCSP_single_get0_status(singleResponse, &reason, &revTime, &thisUpdate, &nextUpdate);
1638 if (!thisUpdate) {
1639 // This is unexpected, treat as SslHandshakeError, OCSP_check_validity assumes this pointer
1640 // to be != nullptr.
1641 ocspErrors.clear();
1642 ocspResponses.clear();
1643 ocspErrorDescription = QSslSocket::tr("Failed to extract 'this update time' from the SingleResponse");
1644 return false;
1645 }
1646
1647 // OCSP_check_validity(this, next, nsec, maxsec) does this check:
1648 // this <= now <= next. They allow some freedom to account
1649 // for delays/time inaccuracy.
1650 // this > now + nsec ? -> NOT_YET_VALID
1651 // if maxsec >= 0:
1652 // now - maxsec > this ? -> TOO_OLD
1653 // now - nsec > next ? -> EXPIRED
1654 // next < this ? -> NEXT_BEFORE_THIS
1655 // OK.
1656 if (!q_OCSP_check_validity(thisUpdate, nextUpdate, 60, -1))
1657 ocspErrors.push_back({QSslError::OcspResponseExpired, configuration.peerCertificate});
1658
1659 // And finally, the status:
1660 switch (certStatus) {
1661 case V_OCSP_CERTSTATUS_GOOD:
1662 // This certificate was not found among the revoked ones.
1663 dResponse->certificateStatus = QOcspCertificateStatus::Good;
1664 break;
1665 case V_OCSP_CERTSTATUS_REVOKED:
1666 dResponse->certificateStatus = QOcspCertificateStatus::Revoked;
1667 dResponse->revocationReason = qt_OCSP_revocation_reason(reason);
1668 ocspErrors.push_back({QSslError::CertificateRevoked, configuration.peerCertificate});
1669 break;
1670 case V_OCSP_CERTSTATUS_UNKNOWN:
1671 dResponse->certificateStatus = QOcspCertificateStatus::Unknown;
1672 ocspErrors.push_back({QSslError::OcspStatusUnknown, configuration.peerCertificate});
1673 }
1674
1675 return !ocspErrors.size();
1676}
1677
1678#endif // ocsp
1679
1680void QSslSocketBackendPrivate::disconnectFromHost()
1681{
1682 if (ssl) {
1683 if (!shutdown) {
1684 q_SSL_shutdown(ssl);
1685 shutdown = true;
1686 transmit();
1687 }
1688 }
1689 plainSocket->disconnectFromHost();
1690}
1691
1692void QSslSocketBackendPrivate::disconnected()
1693{
1694 if (plainSocket->bytesAvailable() <= 0)
1695 destroySslContext();
1696 else {
1697 // Move all bytes into the plain buffer
1698 qint64 tmpReadBufferMaxSize = readBufferMaxSize;
1699 readBufferMaxSize = 0; // reset temporarily so the plain socket buffer is completely drained
1700 transmit();
1701 readBufferMaxSize = tmpReadBufferMaxSize;
1702 }
1703 //if there is still buffered data in the plain socket, don't destroy the ssl context yet.
1704 //it will be destroyed when the socket is deleted.
1705}
1706
1707QSslCipher QSslSocketBackendPrivate::sessionCipher() const
1708{
1709 if (!ssl)
1710 return QSslCipher();
1711
1712 const SSL_CIPHER *sessionCipher = q_SSL_get_current_cipher(ssl);
1713 return sessionCipher ? QSslCipher_from_SSL_CIPHER(sessionCipher) : QSslCipher();
1714}
1715
1716QSsl::SslProtocol QSslSocketBackendPrivate::sessionProtocol() const
1717{
1718 if (!ssl)
1719 return QSsl::UnknownProtocol;
1720 int ver = q_SSL_version(ssl);
1721
1722 switch (ver) {
1723 case 0x2:
1724 return QSsl::SslV2;
1725 case 0x300:
1726 return QSsl::SslV3;
1727 case 0x301:
1728 return QSsl::TlsV1_0;
1729 case 0x302:
1730 return QSsl::TlsV1_1;
1731 case 0x303:
1732 return QSsl::TlsV1_2;
1733 case 0x304:
1734 return QSsl::TlsV1_3;
1735 }
1736
1737 return QSsl::UnknownProtocol;
1738}
1739
1740QList<QSslCertificate> QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates(STACK_OF(X509) *x509)
1741{
1742 ensureInitialized();
1743 QList<QSslCertificate> certificates;
1744 for (int i = 0; i < q_sk_X509_num(x509); ++i) {
1745 if (X509 *entry = q_sk_X509_value(x509, i))
1746 certificates << QSslCertificatePrivate::QSslCertificate_from_X509(entry);
1747 }
1748 return certificates;
1749}
1750
1751QList<QSslError> QSslSocketBackendPrivate::verify(const QList<QSslCertificate> &certificateChain, const QString &hostName)
1752{
1753 QList<QSslError> errors;
1754 if (certificateChain.count() <= 0) {
1755 errors << QSslError(QSslError::UnspecifiedError);
1756 return errors;
1757 }
1758
1759 // Setup the store with the default CA certificates
1760 X509_STORE *certStore = q_X509_STORE_new();
1761 if (!certStore) {
1762 qCWarning(lcSsl) << "Unable to create certificate store";
1763 errors << QSslError(QSslError::UnspecifiedError);
1764 return errors;
1765 }
1766
1767 if (s_loadRootCertsOnDemand) {
1768 setDefaultCaCertificates(defaultCaCertificates() + systemCaCertificates());
1769 }
1770
1771 const QDateTime now = QDateTime::currentDateTimeUtc();
1772 const auto caCertificates = QSslConfiguration::defaultConfiguration().caCertificates();
1773 for (const QSslCertificate &caCertificate : caCertificates) {
1774 // From https://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html:
1775 //
1776 // If several CA certificates matching the name, key identifier, and
1777 // serial number condition are available, only the first one will be
1778 // examined. This may lead to unexpected results if the same CA
1779 // certificate is available with different expiration dates. If a
1780 // ``certificate expired'' verification error occurs, no other
1781 // certificate will be searched. Make sure to not have expired
1782 // certificates mixed with valid ones.
1783 //
1784 // See also: QSslContext::fromConfiguration()
1785 if (caCertificate.expiryDate() >= now) {
1786 q_X509_STORE_add_cert(certStore, reinterpret_cast<X509 *>(caCertificate.handle()));
1787 }
1788 }
1789
1790 QVector<QSslErrorEntry> lastErrors;
1791#if QT_CONFIG(opensslv11)
1792 if (!q_X509_STORE_set_ex_data(certStore, 0, &lastErrors)) {
1793 qCWarning(lcSsl) << "Unable to attach external data (error list) to a store";
1794 errors << QSslError(QSslError::UnspecifiedError);
1795 return errors;
1796 }
1797#else
1798 if (!q_CRYPTO_set_ex_data(&certStore->ex_data, 0, &lastErrors)) {
1799 qCWarning(lcSsl) << "Unable to attach external data (error list) to a store";
1800 errors << QSslError(QSslError::UnspecifiedError);
1801 return errors;
1802 }
1803#endif // opensslv11
1804
1805 // Register a custom callback to get all verification errors.
1806 q_X509_STORE_set_verify_cb(certStore, q_X509Callback);
1807
1808 // Build the chain of intermediate certificates
1809 STACK_OF(X509) *intermediates = nullptr;
1810 if (certificateChain.length() > 1) {
1811 intermediates = (STACK_OF(X509) *) q_OPENSSL_sk_new_null();
1812
1813 if (!intermediates) {
1814 q_X509_STORE_free(certStore);
1815 errors << QSslError(QSslError::UnspecifiedError);
1816 return errors;
1817 }
1818
1819 bool first = true;
1820 for (const QSslCertificate &cert : certificateChain) {
1821 if (first) {
1822 first = false;
1823 continue;
1824 }
1825
1826 q_OPENSSL_sk_push((OPENSSL_STACK *)intermediates, reinterpret_cast<X509 *>(cert.handle()));
1827 }
1828 }
1829
1830 X509_STORE_CTX *storeContext = q_X509_STORE_CTX_new();
1831 if (!storeContext) {
1832 q_X509_STORE_free(certStore);
1833 errors << QSslError(QSslError::UnspecifiedError);
1834 return errors;
1835 }
1836
1837 if (!q_X509_STORE_CTX_init(storeContext, certStore, reinterpret_cast<X509 *>(certificateChain[0].handle()), intermediates)) {
1838 q_X509_STORE_CTX_free(storeContext);
1839 q_X509_STORE_free(certStore);
1840 errors << QSslError(QSslError::UnspecifiedError);
1841 return errors;
1842 }
1843
1844 // Now we can actually perform the verification of the chain we have built.
1845 // We ignore the result of this function since we process errors via the
1846 // callback.
1847 (void) q_X509_verify_cert(storeContext);
1848
1849 q_X509_STORE_CTX_free(storeContext);
1850 q_OPENSSL_sk_free((OPENSSL_STACK *)intermediates);
1851
1852 // Now process the errors
1853
1854 if (QSslCertificatePrivate::isBlacklisted(certificateChain[0])) {
1855 QSslError error(QSslError::CertificateBlacklisted, certificateChain[0]);
1856 errors << error;
1857 }
1858
1859 // Check the certificate name against the hostname if one was specified
1860 if ((!hostName.isEmpty()) && (!isMatchingHostname(certificateChain[0], hostName))) {
1861 // No matches in common names or alternate names.
1862 QSslError error(QSslError::HostNameMismatch, certificateChain[0]);
1863 errors << error;
1864 }
1865
1866 // Translate errors from the error list into QSslErrors.
1867 errors.reserve(errors.size() + lastErrors.size());
1868 for (const auto &error : qAsConst(lastErrors))
1869 errors << _q_OpenSSL_to_QSslError(error.code, certificateChain.value(error.depth));
1870
1871 q_X509_STORE_free(certStore);
1872
1873 return errors;
1874}
1875
1876bool QSslSocketBackendPrivate::importPkcs12(QIODevice *device,
1877 QSslKey *key, QSslCertificate *cert,
1878 QList<QSslCertificate> *caCertificates,
1879 const QByteArray &passPhrase)
1880{
1881 if (!supportsSsl())
1882 return false;
1883
1884 // These are required
1885 Q_ASSERT(device);
1886 Q_ASSERT(key);
1887 Q_ASSERT(cert);
1888
1889 // Read the file into a BIO
1890 QByteArray pkcs12data = device->readAll();
1891 if (pkcs12data.size() == 0)
1892 return false;
1893
1894 BIO *bio = q_BIO_new_mem_buf(const_cast<char *>(pkcs12data.constData()), pkcs12data.size());
1895
1896 // Create the PKCS#12 object
1897 PKCS12 *p12 = q_d2i_PKCS12_bio(bio, nullptr);
1898 if (!p12) {
1899 qCWarning(lcSsl, "Unable to read PKCS#12 structure, %s",
1900 q_ERR_error_string(q_ERR_get_error(), nullptr));
1901 q_BIO_free(bio);
1902 return false;
1903 }
1904
1905 // Extract the data
1906 EVP_PKEY *pkey = nullptr;
1907 X509 *x509;
1908 STACK_OF(X509) *ca = nullptr;
1909
1910 if (!q_PKCS12_parse(p12, passPhrase.constData(), &pkey, &x509, &ca)) {
1911 qCWarning(lcSsl, "Unable to parse PKCS#12 structure, %s",
1912 q_ERR_error_string(q_ERR_get_error(), nullptr));
1913 q_PKCS12_free(p12);
1914 q_BIO_free(bio);
1915 return false;
1916 }
1917
1918 // Convert to Qt types
1919 if (!key->d->fromEVP_PKEY(pkey)) {
1920 qCWarning(lcSsl, "Unable to convert private key");
1921 q_OPENSSL_sk_pop_free(reinterpret_cast<OPENSSL_STACK *>(ca),
1922 reinterpret_cast<void (*)(void *)>(q_X509_free));
1923 q_X509_free(x509);
1924 q_EVP_PKEY_free(pkey);
1925 q_PKCS12_free(p12);
1926 q_BIO_free(bio);
1927
1928 return false;
1929 }
1930
1931 *cert = QSslCertificatePrivate::QSslCertificate_from_X509(x509);
1932
1933 if (caCertificates)
1934 *caCertificates = QSslSocketBackendPrivate::STACKOFX509_to_QSslCertificates(ca);
1935
1936 // Clean up
1937 q_OPENSSL_sk_pop_free(reinterpret_cast<OPENSSL_STACK *>(ca),
1938 reinterpret_cast<void (*)(void *)>(q_X509_free));
1939
1940 q_X509_free(x509);
1941 q_EVP_PKEY_free(pkey);
1942 q_PKCS12_free(p12);
1943 q_BIO_free(bio);
1944
1945 return true;
1946}
1947
1948
1949QT_END_NAMESPACE
1950