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 // Note: CB_HANDSHAKE_DONE is also raised when the handshake is paused to exchange early data,
351 // and SSL_in_init() cannot tell the two apart (OpenSSL clears it before invoking us). We never
352 // enable early data; if we ever do, this needs a guard.
353 if (from & SSL_CB_HANDSHAKE_DONE) {
354 // Handshake is done, get keying material:
356 return;
357 }
358
359 if (!(from & SSL_CB_ALERT)) {
360 // We only want to know about alerts (at least for now).
361 return;
362 }
363
364 if (from & SSL_CB_WRITE)
365 crypto->alertMessageSent(value);
366 else
367 crypto->alertMessageReceived(value);
368}
369
370#if QT_CONFIG(ocsp)
371namespace {
372
374{
375 switch (code) {
381 return QSslError::OcspTryLater;
387 default:
388 return {};
389 }
391}
392
394{
395 switch (reason) {
414 default:
416 }
417
419}
420
422{
423 // OCSP_basic_verify does verify that the responder is legit, the response is
424 // correctly signed, CertID is correct. But it does not know which certificate
425 // we were presented with by our peer, so it does not check if it's a response
426 // for our peer's certificate.
428
429 const OCSP_CERTID *certId = q_OCSP_SINGLERESP_get0_id(singleResponse); // Does not increment refcount.
430 if (!certId) {
431 qCWarning(lcTlsBackend, "A SingleResponse without CertID");
432 return false;
433 }
434
435 ASN1_OBJECT *md = nullptr;
437 const int result = q_OCSP_id_get0_info(nullptr, &md, nullptr, &reportedSerialNumber, const_cast<OCSP_CERTID *>(certId));
438 if (result != 1 || !md || !reportedSerialNumber) {
439 qCWarning(lcTlsBackend, "Failed to extract a hash and serial number from CertID structure");
440 return false;
441 }
442
444 // Is this possible at all? But we have to check this,
445 // ASN1_INTEGER_cmp (called from OCSP_id_cmp) dereferences
446 // without any checks at all.
447 qCWarning(lcTlsBackend, "No serial number in peer's ceritificate");
448 return false;
449 }
450
451 const int nid = q_OBJ_obj2nid(md);
452 if (nid == NID_undef) {
453 qCWarning(lcTlsBackend, "Unknown hash algorithm in CertID");
454 return false;
455 }
456
457 const EVP_MD *digest = q_EVP_get_digestbynid(nid); // Does not increment refcount.
458 if (!digest) {
459 qCWarning(lcTlsBackend) << "No digest for nid" << nid;
460 return false;
461 }
462
464 if (!recreatedId) {
465 qCWarning(lcTlsBackend, "Failed to re-create CertID");
466 return false;
467 }
469
470 if (q_OCSP_id_cmp(const_cast<OCSP_CERTID *>(certId), recreatedId)) {
471 qCDebug(lcTlsBackend, "Certificate ID mismatch");
472 return false;
473 }
474 // Bingo!
475 return true;
476}
477
478} // unnamed namespace
479#endif // ocsp
480
482{
483 destroySslContext();
484}
485
486void TlsCryptographOpenSSL::init(QSslSocket *qObj, QSslSocketPrivate *dObj)
487{
488 Q_ASSERT(qObj);
489 Q_ASSERT(dObj);
490 q = qObj;
491 d = dObj;
492
493 ocspResponses.clear();
494 ocspResponseDer.clear();
495
496 systemOrSslErrorDetected = false;
497 handshakeInterrupted = false;
498
499 fetchAuthorityInformation = false;
500 caToFetch.reset();
501
502 auto &sslCfg = d->configuration;
503 for (auto &entry : sslCfg.keyingMaterial)
504 entry = entry.clone();
505}
506
512
514{
515 return sslContextPointer;
516}
517
519{
520 return sslErrors;
521}
522
524{
525 if (!initSslContext()) {
526 Q_ASSERT(d);
527 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
528 QSslSocket::tr("Unable to init SSL Context: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
529 return;
530 }
531
532 // Start connecting. This will place outgoing data in the BIO, so we
533 // follow up with calling transmit().
536}
537
539{
540 if (!initSslContext()) {
541 Q_ASSERT(d);
542 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
543 QSslSocket::tr("Unable to init SSL Context: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
544 return;
545 }
546
547 // Start connecting. This will place outgoing data in the BIO, so we
548 // follow up with calling transmit().
551}
552
554{
555 // Check if the connection has been established. Get all errors from the
556 // verification stage.
557 Q_ASSERT(q);
558 Q_ASSERT(d);
559
560 using ScopedBool = QScopedValueRollback<bool>;
561
562 if (inSetAndEmitError)
563 return false;
564
565 const auto mode = d->tlsMode();
566
567 pendingFatalAlert = false;
568 errorsReportedFromCallback = false;
569 QList<QSslErrorEntry> lastErrors;
570 q_SSL_set_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData + errorOffsetInExData, &lastErrors);
571
572 // SSL_set_ex_data can fail, but see the callback's code - we handle this there.
575
576 int result = (mode == QSslSocket::SslClientMode) ? q_SSL_connect(ssl) : q_SSL_accept(ssl);
578 // Note, unlike errors as external data on SSL object, we do not unset
579 // a callback/ex-data if alert notifications are enabled: an alert can
580 // arrive after the handshake, for example, this happens when the server
581 // does not find a ClientCert or does not like it.
582
583 if (!lastErrors.isEmpty() || errorsReportedFromCallback)
585
586 // storePeerCertificate() if called above - would update the
587 // configuration with peer's certificates.
588 auto configuration = q->sslConfiguration();
589 if (!errorsReportedFromCallback) {
590 const auto &peerCertificateChain = configuration.peerCertificateChain();
591 for (const auto &currentError : std::as_const(lastErrors)) {
592 emit q->peerVerifyError(QTlsPrivate::X509CertificateOpenSSL::openSSLErrorToQSslError(currentError.code,
593 peerCertificateChain.value(currentError.depth)));
594 if (q->state() != QAbstractSocket::ConnectedState)
595 break;
596 }
597 }
598
599 errorList << lastErrors;
600
601 // Connection aborted during handshake phase.
602 if (q->state() != QAbstractSocket::ConnectedState)
603 return false;
604
605 // Check if we're encrypted or not.
606 if (result <= 0) {
607 switch (q_SSL_get_error(ssl, result)) {
608 case SSL_ERROR_WANT_READ:
609 case SSL_ERROR_WANT_WRITE:
610 // The handshake is not yet complete.
611 break;
612 default:
613 QString errorString = QTlsBackendOpenSSL::msgErrorsDuringHandshake();
614#ifdef QSSLSOCKET_DEBUG
615 qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::startHandshake: error!" << errorString;
616#endif
617 {
618 const ScopedBool bg(inSetAndEmitError, true);
619 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, errorString);
620 if (pendingFatalAlert) {
622 pendingFatalAlert = false;
623 }
624 }
625 q->abort();
626 }
627 return false;
628 }
629
630 // store peer certificate chain
632
633 // Start translating errors.
634 QList<QSslError> errors;
635
636 // Note, the storePeerCerificates() probably updated the configuration at this point.
637 configuration = q->sslConfiguration();
638 // Check the whole chain for blacklisting (including root, as we check for subjectInfo and issuer)
639 const auto &peerCertificateChain = configuration.peerCertificateChain();
640 for (const QSslCertificate &cert : peerCertificateChain) {
641 if (QSslCertificatePrivate::isBlacklisted(cert)) {
642 QSslError error(QSslError::CertificateBlacklisted, cert);
643 errors << error;
644 emit q->peerVerifyError(error);
645 if (q->state() != QAbstractSocket::ConnectedState)
646 return false;
647 }
648 }
649
650 const bool doVerifyPeer = configuration.peerVerifyMode() == QSslSocket::VerifyPeer
651 || (configuration.peerVerifyMode() == QSslSocket::AutoVerifyPeer
652 && mode == QSslSocket::SslClientMode);
653
654#if QT_CONFIG(ocsp)
655 // For now it's always QSslSocket::SslClientMode - initSslContext() will bail out early,
656 // if it's enabled in QSslSocket::SslServerMode. This can change.
657 if (!configuration.peerCertificate().isNull() && configuration.ocspStaplingEnabled() && doVerifyPeer) {
658 if (!checkOcspStatus()) {
659 if (ocspErrors.isEmpty()) {
660 {
661 const ScopedBool bg(inSetAndEmitError, true);
662 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, ocspErrorDescription);
663 }
664 q->abort();
665 return false;
666 }
667
668 for (const QSslError &error : std::as_const(ocspErrors)) {
669 errors << error;
670 emit q->peerVerifyError(error);
671 if (q->state() != QAbstractSocket::ConnectedState)
672 return false;
673 }
674 }
675 }
676#endif // ocsp
677
678 // Check the peer certificate itself. First try the subject's common name
679 // (CN) as a wildcard, then try all alternate subject name DNS entries the
680 // same way.
681 if (!configuration.peerCertificate().isNull()) {
682 // but only if we're a client connecting to a server
683 // if we're the server, don't check CN
684 const auto verificationPeerName = d->verificationName();
685 if (mode == QSslSocket::SslClientMode) {
686 QString peerName = (verificationPeerName.isEmpty () ? q->peerName() : verificationPeerName);
687
688 if (!isMatchingHostname(configuration.peerCertificate(), peerName)) {
689 // No matches in common names or alternate names.
690 QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate());
691 errors << error;
692 emit q->peerVerifyError(error);
693 if (q->state() != QAbstractSocket::ConnectedState)
694 return false;
695 }
696 }
697 } else {
698 // No peer certificate presented. Report as error if the socket
699 // expected one.
700 if (doVerifyPeer) {
701 QSslError error(QSslError::NoPeerCertificate);
702 errors << error;
703 emit q->peerVerifyError(error);
704 if (q->state() != QAbstractSocket::ConnectedState)
705 return false;
706 }
707 }
708
709 // Translate errors from the error list into QSslErrors.
710 errors.reserve(errors.size() + errorList.size());
711 for (const auto &error : std::as_const(errorList))
712 errors << X509CertificateOpenSSL::openSSLErrorToQSslError(error.code, peerCertificateChain.value(error.depth));
713
714 if (!errors.isEmpty()) {
715 sslErrors = errors;
716#ifdef Q_OS_WIN
717 const bool fetchEnabled = QSslSocketPrivate::rootCertOnDemandLoadingSupported()
718 && d->isRootsOnDemandAllowed();
719 // !fetchEnabled is a special case scenario, when we potentially have a missing
720 // intermediate certificate and a recoverable chain, but on demand cert loading
721 // was disabled by setCaCertificates call. For this scenario we check if "Authority
722 // Information Access" is present - wincrypt can deal with such certificates.
723 QSslCertificate certToFetch;
724 if (doVerifyPeer && !d->verifyErrorsHaveBeenIgnored())
725 certToFetch = findCertificateToFetch(sslErrors, !fetchEnabled);
726
727 //Skip this if not using system CAs, or if the SSL errors are configured in advance to be ignorable
728 if (!certToFetch.isNull()) {
729 fetchAuthorityInformation = !fetchEnabled;
730 //Windows desktop versions starting from vista ship with minimal set of roots and download on demand
731 //from the windows update server CA roots that are trusted by MS. It also can fetch a missing intermediate
732 //in case "Authority Information Access" extension is present.
733 //
734 //However, this is only transparent if using WinINET - we have to trigger it
735 //ourselves.
736 fetchCaRootForCert(certToFetch);
737 return false;
738 }
739#endif // Q_OS_WIN
740 if (!checkSslErrors())
741 return false;
742 // A slot, attached to sslErrors signal can call
743 // abort/close/disconnetFromHost/etc; no need to
744 // continue handshake then.
745 if (q->state() != QAbstractSocket::ConnectedState)
746 return false;
747 } else {
748 sslErrors.clear();
749 }
750
752 return true;
753}
754
756{
757 handshakeInterrupted = false;
758}
759
761{
762 fetchAuthorityInformation = false;
763 caToFetch.reset();
764}
765
767{
768 if (d->configuration.keyingMaterial.isEmpty())
769 return;
770
771 for (auto &entry : d->configuration.keyingMaterial) {
772 if (!entry.isValid()) {
773#ifdef QSSLSOCKET_DEBUG
774 qCDebug(lcTlsBackend) << "keying material request is invalid:" << entry;
775#endif
776 continue;
777 }
778
779 /*
780 * https://docs.openssl.org/1.1.1/man3/SSL_export_keying_material/
781 * Note that in TLSv1.2 and below a zero length context is treated
782 * differently from no context at all, and will result in different
783 * keying material being returned. In TLSv1.3 a zero length context
784 * is that same as no context at all and will result in the same
785 * keying material being returned.
786 */
787 const auto context = entry.context();
788 const auto label = entry.label();
789 if (QByteArray output(entry.requestedSize(), Qt::Uninitialized);
790 q_SSL_export_keying_material(ssl,
791 reinterpret_cast<unsigned char*>(output.data_ptr().data()),
792 entry.requestedSize(),
793 label.data(),
794 label.size(),
795 reinterpret_cast<const unsigned char*>(context.data()),
796 context.size(),
797 context.isNull() ? 0 : 1) > 0)
798 {
799 entry.m_value = std::move(output);
800#ifdef QSSLSOCKET_DEBUG
801 } else {
802 qCDebug(lcTlsBackend) << "cannot export keying material:" << entry;
803#endif
804 }
805 }
806}
807
809{
810 Q_ASSERT(q);
811 Q_ASSERT(d);
812
813 auto *plainSocket = d->plainTcpSocket();
814 Q_ASSERT(plainSocket);
815
816 const auto mode = d->tlsMode();
817
818 // if we have a max read buffer size, reset the plain socket's to match
819 if (const auto maxSize = d->maxReadBufferSize())
820 plainSocket->setReadBufferSize(maxSize);
821
822 if (q_SSL_session_reused(ssl))
823 QTlsBackend::setPeerSessionShared(d, true);
824
825#ifdef QT_DECRYPT_SSL_TRAFFIC
826 if (q_SSL_get_session(ssl)) {
827 size_t master_key_len = q_SSL_SESSION_get_master_key(q_SSL_get_session(ssl), nullptr, 0);
828 size_t client_random_len = q_SSL_get_client_random(ssl, nullptr, 0);
829 QByteArray masterKey(int(master_key_len), Qt::Uninitialized); // Will not overflow
830 QByteArray clientRandom(int(client_random_len), Qt::Uninitialized); // Will not overflow
831
832 q_SSL_SESSION_get_master_key(q_SSL_get_session(ssl),
833 reinterpret_cast<unsigned char*>(masterKey.data()),
834 masterKey.size());
835 q_SSL_get_client_random(ssl, reinterpret_cast<unsigned char *>(clientRandom.data()),
836 clientRandom.size());
837
838 QByteArray debugLineClientRandom("CLIENT_RANDOM ");
839 debugLineClientRandom.append(clientRandom.toHex().toUpper());
840 debugLineClientRandom.append(" ");
841 debugLineClientRandom.append(masterKey.toHex().toUpper());
842 debugLineClientRandom.append("\n");
843
844 QString sslKeyFile = QDir::tempPath() + "/qt-ssl-keys"_L1;
845 QFile file(sslKeyFile);
846 if (!file.open(QIODevice::Append))
847 qCWarning(lcTlsBackend) << "could not open file" << sslKeyFile << "for appending";
848 if (!file.write(debugLineClientRandom))
849 qCWarning(lcTlsBackend) << "could not write to file" << sslKeyFile;
850 file.close();
851 } else {
852 qCWarning(lcTlsBackend, "could not decrypt SSL traffic");
853 }
854#endif // QT_DECRYPT_SSL_TRAFFIC
855
856 const auto &configuration = q->sslConfiguration();
857 // Cache this SSL session inside the QSslContext
858 if (!(configuration.testSslOption(QSsl::SslOptionDisableSessionSharing))) {
859 if (!sslContextPointer->cacheSession(ssl)) {
860 sslContextPointer.reset(); // we could not cache the session
861 } else {
862 // Cache the session for permanent usage as well
863 if (!(configuration.testSslOption(QSsl::SslOptionDisableSessionPersistence))) {
864 if (!sslContextPointer->sessionASN1().isEmpty())
865 QTlsBackend::setSessionAsn1(d, sslContextPointer->sessionASN1());
866 QTlsBackend::setSessionLifetimeHint(d, sslContextPointer->sessionTicketLifeTimeHint());
867 }
868 }
869 }
870
871#if !defined(OPENSSL_NO_NEXTPROTONEG)
872
873 QTlsBackend::setAlpnStatus(d, sslContextPointer->npnContext().status);
874 if (sslContextPointer->npnContext().status == QSslConfiguration::NextProtocolNegotiationUnsupported) {
875 // we could not agree -> be conservative and use HTTP/1.1
876 // T.P.: I have to admit, this is a really strange notion of 'conservative',
877 // given the protocol-neutral nature of ALPN/NPN.
878 QTlsBackend::setNegotiatedProtocol(d, QByteArrayLiteral("http/1.1"));
879 } else {
880 const unsigned char *proto = nullptr;
881 unsigned int proto_len = 0;
882
883 q_SSL_get0_alpn_selected(ssl, &proto, &proto_len);
884 if (proto_len && mode == QSslSocket::SslClientMode) {
885 // Client does not have a callback that sets it ...
886 QTlsBackend::setAlpnStatus(d, QSslConfiguration::NextProtocolNegotiationNegotiated);
887 }
888
889 if (!proto_len) { // Test if NPN was more lucky ...
890 q_SSL_get0_next_proto_negotiated(ssl, &proto, &proto_len);
891 }
892
893 if (proto_len)
894 QTlsBackend::setNegotiatedProtocol(d, QByteArray(reinterpret_cast<const char *>(proto), proto_len));
895 else
896 QTlsBackend::setNegotiatedProtocol(d,{});
897 }
898#endif // !defined(OPENSSL_NO_NEXTPROTONEG)
899
900 if (mode == QSslSocket::SslClientMode) {
901 EVP_PKEY *key;
902 if (q_SSL_get_server_tmp_key(ssl, &key))
903 QTlsBackend::setEphemeralKey(d, QSslKey(key, QSsl::PublicKey));
904 }
905
906 d->setEncrypted(true);
907 emit q->encrypted();
908 if (d->isAutoStartingHandshake() && d->isPendingClose()) {
909 d->setPendingClose(false);
910 q->disconnectFromHost();
911 }
912}
913
915{
916 Q_ASSERT(q);
917 Q_ASSERT(d);
918
919 using ScopedBool = QScopedValueRollback<bool>;
920
921 if (inSetAndEmitError)
922 return;
923
924 // If we don't have any SSL context, don't bother transmitting.
925 if (!ssl)
926 return;
927
928 auto &writeBuffer = d->tlsWriteBuffer();
929 auto &buffer = d->tlsBuffer();
930 auto *plainSocket = d->plainTcpSocket();
931 Q_ASSERT(plainSocket);
932 bool &emittedBytesWritten = d->tlsEmittedBytesWritten();
933
934 bool transmitting;
935 do {
936 transmitting = false;
937
938 // If the connection is secure, we can transfer data from the write
939 // buffer (in plain text) to the write BIO through SSL_write.
940 if (q->isEncrypted() && !writeBuffer.isEmpty()) {
941 qint64 totalBytesWritten = 0;
942 int nextDataBlockSize;
943 while ((nextDataBlockSize = writeBuffer.nextDataBlockSize()) > 0) {
944 int writtenBytes = q_SSL_write(ssl, writeBuffer.readPointer(), nextDataBlockSize);
945 if (writtenBytes <= 0) {
946 int error = q_SSL_get_error(ssl, writtenBytes);
947 //write can result in a want_write_error - not an error - continue transmitting
948 if (error == SSL_ERROR_WANT_WRITE) {
949 transmitting = true;
950 break;
951 } else if (error == SSL_ERROR_WANT_READ) {
952 //write can result in a want_read error, possibly due to renegotiation - not an error - stop transmitting
953 transmitting = false;
954 break;
955 } else {
956 // ### Better error handling.
957 const ScopedBool bg(inSetAndEmitError, true);
958 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
959 QSslSocket::tr("Unable to write data: %1").arg(
960 QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
961 return;
962 }
963 }
964#ifdef QSSLSOCKET_DEBUG
965 qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: encrypted" << writtenBytes << "bytes";
966#endif
967 writeBuffer.free(writtenBytes);
968 totalBytesWritten += writtenBytes;
969
970 if (writtenBytes < nextDataBlockSize) {
971 // break out of the writing loop and try again after we had read
972 transmitting = true;
973 break;
974 }
975 }
976
977 if (totalBytesWritten > 0) {
978 // Don't emit bytesWritten() recursively.
979 if (!emittedBytesWritten) {
980 emittedBytesWritten = true;
981 emit q->bytesWritten(totalBytesWritten);
982 emittedBytesWritten = false;
983 }
984 emit q->channelBytesWritten(0, totalBytesWritten);
985 }
986 }
987
988 // Check if we've got any data to be written to the socket.
989 QVarLengthArray<char, 4096> data;
990 int pendingBytes;
991 while (plainSocket->isValid() && (pendingBytes = q_BIO_pending(writeBio)) > 0
992 && plainSocket->openMode() != QIODevice::NotOpen) {
993 // Read encrypted data from the write BIO into a buffer.
994 data.resize(pendingBytes);
995 int encryptedBytesRead = q_BIO_read(writeBio, data.data(), pendingBytes);
996
997 // Write encrypted data from the buffer to the socket.
998 qint64 actualWritten = plainSocket->write(data.constData(), encryptedBytesRead);
999#ifdef QSSLSOCKET_DEBUG
1000 qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: wrote" << encryptedBytesRead
1001 << "encrypted bytes to the socket" << actualWritten << "actual.";
1002#endif
1003 if (actualWritten < 0) {
1004 //plain socket write fails if it was in the pending close state.
1005 const ScopedBool bg(inSetAndEmitError, true);
1006 setErrorAndEmit(d, plainSocket->error(), plainSocket->errorString());
1007 return;
1008 }
1009 transmitting = true;
1010 }
1011
1012 // Check if we've got any data to be read from the socket.
1013 if (!q->isEncrypted() || !d->maxReadBufferSize() || buffer.size() < d->maxReadBufferSize())
1014 while ((pendingBytes = plainSocket->bytesAvailable()) > 0) {
1015 // Read encrypted data from the socket into a buffer.
1016 data.resize(pendingBytes);
1017 // just peek() here because q_BIO_write could write less data than expected
1018 int encryptedBytesRead = plainSocket->peek(data.data(), pendingBytes);
1019
1020#ifdef QSSLSOCKET_DEBUG
1021 qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: read" << encryptedBytesRead << "encrypted bytes from the socket";
1022#endif
1023 // Write encrypted data from the buffer into the read BIO.
1024 int writtenToBio = q_BIO_write(readBio, data.constData(), encryptedBytesRead);
1025
1026 // Throw away the results.
1027 if (writtenToBio > 0) {
1028 plainSocket->skip(writtenToBio);
1029 } else {
1030 // ### Better error handling.
1031 const ScopedBool bg(inSetAndEmitError, true);
1032 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1033 QSslSocket::tr("Unable to decrypt data: %1")
1034 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1035 return;
1036 }
1037
1038 transmitting = true;
1039 }
1040
1041 // If the connection isn't secured yet, this is the time to retry the
1042 // connect / accept.
1043 if (!q->isEncrypted()) {
1044#ifdef QSSLSOCKET_DEBUG
1045 qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: testing encryption";
1046#endif
1047 if (startHandshake()) {
1048#ifdef QSSLSOCKET_DEBUG
1049 qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: encryption established";
1050#endif
1051 d->setEncrypted(true);
1052 transmitting = true;
1053 } else if (plainSocket->state() != QAbstractSocket::ConnectedState) {
1054#ifdef QSSLSOCKET_DEBUG
1055 qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: connection lost";
1056#endif
1057 break;
1058 } else if (d->isPaused()) {
1059 // just wait until the user continues
1060 return;
1061 } else {
1062#ifdef QSSLSOCKET_DEBUG
1063 qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: encryption not done yet";
1064#endif
1065 }
1066 }
1067
1068 // If the request is small and the remote host closes the transmission
1069 // after sending, there's a chance that startHandshake() will already
1070 // have triggered a shutdown.
1071 if (!ssl)
1072 continue;
1073
1074 // We always read everything from the SSL decryption buffers, even if
1075 // we have a readBufferMaxSize. There's no point in leaving data there
1076 // just so that readBuffer.size() == readBufferMaxSize.
1077 int readBytes = 0;
1078 const int bytesToRead = 4096;
1079 do {
1080 if (q->readChannelCount() == 0) {
1081 // The read buffer is deallocated, don't try resize or write to it.
1082 break;
1083 }
1084 // Don't use SSL_pending(). It's very unreliable.
1085 inSslRead = true;
1086 readBytes = q_SSL_read(ssl, buffer.reserve(bytesToRead), bytesToRead);
1087 inSslRead = false;
1088 if (renegotiated) {
1089 renegotiated = false;
1090 X509 *x509 = q_SSL_get_peer_certificate(ssl);
1091 const auto peerCertificate =
1092 QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1093 // Fail the renegotiate if the certificate has changed, else: continue.
1094 if (peerCertificate != q->peerCertificate()) {
1095 const ScopedBool bg(inSetAndEmitError, true);
1096 setErrorAndEmit(
1097 d, QAbstractSocket::RemoteHostClosedError,
1098 QSslSocket::tr(
1099 "TLS certificate unexpectedly changed during renegotiation!"));
1100 q->abort();
1101 return;
1102 }
1103 }
1104 if (readBytes > 0) {
1105#ifdef QSSLSOCKET_DEBUG
1106 qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: decrypted" << readBytes << "bytes";
1107#endif
1108 buffer.chop(bytesToRead - readBytes);
1109
1110 if (bool *readyReadEmittedPointer = d->readyReadPointer())
1111 *readyReadEmittedPointer = true;
1112 emit q->readyRead();
1113 emit q->channelReadyRead(0);
1114 transmitting = true;
1115 continue;
1116 }
1117 buffer.chop(bytesToRead);
1118
1119 // Error.
1120 switch (q_SSL_get_error(ssl, readBytes)) {
1121 case SSL_ERROR_WANT_READ:
1122 case SSL_ERROR_WANT_WRITE:
1123 // Out of data.
1124 break;
1125 case SSL_ERROR_ZERO_RETURN:
1126 // The remote host closed the connection.
1127#ifdef QSSLSOCKET_DEBUG
1128 qCDebug(lcTlsBackend) << "TlsCryptographOpenSSL::transmit: remote disconnect";
1129#endif
1130 if (!shutdown) {
1131 // We haven't sent our close_notify yet: the remote closed first.
1132 shutdown = true; // make sure we do not send shutdown ourselves
1133 const ScopedBool bg(inSetAndEmitError, true);
1134 setErrorAndEmit(d, QAbstractSocket::RemoteHostClosedError,
1135 QSslSocket::tr("The TLS/SSL connection has been closed"));
1136 }
1137 // else: we sent close_notify first and are receiving the expected response;
1138 // not an error.
1139 return;
1140 case SSL_ERROR_SYSCALL: // some IO error
1141 case SSL_ERROR_SSL: // error in the SSL library
1142 // we do not know exactly what the error is, nor whether we can recover from it,
1143 // so just return to prevent an endless loop in the outer "while" statement
1144 systemOrSslErrorDetected = true;
1145 {
1146 const ScopedBool bg(inSetAndEmitError, true);
1147 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1148 QSslSocket::tr("Error while reading: %1")
1149 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1150 }
1151 return;
1152 default:
1153 // SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT: can only happen with a
1154 // BIO_s_connect() or BIO_s_accept(), which we do not call.
1155 // SSL_ERROR_WANT_X509_LOOKUP: can only happen with a
1156 // SSL_CTX_set_client_cert_cb(), which we do not call.
1157 // So this default case should never be triggered.
1158 {
1159 const ScopedBool bg(inSetAndEmitError, true);
1160 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1161 QSslSocket::tr("Error while reading: %1")
1162 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1163 }
1164 break;
1165 }
1166 } while (ssl && readBytes > 0);
1167 } while (ssl && transmitting);
1168}
1169
1171{
1172 if (ssl) {
1173 if (!shutdown && !q_SSL_in_init(ssl) && !systemOrSslErrorDetected) {
1174 if (q_SSL_shutdown(ssl) != 1) {
1175 // Some error may be queued, clear it.
1176 QTlsBackendOpenSSL::clearErrorQueue();
1177 }
1178 shutdown = true;
1179 transmit();
1180 }
1181 }
1182 Q_ASSERT(d);
1183 auto *plainSocket = d->plainTcpSocket();
1184 Q_ASSERT(plainSocket);
1185 plainSocket->disconnectFromHost();
1186}
1187
1189{
1190 Q_ASSERT(d);
1191 auto *plainSocket = d->plainTcpSocket();
1192 Q_ASSERT(plainSocket);
1193 d->setEncrypted(false);
1194
1195 if (plainSocket->bytesAvailable() <= 0) {
1196 destroySslContext();
1197 } else {
1198 // Move all bytes into the plain buffer.
1199 const qint64 tmpReadBufferMaxSize = d->maxReadBufferSize();
1200 // Reset temporarily, so the plain socket buffer is completely drained:
1201 d->setMaxReadBufferSize(0);
1202 transmit();
1203 d->setMaxReadBufferSize(tmpReadBufferMaxSize);
1204 }
1205 //if there is still buffered data in the plain socket, don't destroy the ssl context yet.
1206 //it will be destroyed when the socket is deleted.
1207}
1208
1210{
1211 if (!ssl)
1212 return {};
1213
1214 const SSL_CIPHER *sessionCipher = q_SSL_get_current_cipher(ssl);
1215 return sessionCipher ? QTlsBackendOpenSSL::qt_OpenSSL_cipher_to_QSslCipher(sessionCipher) : QSslCipher{};
1216}
1217
1219{
1220 if (!ssl)
1221 return QSsl::UnknownProtocol;
1222
1223 const int ver = q_SSL_version(ssl);
1224 switch (ver) {
1225QT_WARNING_PUSH
1226QT_WARNING_DISABLE_DEPRECATED
1227 case 0x301:
1228 return QSsl::TlsV1_0;
1229 case 0x302:
1230 return QSsl::TlsV1_1;
1231QT_WARNING_POP
1232 case 0x303:
1233 return QSsl::TlsV1_2;
1234 case 0x304:
1235 return QSsl::TlsV1_3;
1236 }
1237
1238 return QSsl::UnknownProtocol;
1239}
1240
1242{
1243 return ocspResponses;
1244}
1245
1247{
1248 Q_ASSERT(q);
1249 Q_ASSERT(d);
1250
1251 if (sslErrors.isEmpty())
1252 return true;
1253
1254 emit q->sslErrors(sslErrors);
1255
1256 const auto vfyMode = q->peerVerifyMode();
1257 const auto mode = d->tlsMode();
1258
1259 bool doVerifyPeer = vfyMode == QSslSocket::VerifyPeer || (vfyMode == QSslSocket::AutoVerifyPeer
1260 && mode == QSslSocket::SslClientMode);
1261 bool doEmitSslError = !d->verifyErrorsHaveBeenIgnored();
1262 // check whether we need to emit an SSL handshake error
1263 if (doVerifyPeer && doEmitSslError) {
1264 if (q->pauseMode() & QAbstractSocket::PauseOnSslErrors) {
1265 QSslSocketPrivate::pauseSocketNotifiers(q);
1266 d->setPaused(true);
1267 } else {
1268 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, sslErrors.constFirst().errorString());
1269 auto *plainSocket = d->plainTcpSocket();
1270 Q_ASSERT(plainSocket);
1271 plainSocket->disconnectFromHost();
1272 }
1273 return false;
1274 }
1275 return true;
1276}
1277
1279{
1280 // If we return 1, this means we own the session, but we don't.
1281 // 0 would tell OpenSSL to deref (but they still have it in the
1282 // internal cache).
1283 Q_ASSERT(connection);
1284
1285 Q_ASSERT(q);
1286 Q_ASSERT(d);
1287
1288 if (q->sslConfiguration().testSslOption(QSsl::SslOptionDisableSessionPersistence)) {
1289 // We silently ignore, do nothing, remove from cache.
1290 return 0;
1291 }
1292
1293 SSL_SESSION *currentSession = q_SSL_get_session(connection);
1294 if (!currentSession) {
1295 qCWarning(lcTlsBackend,
1296 "New session ticket callback, the session is invalid (nullptr)");
1297 return 0;
1298 }
1299
1300 if (q_SSL_version(connection) < 0x304) {
1301 // We only rely on this mechanics with TLS >= 1.3
1302 return 0;
1303 }
1304
1305#ifdef TLS1_3_VERSION
1306 if (!q_SSL_SESSION_is_resumable(currentSession)) {
1307 qCDebug(lcTlsBackend, "New session ticket, but the session is non-resumable");
1308 return 0;
1309 }
1310#endif // TLS1_3_VERSION
1311
1312 const int sessionSize = q_i2d_SSL_SESSION(currentSession, nullptr);
1313 if (sessionSize <= 0) {
1314 qCWarning(lcTlsBackend, "could not store persistent version of SSL session");
1315 return 0;
1316 }
1317
1318 // We have somewhat perverse naming, it's not a ticket, it's a session.
1319 QByteArray sessionTicket(sessionSize, 0);
1320 auto data = reinterpret_cast<unsigned char *>(sessionTicket.data());
1321 if (!q_i2d_SSL_SESSION(currentSession, &data)) {
1322 qCWarning(lcTlsBackend, "could not store persistent version of SSL session");
1323 return 0;
1324 }
1325
1326 QTlsBackend::setSessionAsn1(d, sessionTicket);
1327 QTlsBackend::setSessionLifetimeHint(d, q_SSL_SESSION_get_ticket_lifetime_hint(currentSession));
1328
1329 emit q->newSessionTicketReceived();
1330 return 0;
1331}
1332
1334{
1335 Q_ASSERT(q);
1336 Q_ASSERT(d);
1337
1338 const auto level = tlsAlertLevel(value);
1339 if (level == QSsl::AlertLevel::Fatal && !q->isEncrypted()) {
1340 // Note, this logic is handshake-time only:
1341 pendingFatalAlert = true;
1342 }
1343
1344 emit q->alertSent(level, tlsAlertType(value), tlsAlertDescription(value));
1345
1346}
1347
1349{
1350 Q_ASSERT(q);
1351
1352 emit q->alertReceived(tlsAlertLevel(value), tlsAlertType(value), tlsAlertDescription(value));
1353}
1354
1356{
1357 // Returns 0 to abort verification, 1 to continue despite error (as
1358 // OpenSSL expects from the verification callback).
1359 Q_ASSERT(q);
1360 Q_ASSERT(ctx);
1361
1362 using ScopedBool = QScopedValueRollback<bool>;
1363 // While we are not setting, we are emitting and in general -
1364 // we want to prevent accidental recursive startHandshake()
1365 // calls:
1366 const ScopedBool bg(inSetAndEmitError, true);
1367
1369 if (!x509) {
1370 qCWarning(lcTlsBackend, "Could not obtain the certificate (that failed to verify)");
1371 return 0;
1372 }
1373
1374 const QSslCertificate certificate = QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1375 const auto errorAndDepth = QTlsPrivate::X509CertificateOpenSSL::errorEntryFromStoreContext(ctx);
1376 const QSslError tlsError = QTlsPrivate::X509CertificateOpenSSL::openSSLErrorToQSslError(errorAndDepth.code, certificate);
1377
1378 errorsReportedFromCallback = true;
1379 handshakeInterrupted = true;
1380 emit q->handshakeInterruptedOnError(tlsError);
1381
1382 // Conveniently so, we also can access 'lastErrors' external data set
1383 // in startHandshake, we store it for the case an application later
1384 // wants to check errors (ignored or not):
1385 const auto offset = QTlsBackendOpenSSL::s_indexForSSLExtraData
1387 if (auto errorList = static_cast<QList<QSslErrorEntry> *>(q_SSL_get_ex_data(ssl, offset)))
1388 errorList->append(errorAndDepth);
1389
1390 // An application is expected to ignore this error (by calling ignoreSslErrors)
1391 // in its directly connected slot:
1392 return !handshakeInterrupted;
1393}
1394
1396{
1397 Q_ASSERT(pendingFatalAlert);
1398 Q_ASSERT(d);
1399
1400 auto *plainSocket = d->plainTcpSocket();
1401
1402 pendingFatalAlert = false;
1403 QVarLengthArray<char, 4096> data;
1404 int pendingBytes = 0;
1405 while (plainSocket->isValid() && (pendingBytes = q_BIO_pending(writeBio)) > 0
1406 && plainSocket->openMode() != QIODevice::NotOpen) {
1407 // Read encrypted data from the write BIO into a buffer.
1408 data.resize(pendingBytes);
1409 const int bioReadBytes = q_BIO_read(writeBio, data.data(), pendingBytes);
1410
1411 // Write encrypted data from the buffer to the socket.
1412 qint64 actualWritten = plainSocket->write(data.constData(), bioReadBytes);
1413 if (actualWritten < 0)
1414 return;
1415 plainSocket->flush();
1416 }
1417}
1418
1419bool TlsCryptographOpenSSL::initSslContext()
1420{
1421 Q_ASSERT(q);
1422 Q_ASSERT(d);
1423
1424 // If no external context was set (e.g. by QHttpNetworkConnection) we will
1425 // create a new one.
1426 const auto mode = d->tlsMode();
1427 const auto configuration = q->sslConfiguration();
1428 if (!sslContextPointer)
1429 sslContextPointer = QSslContext::sharedFromConfiguration(mode, configuration, d->isRootsOnDemandAllowed());
1430
1431 if (sslContextPointer->error() != QSslError::NoError) {
1432 setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError, sslContextPointer->errorString());
1433 sslContextPointer.reset();
1434 return false;
1435 }
1436
1437 // Create and initialize SSL session
1438 if (!(ssl = sslContextPointer->createSsl())) {
1439 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1440 QSslSocket::tr("Error creating SSL session, %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1441 return false;
1442 }
1443
1444 if (configuration.protocol() != QSsl::UnknownProtocol && mode == QSslSocket::SslClientMode) {
1445 const auto verificationPeerName = d->verificationName();
1446 // Set server hostname on TLS extension. RFC4366 section 3.1 requires it in ACE format.
1447 QString tlsHostName = verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName;
1448 if (tlsHostName.isEmpty())
1449 tlsHostName = d->tlsHostName();
1450 QByteArray ace = QUrl::toAce(tlsHostName);
1451 // only send the SNI header if the URL is valid and not an IP
1452 if (!ace.isEmpty()
1453 && !QHostAddress().setAddress(tlsHostName)
1454 && !(configuration.testSslOption(QSsl::SslOptionDisableServerNameIndication))) {
1455 // We don't send the trailing dot from the host header if present see
1456 // https://tools.ietf.org/html/rfc6066#section-3
1457 if (ace.endsWith('.'))
1458 ace.chop(1);
1459 if (!q_SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, ace.data()))
1460 qCWarning(lcTlsBackend, "could not set SSL_CTRL_SET_TLSEXT_HOSTNAME, Server Name Indication disabled");
1461 }
1462 }
1463
1464 // Clear the session.
1465 errorList.clear();
1466
1467 // Initialize memory BIOs for encryption and decryption.
1468 readBio = q_BIO_new(q_BIO_s_mem());
1469 writeBio = q_BIO_new(q_BIO_s_mem());
1470 if (!readBio || !writeBio) {
1471 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1472 QSslSocket::tr("Error creating SSL session: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1473 if (readBio)
1474 q_BIO_free(readBio);
1475 if (writeBio)
1476 q_BIO_free(writeBio);
1477 return false;
1478 }
1479
1480 // Assign the bios.
1481 q_SSL_set_bio(ssl, readBio, writeBio);
1482
1483 if (mode == QSslSocket::SslClientMode)
1485 else
1487
1488 q_SSL_set_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData, this);
1489
1490#ifndef OPENSSL_NO_PSK
1491 // Set the client callback for PSK
1492 if (mode == QSslSocket::SslClientMode)
1494 else if (mode == QSslSocket::SslServerMode)
1496
1497#if OPENSSL_VERSION_NUMBER >= 0x10101006L
1498 // Set the client callback for TLSv1.3 PSK
1499 if (mode == QSslSocket::SslClientMode
1500 && QSslSocket::sslLibraryBuildVersionNumber() >= 0x10101006L) {
1501 q_SSL_set_psk_use_session_callback(ssl, &q_ssl_psk_use_session_callback);
1502 }
1503#endif // openssl version >= 0x10101006L
1504
1505#endif // OPENSSL_NO_PSK
1506
1507#if QT_CONFIG(ocsp)
1508 if (configuration.ocspStaplingEnabled()) {
1509 if (mode == QSslSocket::SslServerMode) {
1510 setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError,
1511 QSslSocket::tr("Server-side QSslSocket does not support OCSP stapling"));
1512 return false;
1513 }
1514 if (q_SSL_set_tlsext_status_type(ssl, TLSEXT_STATUSTYPE_ocsp) != 1) {
1515 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1516 QSslSocket::tr("Failed to enable OCSP stapling"));
1517 return false;
1518 }
1519 }
1520
1521 ocspResponseDer.clear();
1522 const auto backendConfig = configuration.backendConfiguration();
1523 auto responsePos = backendConfig.find("Qt-OCSP-response");
1524 if (responsePos != backendConfig.end()) {
1525 // This is our private, undocumented 'API' we use for the auto-testing of
1526 // OCSP-stapling. It must be a der-encoded OCSP response, presumably set
1527 // by tst_QOcsp.
1528 const QVariant data(responsePos.value());
1529 if (data.canConvert<QByteArray>())
1530 ocspResponseDer = data.toByteArray();
1531 }
1532
1533 if (ocspResponseDer.size()) {
1534 if (mode != QSslSocket::SslServerMode) {
1535 setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError,
1536 QSslSocket::tr("Client-side sockets do not send OCSP responses"));
1537 return false;
1538 }
1539 }
1540#endif // ocsp
1541
1542 return true;
1543}
1544
1545void TlsCryptographOpenSSL::destroySslContext()
1546{
1547 if (ssl) {
1548 if (!q_SSL_in_init(ssl) && !systemOrSslErrorDetected) {
1549 // We do not send a shutdown alert here. Just mark the session as
1550 // resumable for qhttpnetworkconnection's "optimization", otherwise
1551 // OpenSSL won't start a session resumption.
1552 if (q_SSL_shutdown(ssl) != 1) {
1553 // Some error may be queued, clear it.
1554 const auto errors = QTlsBackendOpenSSL::getErrorsFromOpenSsl();
1555 Q_UNUSED(errors);
1556 }
1557 }
1558 q_SSL_free(ssl);
1559 ssl = nullptr;
1560 }
1561 sslContextPointer.reset();
1562}
1563
1565{
1566 Q_ASSERT(d);
1567
1568 // Store the peer certificate and chain. For clients, the peer certificate
1569 // chain includes the peer certificate; for servers, it doesn't. Both the
1570 // peer certificate and the chain may be empty if the peer didn't present
1571 // any certificate.
1572 X509 *x509 = q_SSL_get_peer_certificate(ssl);
1573
1574 const auto peerCertificate = QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1575 QTlsBackend::storePeerCertificate(d, peerCertificate);
1576 q_X509_free(x509);
1577 auto peerCertificateChain = q->peerCertificateChain();
1578 if (peerCertificateChain.isEmpty()) {
1579 peerCertificateChain = QTlsPrivate::X509CertificateOpenSSL::stackOfX509ToQSslCertificates(q_SSL_get_peer_cert_chain(ssl));
1580 if (!peerCertificate.isNull() && d->tlsMode() == QSslSocket::SslServerMode)
1581 peerCertificateChain.prepend(peerCertificate);
1582 QTlsBackend::storePeerCertificateChain(d, peerCertificateChain);
1583 }
1584}
1585
1586#if QT_CONFIG(ocsp)
1587
1589{
1590 Q_ASSERT(ssl);
1591 Q_ASSERT(d);
1592
1593 const auto &configuration = q->sslConfiguration();
1594 Q_ASSERT(d->tlsMode() == QSslSocket::SslClientMode); // See initSslContext() for SslServerMode
1596
1597 const auto clearErrorQueue = qScopeGuard([] {
1599 });
1600
1603 ocspErrors.clear();
1604
1605 const unsigned char *responseData = nullptr;
1607 if (responseLength <= 0 || !responseData) {
1609 return false;
1610 }
1611
1613 if (!response) {
1614 // Treat this as a fatal SslHandshakeError.
1615 ocspErrorDescription = QSslSocket::tr("Failed to decode OCSP response");
1616 return false;
1617 }
1619
1622 // It's not a definitive response, it's an error message (not signed by the responder).
1624 return false;
1625 }
1626
1628 if (!basicResponse) {
1629 // SslHandshakeError.
1630 ocspErrorDescription = QSslSocket::tr("Failed to extract basic OCSP response");
1631 return false;
1632 }
1634
1635 SSL_CTX *ctx = q_SSL_get_SSL_CTX(ssl); // Does not increment refcount.
1636 Q_ASSERT(ctx);
1637 X509_STORE *store = q_SSL_CTX_get_cert_store(ctx); // Does not increment refcount.
1638 if (!store) {
1639 // SslHandshakeError.
1640 ocspErrorDescription = QSslSocket::tr("No certificate verification store, cannot verify OCSP response");
1641 return false;
1642 }
1643
1644 STACK_OF(X509) *peerChain = q_SSL_get_peer_cert_chain(ssl); // Does not increment refcount.
1648 // OCSP_basic_verify with 0 as verificationFlags:
1649 //
1650 // 0) Tries to find the OCSP responder's certificate in either peerChain
1651 // or basicResponse->certs. If not found, verification fails.
1652 // 1) It checks the signature using the responder's public key.
1653 // 2) Then it tries to validate the responder's cert (building a chain
1654 // etc.)
1655 // 3) It checks CertID in response.
1656 // 4) Ensures the responder is authorized to sign the status respond.
1657 //
1658 // Note, OpenSSL prior to 1.0.2b would only use bs->certs to
1659 // verify the responder's chain (see their commit 4ba9a4265bd).
1660 // Working this around - is too much fuss for ancient versions we
1661 // are dropping quite soon anyway.
1662 const unsigned long verificationFlags = 0;
1664 if (success <= 0)
1666
1667 if (q_OCSP_resp_count(basicResponse) != 1) {
1669 return false;
1670 }
1671
1673 if (!singleResponse) {
1674 ocspErrors.clear();
1675 // A fatal problem -> SslHandshakeError.
1676 ocspErrorDescription = QSslSocket::tr("Failed to decode a SingleResponse from OCSP status response");
1677 return false;
1678 }
1679
1680 // Let's make sure the response is for the correct certificate - we
1681 // can re-create this CertID using our peer's certificate and its
1682 // issuer's public key.
1686 bool matchFound = false;
1690 } else {
1692 if (!certs) // Oh, what a cataclysm! Last try:
1694 if (certs) {
1695 // It could be the first certificate in 'certs' is our peer's
1696 // certificate. Since it was not captured by the 'self-signed' branch
1697 // above, the CertID will not match and we'll just iterate on to the
1698 // next certificate. So we start from 0, not 1.
1699 for (int i = 0, e = q_sk_X509_num(certs); i < e; ++i) {
1702 if (matchFound) {
1705 break;
1706 }
1707 matchFound = false;
1708 }
1709 }
1710 }
1711 }
1712
1713 if (!matchFound) {
1716 }
1717
1718 // Check if the response is valid time-wise:
1719 ASN1_GENERALIZEDTIME *revTime = nullptr;
1722 int reason;
1724 if (!thisUpdate) {
1725 // This is unexpected, treat as SslHandshakeError, OCSP_check_validity assumes this pointer
1726 // to be != nullptr.
1727 ocspErrors.clear();
1729 ocspErrorDescription = QSslSocket::tr("Failed to extract 'this update time' from the SingleResponse");
1730 return false;
1731 }
1732
1733 // OCSP_check_validity(this, next, nsec, maxsec) does this check:
1734 // this <= now <= next. They allow some freedom to account
1735 // for delays/time inaccuracy.
1736 // this > now + nsec ? -> NOT_YET_VALID
1737 // if maxsec >= 0:
1738 // now - maxsec > this ? -> TOO_OLD
1739 // now - nsec > next ? -> EXPIRED
1740 // next < this ? -> NEXT_BEFORE_THIS
1741 // OK.
1744
1745 // And finally, the status:
1746 switch (certStatus) {
1748 // This certificate was not found among the revoked ones.
1750 break;
1755 break;
1759 }
1760
1761 return !ocspErrors.size();
1762}
1763
1764#endif // QT_CONFIG(ocsp)
1765
1766
1767unsigned TlsCryptographOpenSSL::pskClientTlsCallback(const char *hint, char *identity,
1768 unsigned max_identity_len,
1769 unsigned char *psk, unsigned max_psk_len)
1770{
1771 Q_ASSERT(q);
1772
1773 QSslPreSharedKeyAuthenticator authenticator;
1774 // Fill in some read-only fields (for the user)
1775 const int hintLength = hint ? int(std::strlen(hint)) : 0;
1776 QTlsBackend::setupClientPskAuth(&authenticator, hint, hintLength, max_identity_len, max_psk_len);
1777 // Let the client provide the remaining bits...
1778 emit q->preSharedKeyAuthenticationRequired(&authenticator);
1779
1780 // No PSK set? Return now to make the handshake fail
1781 if (authenticator.preSharedKey().isEmpty())
1782 return 0;
1783
1784 // Copy data back into OpenSSL
1785 const int identityLength = qMin(authenticator.identity().size(), authenticator.maximumIdentityLength());
1786 std::memcpy(identity, authenticator.identity().constData(), identityLength);
1787 identity[identityLength] = 0;
1788
1789 const int pskLength = qMin(authenticator.preSharedKey().size(), authenticator.maximumPreSharedKeyLength());
1790 std::memcpy(psk, authenticator.preSharedKey().constData(), pskLength);
1791 return pskLength;
1792}
1793
1794unsigned TlsCryptographOpenSSL::pskServerTlsCallback(const char *identity, unsigned char *psk,
1795 unsigned max_psk_len)
1796{
1797 Q_ASSERT(q);
1798
1799 QSslPreSharedKeyAuthenticator authenticator;
1800
1801 // Fill in some read-only fields (for the user)
1802 QTlsBackend::setupServerPskAuth(&authenticator, identity, q->sslConfiguration().preSharedKeyIdentityHint(),
1803 max_psk_len);
1804 emit q->preSharedKeyAuthenticationRequired(&authenticator);
1805
1806 // No PSK set? Return now to make the handshake fail
1807 if (authenticator.preSharedKey().isEmpty())
1808 return 0;
1809
1810 // Copy data back into OpenSSL
1811 const int pskLength = qMin(authenticator.preSharedKey().size(), authenticator.maximumPreSharedKeyLength());
1812 std::memcpy(psk, authenticator.preSharedKey().constData(), pskLength);
1813 return pskLength;
1814}
1815
1817{
1818 return inSslRead;
1819}
1820
1822{
1823 this->renegotiated = renegotiated;
1824}
1825
1826#ifdef Q_OS_WIN
1827
1829{
1830 Q_ASSERT(d);
1831 Q_ASSERT(q);
1832
1833 //The root certificate is downloaded from windows update, which blocks for 15 seconds in the worst case
1834 //so the request is done in a worker thread.
1838
1839 //Remember we are fetching and what we are fetching:
1840 caToFetch = cert;
1841
1843 q->peerVerifyName());
1848 d->setPaused(true);
1849}
1850
1852{
1853 if (caToFetch != cert) {
1854 //Ooops, something from the previous connection attempt, ignore!
1855 return;
1856 }
1857
1858 Q_ASSERT(d);
1859 Q_ASSERT(q);
1860
1861 //Done, fetched already:
1862 caToFetch.reset();
1863
1868 }
1869
1872 //Add the new root cert to default cert list for use by future sockets
1876 }
1877 //Add the new root cert to this socket for future connections
1879 //Remove the broken chain ssl errors (as chain is verified by windows)
1880 for (int i=sslErrors.count() - 1; i >= 0; --i) {
1881 if (sslErrors.at(i).certificate() == cert) {
1882 switch (sslErrors.at(i).error()) {
1887 // error can be ignored if OS says the chain is trusted
1889 break;
1890 default:
1891 // error cannot be ignored
1892 break;
1893 }
1894 }
1895 }
1896 }
1897
1898 auto *plainSocket = d->plainTcpSocket();
1900 // Continue with remaining errors
1901 if (plainSocket)
1903 d->setPaused(false);
1904 if (checkSslErrors() && ssl) {
1907 if (!willClose)
1908 transmit();
1909 }
1910}
1911
1912#endif // Q_OS_WIN
1913
1914} // namespace QTlsPrivate
1915
1916QT_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)