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 : 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 auto sslCfg = q->sslConfiguration();
756 auto list = sslCfg.keyingMaterial();
758 for (
auto &entry : list) {
759 if (!entry.isValid()) {
760#ifdef QSSLSOCKET_DEBUG
761 qCDebug(lcTlsBackend) <<
"keying material request is invalid:" << entry;
766 QByteArray output(entry.keyingValueSize, Qt::Uninitialized);
768
769
770
771
772
773
774
775 auto *outputData =
reinterpret_cast<
unsigned char*>(output.data());
776 const auto *context =
reinterpret_cast<
const unsigned char*>(entry.context().constData());
777 if (q_SSL_export_keying_material(ssl,
779 entry.keyingValueSize,
780 entry.label().constData(),
781 entry.label().size(),
783 entry.context().size(),
784 entry.context().isNull() ? 0 : 1)) {
785 entry.keyingValue = output;
786#ifdef QSSLSOCKET_DEBUG
788 qCDebug(lcTlsBackend) <<
"cannot export keying material:" << entry;
793 sslCfg.setKeyingMaterial(list);
794 q->setSslConfiguration(sslCfg);
802 auto *plainSocket = d->plainTcpSocket();
803 Q_ASSERT(plainSocket);
805 const auto mode = d->tlsMode();
808 if (
const auto maxSize = d->maxReadBufferSize())
809 plainSocket->setReadBufferSize(maxSize);
811 if (q_SSL_session_reused(ssl))
812 QTlsBackend::setPeerSessionShared(d,
true);
814#ifdef QT_DECRYPT_SSL_TRAFFIC
815 if (q_SSL_get_session(ssl)) {
816 size_t master_key_len = q_SSL_SESSION_get_master_key(q_SSL_get_session(ssl),
nullptr, 0);
817 size_t client_random_len = q_SSL_get_client_random(ssl,
nullptr, 0);
818 QByteArray masterKey(
int(master_key_len), Qt::Uninitialized);
819 QByteArray clientRandom(
int(client_random_len), Qt::Uninitialized);
821 q_SSL_SESSION_get_master_key(q_SSL_get_session(ssl),
822 reinterpret_cast<
unsigned char*>(masterKey.data()),
824 q_SSL_get_client_random(ssl,
reinterpret_cast<
unsigned char *>(clientRandom.data()),
825 clientRandom.size());
827 QByteArray debugLineClientRandom(
"CLIENT_RANDOM ");
828 debugLineClientRandom.append(clientRandom.toHex().toUpper());
829 debugLineClientRandom.append(
" ");
830 debugLineClientRandom.append(masterKey.toHex().toUpper());
831 debugLineClientRandom.append(
"\n");
833 QString sslKeyFile = QDir::tempPath() +
"/qt-ssl-keys"_L1;
834 QFile file(sslKeyFile);
835 if (!file.open(QIODevice::Append))
836 qCWarning(lcTlsBackend) <<
"could not open file" << sslKeyFile <<
"for appending";
837 if (!file.write(debugLineClientRandom))
838 qCWarning(lcTlsBackend) <<
"could not write to file" << sslKeyFile;
841 qCWarning(lcTlsBackend,
"could not decrypt SSL traffic");
845 const auto &configuration = q->sslConfiguration();
847 if (!(configuration.testSslOption(QSsl::SslOptionDisableSessionSharing))) {
848 if (!sslContextPointer->cacheSession(ssl)) {
849 sslContextPointer.reset();
852 if (!(configuration.testSslOption(QSsl::SslOptionDisableSessionPersistence))) {
853 if (!sslContextPointer->sessionASN1().isEmpty())
854 QTlsBackend::setSessionAsn1(d, sslContextPointer->sessionASN1());
855 QTlsBackend::setSessionLifetimeHint(d, sslContextPointer->sessionTicketLifeTimeHint());
860#if !defined(OPENSSL_NO_NEXTPROTONEG)
862 QTlsBackend::setAlpnStatus(d, sslContextPointer->npnContext().status);
863 if (sslContextPointer->npnContext().status == QSslConfiguration::NextProtocolNegotiationUnsupported) {
867 QTlsBackend::setNegotiatedProtocol(d, QByteArrayLiteral(
"http/1.1"));
869 const unsigned char *proto =
nullptr;
870 unsigned int proto_len = 0;
873 if (proto_len && mode == QSslSocket::SslClientMode) {
875 QTlsBackend::setAlpnStatus(d, QSslConfiguration::NextProtocolNegotiationNegotiated);
883 QTlsBackend::setNegotiatedProtocol(d, QByteArray(
reinterpret_cast<
const char *>(proto), proto_len));
885 QTlsBackend::setNegotiatedProtocol(d,{});
889 if (mode == QSslSocket::SslClientMode) {
892 QTlsBackend::setEphemeralKey(d, QSslKey(key, QSsl::PublicKey));
897 d->setEncrypted(
true);
899 if (d->isAutoStartingHandshake() && d->isPendingClose()) {
900 d->setPendingClose(
false);
901 q->disconnectFromHost();
910 using ScopedBool = QScopedValueRollback<
bool>;
912 if (inSetAndEmitError)
919 auto &writeBuffer = d->tlsWriteBuffer();
920 auto &buffer = d->tlsBuffer();
921 auto *plainSocket = d->plainTcpSocket();
922 Q_ASSERT(plainSocket);
923 bool &emittedBytesWritten = d->tlsEmittedBytesWritten();
927 transmitting =
false;
931 if (q->isEncrypted() && !writeBuffer.isEmpty()) {
932 qint64 totalBytesWritten = 0;
933 int nextDataBlockSize;
934 while ((nextDataBlockSize = writeBuffer.nextDataBlockSize()) > 0) {
935 int writtenBytes = q_SSL_write(ssl, writeBuffer.readPointer(), nextDataBlockSize);
936 if (writtenBytes <= 0) {
939 if (error == SSL_ERROR_WANT_WRITE) {
942 }
else if (error == SSL_ERROR_WANT_READ) {
944 transmitting =
false;
948 const ScopedBool bg(inSetAndEmitError,
true);
949 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
950 QSslSocket::tr(
"Unable to write data: %1").arg(
951 QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
955#ifdef QSSLSOCKET_DEBUG
956 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: encrypted" << writtenBytes <<
"bytes";
958 writeBuffer.free(writtenBytes);
959 totalBytesWritten += writtenBytes;
961 if (writtenBytes < nextDataBlockSize) {
968 if (totalBytesWritten > 0) {
970 if (!emittedBytesWritten) {
971 emittedBytesWritten =
true;
972 emit q->bytesWritten(totalBytesWritten);
973 emittedBytesWritten =
false;
975 emit q->channelBytesWritten(0, totalBytesWritten);
980 QVarLengthArray<
char, 4096> data;
982 while (plainSocket->isValid() && (pendingBytes =
q_BIO_pending(writeBio)) > 0
983 && plainSocket->openMode() != QIODevice::NotOpen) {
985 data.resize(pendingBytes);
986 int encryptedBytesRead = q_BIO_read(writeBio, data.data(), pendingBytes);
989 qint64 actualWritten = plainSocket->write(data.constData(), encryptedBytesRead);
990#ifdef QSSLSOCKET_DEBUG
991 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: wrote" << encryptedBytesRead
992 <<
"encrypted bytes to the socket" << actualWritten <<
"actual.";
994 if (actualWritten < 0) {
996 const ScopedBool bg(inSetAndEmitError,
true);
997 setErrorAndEmit(d, plainSocket->error(), plainSocket->errorString());
1000 transmitting =
true;
1004 if (!q->isEncrypted() || !d->maxReadBufferSize() || buffer.size() < d->maxReadBufferSize())
1005 while ((pendingBytes = plainSocket->bytesAvailable()) > 0) {
1007 data.resize(pendingBytes);
1009 int encryptedBytesRead = plainSocket->peek(data.data(), pendingBytes);
1011#ifdef QSSLSOCKET_DEBUG
1012 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: read" << encryptedBytesRead <<
"encrypted bytes from the socket";
1015 int writtenToBio = q_BIO_write(readBio, data.constData(), encryptedBytesRead);
1018 if (writtenToBio > 0) {
1019 plainSocket->skip(writtenToBio);
1022 const ScopedBool bg(inSetAndEmitError,
true);
1023 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1024 QSslSocket::tr(
"Unable to decrypt data: %1")
1025 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1029 transmitting =
true;
1034 if (!q->isEncrypted()) {
1035#ifdef QSSLSOCKET_DEBUG
1036 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: testing encryption";
1039#ifdef QSSLSOCKET_DEBUG
1040 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: encryption established";
1042 d->setEncrypted(
true);
1043 transmitting =
true;
1044 }
else if (plainSocket->state() != QAbstractSocket::ConnectedState) {
1045#ifdef QSSLSOCKET_DEBUG
1046 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: connection lost";
1049 }
else if (d->isPaused()) {
1053#ifdef QSSLSOCKET_DEBUG
1054 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: encryption not done yet";
1069 const int bytesToRead = 4096;
1071 if (q->readChannelCount() == 0) {
1077 readBytes = q_SSL_read(ssl, buffer.reserve(bytesToRead), bytesToRead);
1080 renegotiated =
false;
1081 X509 *x509 = q_SSL_get_peer_certificate(ssl);
1082 const auto peerCertificate =
1083 QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1085 if (peerCertificate != q->peerCertificate()) {
1086 const ScopedBool bg(inSetAndEmitError,
true);
1088 d, QAbstractSocket::RemoteHostClosedError,
1090 "TLS certificate unexpectedly changed during renegotiation!"));
1095 if (readBytes > 0) {
1096#ifdef QSSLSOCKET_DEBUG
1097 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: decrypted" << readBytes <<
"bytes";
1099 buffer.chop(bytesToRead - readBytes);
1101 if (
bool *readyReadEmittedPointer = d->readyReadPointer())
1102 *readyReadEmittedPointer =
true;
1103 emit q->readyRead();
1104 emit q->channelReadyRead(0);
1105 transmitting =
true;
1108 buffer.chop(bytesToRead);
1112 case SSL_ERROR_WANT_READ:
1113 case SSL_ERROR_WANT_WRITE:
1116 case SSL_ERROR_ZERO_RETURN:
1118#ifdef QSSLSOCKET_DEBUG
1119 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: remote disconnect";
1123 const ScopedBool bg(inSetAndEmitError,
true);
1124 setErrorAndEmit(d, QAbstractSocket::RemoteHostClosedError,
1125 QSslSocket::tr(
"The TLS/SSL connection has been closed"));
1128 case SSL_ERROR_SYSCALL:
1132 systemOrSslErrorDetected =
true;
1134 const ScopedBool bg(inSetAndEmitError,
true);
1135 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1136 QSslSocket::tr(
"Error while reading: %1")
1137 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1147 const ScopedBool bg(inSetAndEmitError,
true);
1148 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1149 QSslSocket::tr(
"Error while reading: %1")
1150 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1154 }
while (ssl && readBytes > 0);
1155 }
while (ssl && transmitting);
1171 auto *plainSocket = d->plainTcpSocket();
1172 Q_ASSERT(plainSocket);
1173 plainSocket->disconnectFromHost();
1179 auto *plainSocket = d->plainTcpSocket();
1180 Q_ASSERT(plainSocket);
1181 d->setEncrypted(
false);
1183 if (plainSocket->bytesAvailable() <= 0) {
1184 destroySslContext();
1187 const qint64 tmpReadBufferMaxSize = d->maxReadBufferSize();
1189 d->setMaxReadBufferSize(0);
1191 d->setMaxReadBufferSize(tmpReadBufferMaxSize);
1203 return sessionCipher ? QTlsBackendOpenSSL::qt_OpenSSL_cipher_to_QSslCipher(sessionCipher) : QSslCipher{};
1209 return QSsl::UnknownProtocol;
1214QT_WARNING_DISABLE_DEPRECATED
1216 return QSsl::TlsV1_0;
1218 return QSsl::TlsV1_1;
1221 return QSsl::TlsV1_2;
1223 return QSsl::TlsV1_3;
1226 return QSsl::UnknownProtocol;
1231 return ocspResponses;
1239 if (sslErrors.isEmpty())
1242 emit q->sslErrors(sslErrors);
1244 const auto vfyMode = q->peerVerifyMode();
1245 const auto mode = d->tlsMode();
1247 bool doVerifyPeer = vfyMode == QSslSocket::VerifyPeer || (vfyMode == QSslSocket::AutoVerifyPeer
1248 && mode == QSslSocket::SslClientMode);
1249 bool doEmitSslError = !d->verifyErrorsHaveBeenIgnored();
1251 if (doVerifyPeer && doEmitSslError) {
1252 if (q->pauseMode() & QAbstractSocket::PauseOnSslErrors) {
1253 QSslSocketPrivate::pauseSocketNotifiers(q);
1256 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, sslErrors.constFirst().errorString());
1257 auto *plainSocket = d->plainTcpSocket();
1258 Q_ASSERT(plainSocket);
1259 plainSocket->disconnectFromHost();
1271 Q_ASSERT(connection);
1276 if (q->sslConfiguration().testSslOption(QSsl::SslOptionDisableSessionPersistence)) {
1282 if (!currentSession) {
1283 qCWarning(lcTlsBackend,
1284 "New session ticket callback, the session is invalid (nullptr)");
1293#ifdef TLS1_3_VERSION
1294 if (!q_SSL_SESSION_is_resumable(currentSession)) {
1295 qCDebug(lcTlsBackend,
"New session ticket, but the session is non-resumable");
1301 if (sessionSize <= 0) {
1302 qCWarning(lcTlsBackend,
"could not store persistent version of SSL session");
1307 QByteArray sessionTicket(sessionSize, 0);
1308 auto data =
reinterpret_cast<
unsigned char *>(sessionTicket.data());
1309 if (!q_i2d_SSL_SESSION(currentSession, &data)) {
1310 qCWarning(lcTlsBackend,
"could not store persistent version of SSL session");
1314 QTlsBackend::setSessionAsn1(d, sessionTicket);
1315 QTlsBackend::setSessionLifetimeHint(d, q_SSL_SESSION_get_ticket_lifetime_hint(currentSession));
1317 emit q->newSessionTicketReceived();
1326 const auto level = tlsAlertLevel(value);
1327 if (level == QSsl::AlertLevel::Fatal && !q->isEncrypted()) {
1329 pendingFatalAlert =
true;
1332 emit q->alertSent(level, tlsAlertType(value), tlsAlertDescription(value));
1340 emit q->alertReceived(tlsAlertLevel(value), tlsAlertType(value), tlsAlertDescription(value));
1350 using ScopedBool = QScopedValueRollback<
bool>;
1354 const ScopedBool bg(inSetAndEmitError,
true);
1358 qCWarning(lcTlsBackend,
"Could not obtain the certificate (that failed to verify)");
1362 const QSslCertificate certificate = QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1364 const QSslError tlsError = QTlsPrivate::X509CertificateOpenSSL::openSSLErrorToQSslError(errorAndDepth.code, certificate);
1366 errorsReportedFromCallback =
true;
1367 handshakeInterrupted =
true;
1368 emit q->handshakeInterruptedOnError(tlsError);
1376 errorList->append(errorAndDepth);
1380 return !handshakeInterrupted;
1385 Q_ASSERT(pendingFatalAlert);
1388 auto *plainSocket = d->plainTcpSocket();
1390 pendingFatalAlert =
false;
1391 QVarLengthArray<
char, 4096> data;
1392 int pendingBytes = 0;
1393 while (plainSocket->isValid() && (pendingBytes =
q_BIO_pending(writeBio)) > 0
1394 && plainSocket->openMode() != QIODevice::NotOpen) {
1396 data.resize(pendingBytes);
1397 const int bioReadBytes = q_BIO_read(writeBio, data.data(), pendingBytes);
1400 qint64 actualWritten = plainSocket->write(data.constData(), bioReadBytes);
1401 if (actualWritten < 0)
1403 plainSocket->flush();
1414 const auto mode = d->tlsMode();
1415 const auto configuration = q->sslConfiguration();
1416 if (!sslContextPointer)
1417 sslContextPointer = QSslContext::sharedFromConfiguration(mode, configuration, d->isRootsOnDemandAllowed());
1419 if (sslContextPointer->error() != QSslError::NoError) {
1420 setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError, sslContextPointer->errorString());
1421 sslContextPointer.reset();
1426 if (!(ssl = sslContextPointer->createSsl())) {
1427 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1428 QSslSocket::tr(
"Error creating SSL session, %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1432 if (configuration.protocol() != QSsl::UnknownProtocol && mode == QSslSocket::SslClientMode) {
1433 const auto verificationPeerName = d->verificationName();
1435 QString tlsHostName = verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName;
1436 if (tlsHostName.isEmpty())
1437 tlsHostName = d->tlsHostName();
1438 QByteArray ace = QUrl::toAce(tlsHostName);
1441 && !QHostAddress().setAddress(tlsHostName)
1442 && !(configuration.testSslOption(QSsl::SslOptionDisableServerNameIndication))) {
1445 if (ace.endsWith(
'.'))
1447 if (!q_SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, ace.data()))
1448 qCWarning(lcTlsBackend,
"could not set SSL_CTRL_SET_TLSEXT_HOSTNAME, Server Name Indication disabled");
1458 if (!readBio || !writeBio) {
1459 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1460 QSslSocket::tr(
"Error creating SSL session: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1471 if (mode == QSslSocket::SslClientMode)
1478#ifndef OPENSSL_NO_PSK
1480 if (mode == QSslSocket::SslClientMode)
1482 else if (mode == QSslSocket::SslServerMode)
1485#if OPENSSL_VERSION_NUMBER
>= 0x10101006L
1487 if (mode == QSslSocket::SslClientMode
1488 && QSslSocket::sslLibraryBuildVersionNumber() >= 0x10101006L) {
1489 q_SSL_set_psk_use_session_callback(ssl, &q_ssl_psk_use_session_callback);
1496 if (configuration.ocspStaplingEnabled()) {
1497 if (mode == QSslSocket::SslServerMode) {
1498 setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError,
1499 QSslSocket::tr(
"Server-side QSslSocket does not support OCSP stapling"));
1502 if (q_SSL_set_tlsext_status_type(ssl, TLSEXT_STATUSTYPE_ocsp) != 1) {
1503 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1504 QSslSocket::tr(
"Failed to enable OCSP stapling"));
1509 ocspResponseDer.clear();
1510 const auto backendConfig = configuration.backendConfiguration();
1511 auto responsePos = backendConfig.find(
"Qt-OCSP-response");
1512 if (responsePos != backendConfig.end()) {
1516 const QVariant data(responsePos.value());
1517 if (data.canConvert<QByteArray>())
1518 ocspResponseDer = data.toByteArray();
1521 if (ocspResponseDer.size()) {
1522 if (mode != QSslSocket::SslServerMode) {
1523 setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError,
1524 QSslSocket::tr(
"Client-side sockets do not send OCSP responses"));
1542 const auto errors = QTlsBackendOpenSSL::getErrorsFromOpenSsl();
1549 sslContextPointer.reset();
1560 X509 *x509 = q_SSL_get_peer_certificate(ssl);
1562 const auto peerCertificate = QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1563 QTlsBackend::storePeerCertificate(d, peerCertificate);
1565 auto peerCertificateChain = q->peerCertificateChain();
1566 if (peerCertificateChain.isEmpty()) {
1567 peerCertificateChain = QTlsPrivate::X509CertificateOpenSSL::stackOfX509ToQSslCertificates(q_SSL_get_peer_cert_chain(ssl));
1568 if (!peerCertificate.isNull() && d->tlsMode() == QSslSocket::SslServerMode)
1569 peerCertificateChain.prepend(peerCertificate);
1570 QTlsBackend::storePeerCertificateChain(d, peerCertificateChain);
1756 unsigned max_identity_len,
1757 unsigned char *psk,
unsigned max_psk_len)
1761 QSslPreSharedKeyAuthenticator authenticator;
1763 const int hintLength = hint ?
int(std::strlen(hint)) : 0;
1764 QTlsBackend::setupClientPskAuth(&authenticator, hint, hintLength, max_identity_len, max_psk_len);
1766 emit q->preSharedKeyAuthenticationRequired(&authenticator);
1769 if (authenticator.preSharedKey().isEmpty())
1773 const int identityLength = qMin(authenticator.identity().size(), authenticator.maximumIdentityLength());
1774 std::memcpy(identity, authenticator.identity().constData(), identityLength);
1775 identity[identityLength] = 0;
1777 const int pskLength = qMin(authenticator.preSharedKey().size(), authenticator.maximumPreSharedKeyLength());
1778 std::memcpy(psk, authenticator.preSharedKey().constData(), pskLength);
1783 unsigned max_psk_len)
1787 QSslPreSharedKeyAuthenticator authenticator;
1790 QTlsBackend::setupServerPskAuth(&authenticator, identity, q->sslConfiguration().preSharedKeyIdentityHint(),
1792 emit q->preSharedKeyAuthenticationRequired(&authenticator);
1795 if (authenticator.preSharedKey().isEmpty())
1799 const int pskLength = qMin(authenticator.preSharedKey().size(), authenticator.maximumPreSharedKeyLength());
1800 std::memcpy(psk, authenticator.preSharedKey().constData(), pskLength);
1811 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)