10#include "qwindowscarootfetcher_p.h"
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>
18#include <QtNetwork/qsslpresharedkeyauthenticator.h>
19#include <QtNetwork/qsslkeyingmaterial.h>
21#include <QtCore/qscopedvaluerollback.h>
22#include <QtCore/qscopeguard.h>
29using namespace Qt::StringLiterals;
33QSsl::AlertLevel tlsAlertLevel(
int value)
35 using QSsl::AlertLevel;
40 switch (typeString[0]) {
42 return AlertLevel::Warning;
44 return AlertLevel::Fatal;
49 return AlertLevel::Unknown;
52QString tlsAlertDescription(
int value)
55 if (!description.size())
56 description =
"no description provided"_L1;
60QSsl::AlertType tlsAlertType(
int value)
66 return QSsl::AlertType(value & 0xff);
71QSslCertificate findCertificateToFetch(
const QList<QSslError> &tlsErrors,
bool checkAIA)
73 QSslCertificate certToFetch;
75 for (
const auto &tlsError : tlsErrors) {
76 switch (tlsError.error()) {
77 case QSslError::UnableToGetLocalIssuerCertificate:
78 case QSslError::SelfSignedCertificateInChain:
79 certToFetch = tlsError.certificate();
81 case QSslError::SelfSignedCertificate:
82 case QSslError::CertificateBlacklisted:
84 return QSslCertificate{};
86#ifdef QSSLSOCKET_DEBUG
87 qCDebug(lcTlsBackend) << tlsError.errorString();
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")
104 return QSslCertificate{};
121 using ErrorListPtr = QList<QSslErrorEntry> *;
122 ErrorListPtr errors =
nullptr;
160 qCWarning(lcTlsBackend,
"Neither X509_STORE, nor SSL contains error list, handshake failure");
182 qCWarning(lcTlsBackend,
"Invalid store context (nullptr)");
194 qCWarning(lcTlsBackend,
"No external data (SSL) found in X509 store object");
202 qCWarning(lcTlsBackend,
"No external data (TlsCryptographOpenSSL) found in SSL object");
211#ifndef OPENSSL_NO_PSK
213 unsigned char *psk,
unsigned max_psk_len)
220 unsigned int max_psk_len)
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)
233 Q_UNUSED(max_identity_len);
235 Q_UNUSED(max_psk_len);
238 auto tls =
static_cast<TlsCryptographOpenSSL *>(q_SSL_get_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData));
241 Q_ASSERT(tls->d->tlsMode() == QSslSocket::SslClientMode);
248 if (qEnvironmentVariableIsSet(
"QT_USE_TLS_1_3_PSK"))
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)
265 auto *tls =
static_cast<TlsCryptographOpenSSL *>(q_SSL_get_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData));
268 Q_ASSERT(tls->d->tlsMode() == QSslSocket::SslClientMode);
277int q_ssl_sess_set_new_cb(SSL *ssl, SSL_SESSION *session)
280 qCWarning(lcTlsBackend,
"Invalid SSL (nullptr)");
284 qCWarning(lcTlsBackend,
"Invalid SSL_SESSION (nullptr)");
333#ifdef QSSLSOCKET_DEBUG
334 qCWarning(lcTlsBackend,
"Invalid 'connection' parameter (nullptr)");
344#ifdef QSSLSOCKET_DEBUG
345 qCWarning(lcTlsBackend,
"No external data (socket backend) found for parameter 'connection'");
353 if (from & SSL_CB_HANDSHAKE_DONE) {
359 if (!(from & SSL_CB_ALERT)) {
364 if (from & SSL_CB_WRITE)
493 ocspResponses.clear();
494 ocspResponseDer.clear();
496 systemOrSslErrorDetected =
false;
497 handshakeInterrupted =
false;
499 fetchAuthorityInformation =
false;
502 auto &sslCfg = d->configuration;
503 for (
auto &entry : sslCfg.keyingMaterial)
504 entry = entry.clone();
515 return sslContextPointer;
525 if (!initSslContext()) {
527 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
528 QSslSocket::tr(
"Unable to init SSL Context: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
540 if (!initSslContext()) {
542 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
543 QSslSocket::tr(
"Unable to init SSL Context: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
560 using ScopedBool = QScopedValueRollback<
bool>;
562 if (inSetAndEmitError)
565 const auto mode = d->tlsMode();
567 pendingFatalAlert =
false;
568 errorsReportedFromCallback =
false;
569 QList<QSslErrorEntry> lastErrors;
576 int result = (mode == QSslSocket::SslClientMode) ? q_SSL_connect(ssl) : q_SSL_accept(ssl);
583 if (!lastErrors.isEmpty() || errorsReportedFromCallback)
588 auto configuration = q->sslConfiguration();
589 if (!errorsReportedFromCallback) {
590 const auto &peerCertificateChain = configuration.peerCertificateChain();
591 for (
const auto ¤tError : std::as_const(lastErrors)) {
592 emit q->peerVerifyError(QTlsPrivate::X509CertificateOpenSSL::openSSLErrorToQSslError(currentError.code,
593 peerCertificateChain.value(currentError.depth)));
594 if (q->state() != QAbstractSocket::ConnectedState)
599 errorList << lastErrors;
602 if (q->state() != QAbstractSocket::ConnectedState)
608 case SSL_ERROR_WANT_READ:
609 case SSL_ERROR_WANT_WRITE:
613 QString errorString = QTlsBackendOpenSSL::msgErrorsDuringHandshake();
614#ifdef QSSLSOCKET_DEBUG
615 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::startHandshake: error!" << errorString;
618 const ScopedBool bg(inSetAndEmitError,
true);
619 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, errorString);
620 if (pendingFatalAlert) {
622 pendingFatalAlert =
false;
634 QList<QSslError> errors;
637 configuration = q->sslConfiguration();
639 const auto &peerCertificateChain = configuration.peerCertificateChain();
640 for (
const QSslCertificate &cert : peerCertificateChain) {
641 if (QSslCertificatePrivate::isBlacklisted(cert)) {
642 QSslError error(QSslError::CertificateBlacklisted, cert);
644 emit q->peerVerifyError(error);
645 if (q->state() != QAbstractSocket::ConnectedState)
650 const bool doVerifyPeer = configuration.peerVerifyMode() == QSslSocket::VerifyPeer
651 || (configuration.peerVerifyMode() == QSslSocket::AutoVerifyPeer
652 && mode == QSslSocket::SslClientMode);
657 if (!configuration.peerCertificate().isNull() && configuration.ocspStaplingEnabled() && doVerifyPeer) {
658 if (!checkOcspStatus()) {
659 if (ocspErrors.isEmpty()) {
661 const ScopedBool bg(inSetAndEmitError,
true);
662 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, ocspErrorDescription);
668 for (
const QSslError &error : std::as_const(ocspErrors)) {
670 emit q->peerVerifyError(error);
671 if (q->state() != QAbstractSocket::ConnectedState)
681 if (!configuration.peerCertificate().isNull()) {
684 const auto verificationPeerName = d->verificationName();
685 if (mode == QSslSocket::SslClientMode) {
686 QString peerName = (verificationPeerName.isEmpty () ? q->peerName() : verificationPeerName);
688 if (!isMatchingHostname(configuration.peerCertificate(), peerName)) {
690 QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate());
692 emit q->peerVerifyError(error);
693 if (q->state() != QAbstractSocket::ConnectedState)
701 QSslError error(QSslError::NoPeerCertificate);
703 emit q->peerVerifyError(error);
704 if (q->state() != QAbstractSocket::ConnectedState)
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));
714 if (!errors.isEmpty()) {
717 const bool fetchEnabled = QSslSocketPrivate::rootCertOnDemandLoadingSupported()
718 && d->isRootsOnDemandAllowed();
723 QSslCertificate certToFetch;
724 if (doVerifyPeer && !d->verifyErrorsHaveBeenIgnored())
725 certToFetch = findCertificateToFetch(sslErrors, !fetchEnabled);
728 if (!certToFetch.isNull()) {
729 fetchAuthorityInformation = !fetchEnabled;
736 fetchCaRootForCert(certToFetch);
745 if (q->state() != QAbstractSocket::ConnectedState)
757 handshakeInterrupted =
false;
762 fetchAuthorityInformation =
false;
768 if (d->configuration.keyingMaterial.isEmpty())
771 for (
auto &entry : d->configuration.keyingMaterial) {
772 if (!entry.isValid()) {
773#ifdef QSSLSOCKET_DEBUG
774 qCDebug(lcTlsBackend) <<
"keying material request is invalid:" << entry;
780
781
782
783
784
785
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(),
795 reinterpret_cast<
const unsigned char*>(context.data()),
797 context.isNull() ? 0 : 1) > 0)
799 entry.m_value = std::move(output);
800#ifdef QSSLSOCKET_DEBUG
802 qCDebug(lcTlsBackend) <<
"cannot export keying material:" << entry;
813 auto *plainSocket = d->plainTcpSocket();
814 Q_ASSERT(plainSocket);
816 const auto mode = d->tlsMode();
819 if (
const auto maxSize = d->maxReadBufferSize())
820 plainSocket->setReadBufferSize(maxSize);
822 if (q_SSL_session_reused(ssl))
823 QTlsBackend::setPeerSessionShared(d,
true);
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);
830 QByteArray clientRandom(
int(client_random_len), Qt::Uninitialized);
832 q_SSL_SESSION_get_master_key(q_SSL_get_session(ssl),
833 reinterpret_cast<
unsigned char*>(masterKey.data()),
835 q_SSL_get_client_random(ssl,
reinterpret_cast<
unsigned char *>(clientRandom.data()),
836 clientRandom.size());
838 QByteArray debugLineClientRandom(
"CLIENT_RANDOM ");
839 debugLineClientRandom.append(clientRandom.toHex().toUpper());
840 debugLineClientRandom.append(
" ");
841 debugLineClientRandom.append(masterKey.toHex().toUpper());
842 debugLineClientRandom.append(
"\n");
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;
852 qCWarning(lcTlsBackend,
"could not decrypt SSL traffic");
856 const auto &configuration = q->sslConfiguration();
858 if (!(configuration.testSslOption(QSsl::SslOptionDisableSessionSharing))) {
859 if (!sslContextPointer->cacheSession(ssl)) {
860 sslContextPointer.reset();
863 if (!(configuration.testSslOption(QSsl::SslOptionDisableSessionPersistence))) {
864 if (!sslContextPointer->sessionASN1().isEmpty())
865 QTlsBackend::setSessionAsn1(d, sslContextPointer->sessionASN1());
866 QTlsBackend::setSessionLifetimeHint(d, sslContextPointer->sessionTicketLifeTimeHint());
871#if !defined(OPENSSL_NO_NEXTPROTONEG)
873 QTlsBackend::setAlpnStatus(d, sslContextPointer->npnContext().status);
874 if (sslContextPointer->npnContext().status == QSslConfiguration::NextProtocolNegotiationUnsupported) {
878 QTlsBackend::setNegotiatedProtocol(d, QByteArrayLiteral(
"http/1.1"));
880 const unsigned char *proto =
nullptr;
881 unsigned int proto_len = 0;
884 if (proto_len && mode == QSslSocket::SslClientMode) {
886 QTlsBackend::setAlpnStatus(d, QSslConfiguration::NextProtocolNegotiationNegotiated);
894 QTlsBackend::setNegotiatedProtocol(d, QByteArray(
reinterpret_cast<
const char *>(proto), proto_len));
896 QTlsBackend::setNegotiatedProtocol(d,{});
900 if (mode == QSslSocket::SslClientMode) {
903 QTlsBackend::setEphemeralKey(d, QSslKey(key, QSsl::PublicKey));
906 d->setEncrypted(
true);
908 if (d->isAutoStartingHandshake() && d->isPendingClose()) {
909 d->setPendingClose(
false);
910 q->disconnectFromHost();
919 using ScopedBool = QScopedValueRollback<
bool>;
921 if (inSetAndEmitError)
928 auto &writeBuffer = d->tlsWriteBuffer();
929 auto &buffer = d->tlsBuffer();
930 auto *plainSocket = d->plainTcpSocket();
931 Q_ASSERT(plainSocket);
932 bool &emittedBytesWritten = d->tlsEmittedBytesWritten();
936 transmitting =
false;
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) {
948 if (error == SSL_ERROR_WANT_WRITE) {
951 }
else if (error == SSL_ERROR_WANT_READ) {
953 transmitting =
false;
957 const ScopedBool bg(inSetAndEmitError,
true);
958 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
959 QSslSocket::tr(
"Unable to write data: %1").arg(
960 QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
964#ifdef QSSLSOCKET_DEBUG
965 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: encrypted" << writtenBytes <<
"bytes";
967 writeBuffer.free(writtenBytes);
968 totalBytesWritten += writtenBytes;
970 if (writtenBytes < nextDataBlockSize) {
977 if (totalBytesWritten > 0) {
979 if (!emittedBytesWritten) {
980 emittedBytesWritten =
true;
981 emit q->bytesWritten(totalBytesWritten);
982 emittedBytesWritten =
false;
984 emit q->channelBytesWritten(0, totalBytesWritten);
989 QVarLengthArray<
char, 4096> data;
991 while (plainSocket->isValid() && (pendingBytes =
q_BIO_pending(writeBio)) > 0
992 && plainSocket->openMode() != QIODevice::NotOpen) {
994 data.resize(pendingBytes);
995 int encryptedBytesRead = q_BIO_read(writeBio, data.data(), pendingBytes);
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.";
1003 if (actualWritten < 0) {
1005 const ScopedBool bg(inSetAndEmitError,
true);
1006 setErrorAndEmit(d, plainSocket->error(), plainSocket->errorString());
1009 transmitting =
true;
1013 if (!q->isEncrypted() || !d->maxReadBufferSize() || buffer.size() < d->maxReadBufferSize())
1014 while ((pendingBytes = plainSocket->bytesAvailable()) > 0) {
1016 data.resize(pendingBytes);
1018 int encryptedBytesRead = plainSocket->peek(data.data(), pendingBytes);
1020#ifdef QSSLSOCKET_DEBUG
1021 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: read" << encryptedBytesRead <<
"encrypted bytes from the socket";
1024 int writtenToBio = q_BIO_write(readBio, data.constData(), encryptedBytesRead);
1027 if (writtenToBio > 0) {
1028 plainSocket->skip(writtenToBio);
1031 const ScopedBool bg(inSetAndEmitError,
true);
1032 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1033 QSslSocket::tr(
"Unable to decrypt data: %1")
1034 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1038 transmitting =
true;
1043 if (!q->isEncrypted()) {
1044#ifdef QSSLSOCKET_DEBUG
1045 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: testing encryption";
1048#ifdef QSSLSOCKET_DEBUG
1049 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: encryption established";
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";
1058 }
else if (d->isPaused()) {
1062#ifdef QSSLSOCKET_DEBUG
1063 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: encryption not done yet";
1078 const int bytesToRead = 4096;
1080 if (q->readChannelCount() == 0) {
1086 readBytes = q_SSL_read(ssl, buffer.reserve(bytesToRead), bytesToRead);
1089 renegotiated =
false;
1090 X509 *x509 = q_SSL_get_peer_certificate(ssl);
1091 const auto peerCertificate =
1092 QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1094 if (peerCertificate != q->peerCertificate()) {
1095 const ScopedBool bg(inSetAndEmitError,
true);
1097 d, QAbstractSocket::RemoteHostClosedError,
1099 "TLS certificate unexpectedly changed during renegotiation!"));
1104 if (readBytes > 0) {
1105#ifdef QSSLSOCKET_DEBUG
1106 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: decrypted" << readBytes <<
"bytes";
1108 buffer.chop(bytesToRead - readBytes);
1110 if (
bool *readyReadEmittedPointer = d->readyReadPointer())
1111 *readyReadEmittedPointer =
true;
1112 emit q->readyRead();
1113 emit q->channelReadyRead(0);
1114 transmitting =
true;
1117 buffer.chop(bytesToRead);
1121 case SSL_ERROR_WANT_READ:
1122 case SSL_ERROR_WANT_WRITE:
1125 case SSL_ERROR_ZERO_RETURN:
1127#ifdef QSSLSOCKET_DEBUG
1128 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: remote disconnect";
1133 const ScopedBool bg(inSetAndEmitError,
true);
1134 setErrorAndEmit(d, QAbstractSocket::RemoteHostClosedError,
1135 QSslSocket::tr(
"The TLS/SSL connection has been closed"));
1140 case SSL_ERROR_SYSCALL:
1144 systemOrSslErrorDetected =
true;
1146 const ScopedBool bg(inSetAndEmitError,
true);
1147 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1148 QSslSocket::tr(
"Error while reading: %1")
1149 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1159 const ScopedBool bg(inSetAndEmitError,
true);
1160 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1161 QSslSocket::tr(
"Error while reading: %1")
1162 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1166 }
while (ssl && readBytes > 0);
1167 }
while (ssl && transmitting);
1183 auto *plainSocket = d->plainTcpSocket();
1184 Q_ASSERT(plainSocket);
1185 plainSocket->disconnectFromHost();
1191 auto *plainSocket = d->plainTcpSocket();
1192 Q_ASSERT(plainSocket);
1193 d->setEncrypted(
false);
1195 if (plainSocket->bytesAvailable() <= 0) {
1196 destroySslContext();
1199 const qint64 tmpReadBufferMaxSize = d->maxReadBufferSize();
1201 d->setMaxReadBufferSize(0);
1203 d->setMaxReadBufferSize(tmpReadBufferMaxSize);
1215 return sessionCipher ? QTlsBackendOpenSSL::qt_OpenSSL_cipher_to_QSslCipher(sessionCipher) : QSslCipher{};
1221 return QSsl::UnknownProtocol;
1226QT_WARNING_DISABLE_DEPRECATED
1228 return QSsl::TlsV1_0;
1230 return QSsl::TlsV1_1;
1233 return QSsl::TlsV1_2;
1235 return QSsl::TlsV1_3;
1238 return QSsl::UnknownProtocol;
1243 return ocspResponses;
1251 if (sslErrors.isEmpty())
1254 emit q->sslErrors(sslErrors);
1256 const auto vfyMode = q->peerVerifyMode();
1257 const auto mode = d->tlsMode();
1259 bool doVerifyPeer = vfyMode == QSslSocket::VerifyPeer || (vfyMode == QSslSocket::AutoVerifyPeer
1260 && mode == QSslSocket::SslClientMode);
1261 bool doEmitSslError = !d->verifyErrorsHaveBeenIgnored();
1263 if (doVerifyPeer && doEmitSslError) {
1264 if (q->pauseMode() & QAbstractSocket::PauseOnSslErrors) {
1265 QSslSocketPrivate::pauseSocketNotifiers(q);
1268 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, sslErrors.constFirst().errorString());
1269 auto *plainSocket = d->plainTcpSocket();
1270 Q_ASSERT(plainSocket);
1271 plainSocket->disconnectFromHost();
1283 Q_ASSERT(connection);
1288 if (q->sslConfiguration().testSslOption(QSsl::SslOptionDisableSessionPersistence)) {
1294 if (!currentSession) {
1295 qCWarning(lcTlsBackend,
1296 "New session ticket callback, the session is invalid (nullptr)");
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");
1313 if (sessionSize <= 0) {
1314 qCWarning(lcTlsBackend,
"could not store persistent version of SSL 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");
1326 QTlsBackend::setSessionAsn1(d, sessionTicket);
1327 QTlsBackend::setSessionLifetimeHint(d, q_SSL_SESSION_get_ticket_lifetime_hint(currentSession));
1329 emit q->newSessionTicketReceived();
1338 const auto level = tlsAlertLevel(value);
1339 if (level == QSsl::AlertLevel::Fatal && !q->isEncrypted()) {
1341 pendingFatalAlert =
true;
1344 emit q->alertSent(level, tlsAlertType(value), tlsAlertDescription(value));
1352 emit q->alertReceived(tlsAlertLevel(value), tlsAlertType(value), tlsAlertDescription(value));
1362 using ScopedBool = QScopedValueRollback<
bool>;
1366 const ScopedBool bg(inSetAndEmitError,
true);
1370 qCWarning(lcTlsBackend,
"Could not obtain the certificate (that failed to verify)");
1374 const QSslCertificate certificate = QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1376 const QSslError tlsError = QTlsPrivate::X509CertificateOpenSSL::openSSLErrorToQSslError(errorAndDepth.code, certificate);
1378 errorsReportedFromCallback =
true;
1379 handshakeInterrupted =
true;
1380 emit q->handshakeInterruptedOnError(tlsError);
1388 errorList->append(errorAndDepth);
1392 return !handshakeInterrupted;
1397 Q_ASSERT(pendingFatalAlert);
1400 auto *plainSocket = d->plainTcpSocket();
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) {
1408 data.resize(pendingBytes);
1409 const int bioReadBytes = q_BIO_read(writeBio, data.data(), pendingBytes);
1412 qint64 actualWritten = plainSocket->write(data.constData(), bioReadBytes);
1413 if (actualWritten < 0)
1415 plainSocket->flush();
1426 const auto mode = d->tlsMode();
1427 const auto configuration = q->sslConfiguration();
1428 if (!sslContextPointer)
1429 sslContextPointer = QSslContext::sharedFromConfiguration(mode, configuration, d->isRootsOnDemandAllowed());
1431 if (sslContextPointer->error() != QSslError::NoError) {
1432 setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError, sslContextPointer->errorString());
1433 sslContextPointer.reset();
1438 if (!(ssl = sslContextPointer->createSsl())) {
1439 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1440 QSslSocket::tr(
"Error creating SSL session, %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1444 if (configuration.protocol() != QSsl::UnknownProtocol && mode == QSslSocket::SslClientMode) {
1445 const auto verificationPeerName = d->verificationName();
1447 QString tlsHostName = verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName;
1448 if (tlsHostName.isEmpty())
1449 tlsHostName = d->tlsHostName();
1450 QByteArray ace = QUrl::toAce(tlsHostName);
1453 && !QHostAddress().setAddress(tlsHostName)
1454 && !(configuration.testSslOption(QSsl::SslOptionDisableServerNameIndication))) {
1457 if (ace.endsWith(
'.'))
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");
1470 if (!readBio || !writeBio) {
1471 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1472 QSslSocket::tr(
"Error creating SSL session: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1483 if (mode == QSslSocket::SslClientMode)
1490#ifndef OPENSSL_NO_PSK
1492 if (mode == QSslSocket::SslClientMode)
1494 else if (mode == QSslSocket::SslServerMode)
1497#if OPENSSL_VERSION_NUMBER
>= 0x10101006L
1499 if (mode == QSslSocket::SslClientMode
1500 && QSslSocket::sslLibraryBuildVersionNumber() >= 0x10101006L) {
1501 q_SSL_set_psk_use_session_callback(ssl, &q_ssl_psk_use_session_callback);
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"));
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"));
1521 ocspResponseDer.clear();
1522 const auto backendConfig = configuration.backendConfiguration();
1523 auto responsePos = backendConfig.find(
"Qt-OCSP-response");
1524 if (responsePos != backendConfig.end()) {
1528 const QVariant data(responsePos.value());
1529 if (data.canConvert<QByteArray>())
1530 ocspResponseDer = data.toByteArray();
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"));
1554 const auto errors = QTlsBackendOpenSSL::getErrorsFromOpenSsl();
1561 sslContextPointer.reset();
1572 X509 *x509 = q_SSL_get_peer_certificate(ssl);
1574 const auto peerCertificate = QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1575 QTlsBackend::storePeerCertificate(d, peerCertificate);
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);
1768 unsigned max_identity_len,
1769 unsigned char *psk,
unsigned max_psk_len)
1773 QSslPreSharedKeyAuthenticator authenticator;
1775 const int hintLength = hint ?
int(std::strlen(hint)) : 0;
1776 QTlsBackend::setupClientPskAuth(&authenticator, hint, hintLength, max_identity_len, max_psk_len);
1778 emit q->preSharedKeyAuthenticationRequired(&authenticator);
1781 if (authenticator.preSharedKey().isEmpty())
1785 const int identityLength = qMin(authenticator.identity().size(), authenticator.maximumIdentityLength());
1786 std::memcpy(identity, authenticator.identity().constData(), identityLength);
1787 identity[identityLength] = 0;
1789 const int pskLength = qMin(authenticator.preSharedKey().size(), authenticator.maximumPreSharedKeyLength());
1790 std::memcpy(psk, authenticator.preSharedKey().constData(), pskLength);
1795 unsigned max_psk_len)
1799 QSslPreSharedKeyAuthenticator authenticator;
1802 QTlsBackend::setupServerPskAuth(&authenticator, identity, q->sslConfiguration().preSharedKeyIdentityHint(),
1804 emit q->preSharedKeyAuthenticationRequired(&authenticator);
1807 if (authenticator.preSharedKey().isEmpty())
1811 const int pskLength = qMin(authenticator.preSharedKey().size(), authenticator.maximumPreSharedKeyLength());
1812 std::memcpy(psk, authenticator.preSharedKey().constData(), pskLength);
1823 this->renegotiated = renegotiated;
static void clearErrorQueue()
static int s_indexForSSLExtraData
unsigned pskClientTlsCallback(const char *hint, char *identity, unsigned max_identity_len, unsigned char *psk, unsigned max_psk_len)
void enableHandshakeContinuation() override
void alertMessageReceived(int encoded)
std::shared_ptr< QSslContext > sslContext() const override
int handleNewSessionTicket(SSL *connection)
QList< QOcspResponse > ocsps() const override
int emitErrorFromCallback(X509_STORE_CTX *ctx)
void disconnectFromHost() override
void alertMessageSent(int encoded)
void continueHandshake() override
unsigned pskServerTlsCallback(const char *identity, unsigned char *psk, unsigned max_psk_len)
void startClientEncryption() override
QSsl::SslProtocol sessionProtocol() const override
void init(QSslSocket *qObj, QSslSocketPrivate *dObj) override
void disconnected() override
void storePeerCertificates()
void cancelCAFetch() override
QList< QSslError > tlsErrors() const override
void startServerEncryption() override
void setRenegotiated(bool renegotiated)
void exportKeyingMaterial()
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_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)
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_SSL_set_ex_data(SSL *ssl, int idx, void *arg)