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'");
350 if (!(from & SSL_CB_ALERT)) {
355 if (from & SSL_CB_WRITE)
484 ocspResponses.clear();
485 ocspResponseDer.clear();
487 systemOrSslErrorDetected =
false;
488 handshakeInterrupted =
false;
490 fetchAuthorityInformation =
false;
502 return sslContextPointer;
512 if (!initSslContext()) {
514 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
515 QSslSocket::tr(
"Unable to init SSL Context: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
527 if (!initSslContext()) {
529 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
530 QSslSocket::tr(
"Unable to init SSL Context: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
547 using ScopedBool = QScopedValueRollback<
bool>;
549 if (inSetAndEmitError)
552 const auto mode = d->tlsMode();
554 pendingFatalAlert =
false;
555 errorsReportedFromCallback =
false;
556 QList<QSslErrorEntry> lastErrors;
563 int result = (mode == QSslSocket::SslClientMode) ? q_SSL_connect(ssl) : q_SSL_accept(ssl);
570 if (!lastErrors.isEmpty() || errorsReportedFromCallback)
575 auto configuration = q->sslConfiguration();
576 if (!errorsReportedFromCallback) {
577 const auto &peerCertificateChain = configuration.peerCertificateChain();
578 for (
const auto ¤tError : std::as_const(lastErrors)) {
579 emit q->peerVerifyError(QTlsPrivate::X509CertificateOpenSSL::openSSLErrorToQSslError(currentError.code,
580 peerCertificateChain.value(currentError.depth)));
581 if (q->state() != QAbstractSocket::ConnectedState)
586 errorList << lastErrors;
589 if (q->state() != QAbstractSocket::ConnectedState)
595 case SSL_ERROR_WANT_READ:
596 case SSL_ERROR_WANT_WRITE:
600 QString errorString = QTlsBackendOpenSSL::msgErrorsDuringHandshake();
601#ifdef QSSLSOCKET_DEBUG
602 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::startHandshake: error!" << errorString;
605 const ScopedBool bg(inSetAndEmitError,
true);
606 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, errorString);
607 if (pendingFatalAlert) {
609 pendingFatalAlert =
false;
621 QList<QSslError> errors;
624 configuration = q->sslConfiguration();
626 const auto &peerCertificateChain = configuration.peerCertificateChain();
627 for (
const QSslCertificate &cert : peerCertificateChain) {
628 if (QSslCertificatePrivate::isBlacklisted(cert)) {
629 QSslError error(QSslError::CertificateBlacklisted, cert);
631 emit q->peerVerifyError(error);
632 if (q->state() != QAbstractSocket::ConnectedState)
637 const bool doVerifyPeer = configuration.peerVerifyMode() == QSslSocket::VerifyPeer
638 || (configuration.peerVerifyMode() == QSslSocket::AutoVerifyPeer
639 && mode == QSslSocket::SslClientMode);
644 if (!configuration.peerCertificate().isNull() && configuration.ocspStaplingEnabled() && doVerifyPeer) {
645 if (!checkOcspStatus()) {
646 if (ocspErrors.isEmpty()) {
648 const ScopedBool bg(inSetAndEmitError,
true);
649 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, ocspErrorDescription);
655 for (
const QSslError &error : std::as_const(ocspErrors)) {
657 emit q->peerVerifyError(error);
658 if (q->state() != QAbstractSocket::ConnectedState)
668 if (!configuration.peerCertificate().isNull()) {
671 const auto verificationPeerName = d->verificationName();
672 if (mode == QSslSocket::SslClientMode) {
673 QString peerName = (verificationPeerName.isEmpty () ? q->peerName() : verificationPeerName);
675 if (!isMatchingHostname(configuration.peerCertificate(), peerName)) {
677 QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate());
679 emit q->peerVerifyError(error);
680 if (q->state() != QAbstractSocket::ConnectedState)
688 QSslError error(QSslError::NoPeerCertificate);
690 emit q->peerVerifyError(error);
691 if (q->state() != QAbstractSocket::ConnectedState)
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));
701 if (!errors.isEmpty()) {
704 const bool fetchEnabled = QSslSocketPrivate::rootCertOnDemandLoadingSupported()
705 && d->isRootsOnDemandAllowed();
710 QSslCertificate certToFetch;
711 if (doVerifyPeer && !d->verifyErrorsHaveBeenIgnored())
712 certToFetch = findCertificateToFetch(sslErrors, !fetchEnabled);
715 if (!certToFetch.isNull()) {
716 fetchAuthorityInformation = !fetchEnabled;
723 fetchCaRootForCert(certToFetch);
732 if (q->state() != QAbstractSocket::ConnectedState)
744 handshakeInterrupted =
false;
749 fetchAuthorityInformation =
false;
755 if (d->configuration.keyingMaterial.isEmpty())
757 auto sslCfg = q->sslConfiguration();
758 auto list = sslCfg.keyingMaterial();
760 for (
auto &entry : list) {
761 if (!entry.isValid()) {
762#ifdef QSSLSOCKET_DEBUG
763 qCDebug(lcTlsBackend) <<
"keying material request is invalid:" << entry;
769
770
771
772
773
774
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(),
784 reinterpret_cast<
const unsigned char*>(context.data()),
786 context.isNull() ? 0 : 1) > 0)
788 entry.m_value = std::move(output);
789#ifdef QSSLSOCKET_DEBUG
791 qCDebug(lcTlsBackend) <<
"cannot export keying material:" << entry;
796 sslCfg.setKeyingMaterial(list);
797 q->setSslConfiguration(sslCfg);
805 auto *plainSocket = d->plainTcpSocket();
806 Q_ASSERT(plainSocket);
808 const auto mode = d->tlsMode();
811 if (
const auto maxSize = d->maxReadBufferSize())
812 plainSocket->setReadBufferSize(maxSize);
814 if (q_SSL_session_reused(ssl))
815 QTlsBackend::setPeerSessionShared(d,
true);
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);
822 QByteArray clientRandom(
int(client_random_len), Qt::Uninitialized);
824 q_SSL_SESSION_get_master_key(q_SSL_get_session(ssl),
825 reinterpret_cast<
unsigned char*>(masterKey.data()),
827 q_SSL_get_client_random(ssl,
reinterpret_cast<
unsigned char *>(clientRandom.data()),
828 clientRandom.size());
830 QByteArray debugLineClientRandom(
"CLIENT_RANDOM ");
831 debugLineClientRandom.append(clientRandom.toHex().toUpper());
832 debugLineClientRandom.append(
" ");
833 debugLineClientRandom.append(masterKey.toHex().toUpper());
834 debugLineClientRandom.append(
"\n");
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;
844 qCWarning(lcTlsBackend,
"could not decrypt SSL traffic");
848 const auto &configuration = q->sslConfiguration();
850 if (!(configuration.testSslOption(QSsl::SslOptionDisableSessionSharing))) {
851 if (!sslContextPointer->cacheSession(ssl)) {
852 sslContextPointer.reset();
855 if (!(configuration.testSslOption(QSsl::SslOptionDisableSessionPersistence))) {
856 if (!sslContextPointer->sessionASN1().isEmpty())
857 QTlsBackend::setSessionAsn1(d, sslContextPointer->sessionASN1());
858 QTlsBackend::setSessionLifetimeHint(d, sslContextPointer->sessionTicketLifeTimeHint());
863#if !defined(OPENSSL_NO_NEXTPROTONEG)
865 QTlsBackend::setAlpnStatus(d, sslContextPointer->npnContext().status);
866 if (sslContextPointer->npnContext().status == QSslConfiguration::NextProtocolNegotiationUnsupported) {
870 QTlsBackend::setNegotiatedProtocol(d, QByteArrayLiteral(
"http/1.1"));
872 const unsigned char *proto =
nullptr;
873 unsigned int proto_len = 0;
876 if (proto_len && mode == QSslSocket::SslClientMode) {
878 QTlsBackend::setAlpnStatus(d, QSslConfiguration::NextProtocolNegotiationNegotiated);
886 QTlsBackend::setNegotiatedProtocol(d, QByteArray(
reinterpret_cast<
const char *>(proto), proto_len));
888 QTlsBackend::setNegotiatedProtocol(d,{});
892 if (mode == QSslSocket::SslClientMode) {
895 QTlsBackend::setEphemeralKey(d, QSslKey(key, QSsl::PublicKey));
900 d->setEncrypted(
true);
902 if (d->isAutoStartingHandshake() && d->isPendingClose()) {
903 d->setPendingClose(
false);
904 q->disconnectFromHost();
913 using ScopedBool = QScopedValueRollback<
bool>;
915 if (inSetAndEmitError)
922 auto &writeBuffer = d->tlsWriteBuffer();
923 auto &buffer = d->tlsBuffer();
924 auto *plainSocket = d->plainTcpSocket();
925 Q_ASSERT(plainSocket);
926 bool &emittedBytesWritten = d->tlsEmittedBytesWritten();
930 transmitting =
false;
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) {
942 if (error == SSL_ERROR_WANT_WRITE) {
945 }
else if (error == SSL_ERROR_WANT_READ) {
947 transmitting =
false;
951 const ScopedBool bg(inSetAndEmitError,
true);
952 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
953 QSslSocket::tr(
"Unable to write data: %1").arg(
954 QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
958#ifdef QSSLSOCKET_DEBUG
959 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: encrypted" << writtenBytes <<
"bytes";
961 writeBuffer.free(writtenBytes);
962 totalBytesWritten += writtenBytes;
964 if (writtenBytes < nextDataBlockSize) {
971 if (totalBytesWritten > 0) {
973 if (!emittedBytesWritten) {
974 emittedBytesWritten =
true;
975 emit q->bytesWritten(totalBytesWritten);
976 emittedBytesWritten =
false;
978 emit q->channelBytesWritten(0, totalBytesWritten);
983 QVarLengthArray<
char, 4096> data;
985 while (plainSocket->isValid() && (pendingBytes =
q_BIO_pending(writeBio)) > 0
986 && plainSocket->openMode() != QIODevice::NotOpen) {
988 data.resize(pendingBytes);
989 int encryptedBytesRead = q_BIO_read(writeBio, data.data(), pendingBytes);
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.";
997 if (actualWritten < 0) {
999 const ScopedBool bg(inSetAndEmitError,
true);
1000 setErrorAndEmit(d, plainSocket->error(), plainSocket->errorString());
1003 transmitting =
true;
1007 if (!q->isEncrypted() || !d->maxReadBufferSize() || buffer.size() < d->maxReadBufferSize())
1008 while ((pendingBytes = plainSocket->bytesAvailable()) > 0) {
1010 data.resize(pendingBytes);
1012 int encryptedBytesRead = plainSocket->peek(data.data(), pendingBytes);
1014#ifdef QSSLSOCKET_DEBUG
1015 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: read" << encryptedBytesRead <<
"encrypted bytes from the socket";
1018 int writtenToBio = q_BIO_write(readBio, data.constData(), encryptedBytesRead);
1021 if (writtenToBio > 0) {
1022 plainSocket->skip(writtenToBio);
1025 const ScopedBool bg(inSetAndEmitError,
true);
1026 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1027 QSslSocket::tr(
"Unable to decrypt data: %1")
1028 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1032 transmitting =
true;
1037 if (!q->isEncrypted()) {
1038#ifdef QSSLSOCKET_DEBUG
1039 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: testing encryption";
1042#ifdef QSSLSOCKET_DEBUG
1043 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: encryption established";
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";
1052 }
else if (d->isPaused()) {
1056#ifdef QSSLSOCKET_DEBUG
1057 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: encryption not done yet";
1072 const int bytesToRead = 4096;
1074 if (q->readChannelCount() == 0) {
1080 readBytes = q_SSL_read(ssl, buffer.reserve(bytesToRead), bytesToRead);
1083 renegotiated =
false;
1084 X509 *x509 = q_SSL_get_peer_certificate(ssl);
1085 const auto peerCertificate =
1086 QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1088 if (peerCertificate != q->peerCertificate()) {
1089 const ScopedBool bg(inSetAndEmitError,
true);
1091 d, QAbstractSocket::RemoteHostClosedError,
1093 "TLS certificate unexpectedly changed during renegotiation!"));
1098 if (readBytes > 0) {
1099#ifdef QSSLSOCKET_DEBUG
1100 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: decrypted" << readBytes <<
"bytes";
1102 buffer.chop(bytesToRead - readBytes);
1104 if (
bool *readyReadEmittedPointer = d->readyReadPointer())
1105 *readyReadEmittedPointer =
true;
1106 emit q->readyRead();
1107 emit q->channelReadyRead(0);
1108 transmitting =
true;
1111 buffer.chop(bytesToRead);
1115 case SSL_ERROR_WANT_READ:
1116 case SSL_ERROR_WANT_WRITE:
1119 case SSL_ERROR_ZERO_RETURN:
1121#ifdef QSSLSOCKET_DEBUG
1122 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: remote disconnect";
1127 const ScopedBool bg(inSetAndEmitError,
true);
1128 setErrorAndEmit(d, QAbstractSocket::RemoteHostClosedError,
1129 QSslSocket::tr(
"The TLS/SSL connection has been closed"));
1134 case SSL_ERROR_SYSCALL:
1138 systemOrSslErrorDetected =
true;
1140 const ScopedBool bg(inSetAndEmitError,
true);
1141 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1142 QSslSocket::tr(
"Error while reading: %1")
1143 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1153 const ScopedBool bg(inSetAndEmitError,
true);
1154 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1155 QSslSocket::tr(
"Error while reading: %1")
1156 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1160 }
while (ssl && readBytes > 0);
1161 }
while (ssl && transmitting);
1177 auto *plainSocket = d->plainTcpSocket();
1178 Q_ASSERT(plainSocket);
1179 plainSocket->disconnectFromHost();
1185 auto *plainSocket = d->plainTcpSocket();
1186 Q_ASSERT(plainSocket);
1187 d->setEncrypted(
false);
1189 if (plainSocket->bytesAvailable() <= 0) {
1190 destroySslContext();
1193 const qint64 tmpReadBufferMaxSize = d->maxReadBufferSize();
1195 d->setMaxReadBufferSize(0);
1197 d->setMaxReadBufferSize(tmpReadBufferMaxSize);
1209 return sessionCipher ? QTlsBackendOpenSSL::qt_OpenSSL_cipher_to_QSslCipher(sessionCipher) : QSslCipher{};
1215 return QSsl::UnknownProtocol;
1220QT_WARNING_DISABLE_DEPRECATED
1222 return QSsl::TlsV1_0;
1224 return QSsl::TlsV1_1;
1227 return QSsl::TlsV1_2;
1229 return QSsl::TlsV1_3;
1232 return QSsl::UnknownProtocol;
1237 return ocspResponses;
1245 if (sslErrors.isEmpty())
1248 emit q->sslErrors(sslErrors);
1250 const auto vfyMode = q->peerVerifyMode();
1251 const auto mode = d->tlsMode();
1253 bool doVerifyPeer = vfyMode == QSslSocket::VerifyPeer || (vfyMode == QSslSocket::AutoVerifyPeer
1254 && mode == QSslSocket::SslClientMode);
1255 bool doEmitSslError = !d->verifyErrorsHaveBeenIgnored();
1257 if (doVerifyPeer && doEmitSslError) {
1258 if (q->pauseMode() & QAbstractSocket::PauseOnSslErrors) {
1259 QSslSocketPrivate::pauseSocketNotifiers(q);
1262 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, sslErrors.constFirst().errorString());
1263 auto *plainSocket = d->plainTcpSocket();
1264 Q_ASSERT(plainSocket);
1265 plainSocket->disconnectFromHost();
1277 Q_ASSERT(connection);
1282 if (q->sslConfiguration().testSslOption(QSsl::SslOptionDisableSessionPersistence)) {
1288 if (!currentSession) {
1289 qCWarning(lcTlsBackend,
1290 "New session ticket callback, the session is invalid (nullptr)");
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");
1307 if (sessionSize <= 0) {
1308 qCWarning(lcTlsBackend,
"could not store persistent version of SSL 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");
1320 QTlsBackend::setSessionAsn1(d, sessionTicket);
1321 QTlsBackend::setSessionLifetimeHint(d, q_SSL_SESSION_get_ticket_lifetime_hint(currentSession));
1323 emit q->newSessionTicketReceived();
1332 const auto level = tlsAlertLevel(value);
1333 if (level == QSsl::AlertLevel::Fatal && !q->isEncrypted()) {
1335 pendingFatalAlert =
true;
1338 emit q->alertSent(level, tlsAlertType(value), tlsAlertDescription(value));
1346 emit q->alertReceived(tlsAlertLevel(value), tlsAlertType(value), tlsAlertDescription(value));
1356 using ScopedBool = QScopedValueRollback<
bool>;
1360 const ScopedBool bg(inSetAndEmitError,
true);
1364 qCWarning(lcTlsBackend,
"Could not obtain the certificate (that failed to verify)");
1368 const QSslCertificate certificate = QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1370 const QSslError tlsError = QTlsPrivate::X509CertificateOpenSSL::openSSLErrorToQSslError(errorAndDepth.code, certificate);
1372 errorsReportedFromCallback =
true;
1373 handshakeInterrupted =
true;
1374 emit q->handshakeInterruptedOnError(tlsError);
1382 errorList->append(errorAndDepth);
1386 return !handshakeInterrupted;
1391 Q_ASSERT(pendingFatalAlert);
1394 auto *plainSocket = d->plainTcpSocket();
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) {
1402 data.resize(pendingBytes);
1403 const int bioReadBytes = q_BIO_read(writeBio, data.data(), pendingBytes);
1406 qint64 actualWritten = plainSocket->write(data.constData(), bioReadBytes);
1407 if (actualWritten < 0)
1409 plainSocket->flush();
1420 const auto mode = d->tlsMode();
1421 const auto configuration = q->sslConfiguration();
1422 if (!sslContextPointer)
1423 sslContextPointer = QSslContext::sharedFromConfiguration(mode, configuration, d->isRootsOnDemandAllowed());
1425 if (sslContextPointer->error() != QSslError::NoError) {
1426 setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError, sslContextPointer->errorString());
1427 sslContextPointer.reset();
1432 if (!(ssl = sslContextPointer->createSsl())) {
1433 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1434 QSslSocket::tr(
"Error creating SSL session, %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1438 if (configuration.protocol() != QSsl::UnknownProtocol && mode == QSslSocket::SslClientMode) {
1439 const auto verificationPeerName = d->verificationName();
1441 QString tlsHostName = verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName;
1442 if (tlsHostName.isEmpty())
1443 tlsHostName = d->tlsHostName();
1444 QByteArray ace = QUrl::toAce(tlsHostName);
1447 && !QHostAddress().setAddress(tlsHostName)
1448 && !(configuration.testSslOption(QSsl::SslOptionDisableServerNameIndication))) {
1451 if (ace.endsWith(
'.'))
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");
1464 if (!readBio || !writeBio) {
1465 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1466 QSslSocket::tr(
"Error creating SSL session: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1477 if (mode == QSslSocket::SslClientMode)
1484#ifndef OPENSSL_NO_PSK
1486 if (mode == QSslSocket::SslClientMode)
1488 else if (mode == QSslSocket::SslServerMode)
1491#if OPENSSL_VERSION_NUMBER
>= 0x10101006L
1493 if (mode == QSslSocket::SslClientMode
1494 && QSslSocket::sslLibraryBuildVersionNumber() >= 0x10101006L) {
1495 q_SSL_set_psk_use_session_callback(ssl, &q_ssl_psk_use_session_callback);
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"));
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"));
1515 ocspResponseDer.clear();
1516 const auto backendConfig = configuration.backendConfiguration();
1517 auto responsePos = backendConfig.find(
"Qt-OCSP-response");
1518 if (responsePos != backendConfig.end()) {
1522 const QVariant data(responsePos.value());
1523 if (data.canConvert<QByteArray>())
1524 ocspResponseDer = data.toByteArray();
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"));
1548 const auto errors = QTlsBackendOpenSSL::getErrorsFromOpenSsl();
1555 sslContextPointer.reset();
1566 X509 *x509 = q_SSL_get_peer_certificate(ssl);
1568 const auto peerCertificate = QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1569 QTlsBackend::storePeerCertificate(d, peerCertificate);
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);
1762 unsigned max_identity_len,
1763 unsigned char *psk,
unsigned max_psk_len)
1767 QSslPreSharedKeyAuthenticator authenticator;
1769 const int hintLength = hint ?
int(std::strlen(hint)) : 0;
1770 QTlsBackend::setupClientPskAuth(&authenticator, hint, hintLength, max_identity_len, max_psk_len);
1772 emit q->preSharedKeyAuthenticationRequired(&authenticator);
1775 if (authenticator.preSharedKey().isEmpty())
1779 const int identityLength = qMin(authenticator.identity().size(), authenticator.maximumIdentityLength());
1780 std::memcpy(identity, authenticator.identity().constData(), identityLength);
1781 identity[identityLength] = 0;
1783 const int pskLength = qMin(authenticator.preSharedKey().size(), authenticator.maximumPreSharedKeyLength());
1784 std::memcpy(psk, authenticator.preSharedKey().constData(), pskLength);
1789 unsigned max_psk_len)
1793 QSslPreSharedKeyAuthenticator authenticator;
1796 QTlsBackend::setupServerPskAuth(&authenticator, identity, q->sslConfiguration().preSharedKeyIdentityHint(),
1798 emit q->preSharedKeyAuthenticationRequired(&authenticator);
1801 if (authenticator.preSharedKey().isEmpty())
1805 const int pskLength = qMin(authenticator.preSharedKey().size(), authenticator.maximumPreSharedKeyLength());
1806 std::memcpy(psk, authenticator.preSharedKey().constData(), pskLength);
1817 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)