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