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