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>
20#include <QtCore/qscopedvaluerollback.h>
21#include <QtCore/qscopeguard.h>
28using namespace Qt::StringLiterals;
32QSsl::AlertLevel tlsAlertLevel(
int value)
34 using QSsl::AlertLevel;
39 switch (typeString[0]) {
41 return AlertLevel::Warning;
43 return AlertLevel::Fatal;
48 return AlertLevel::Unknown;
51QString tlsAlertDescription(
int value)
54 if (!description.size())
55 description =
"no description provided"_L1;
59QSsl::AlertType tlsAlertType(
int value)
65 return QSsl::AlertType(value & 0xff);
70QSslCertificate findCertificateToFetch(
const QList<QSslError> &tlsErrors,
bool checkAIA)
72 QSslCertificate certToFetch;
74 for (
const auto &tlsError : tlsErrors) {
75 switch (tlsError.error()) {
76 case QSslError::UnableToGetLocalIssuerCertificate:
77 case QSslError::SelfSignedCertificateInChain:
78 certToFetch = tlsError.certificate();
80 case QSslError::SelfSignedCertificate:
81 case QSslError::CertificateBlacklisted:
83 return QSslCertificate{};
85#ifdef QSSLSOCKET_DEBUG
86 qCDebug(lcTlsBackend) << tlsError.errorString();
94 const auto extensions = certToFetch.extensions();
95 for (
const auto &ext : extensions) {
96 if (ext.oid() == u"1.3.6.1.5.5.7.1.1")
103 return QSslCertificate{};
120 using ErrorListPtr = QList<QSslErrorEntry> *;
121 ErrorListPtr errors =
nullptr;
159 qCWarning(lcTlsBackend,
"Neither X509_STORE, nor SSL contains error list, handshake failure");
181 qCWarning(lcTlsBackend,
"Invalid store context (nullptr)");
193 qCWarning(lcTlsBackend,
"No external data (SSL) found in X509 store object");
201 qCWarning(lcTlsBackend,
"No external data (TlsCryptographOpenSSL) found in SSL object");
210#ifndef OPENSSL_NO_PSK
212 unsigned char *psk,
unsigned max_psk_len)
219 unsigned int max_psk_len)
227static unsigned q_ssl_psk_restore_client(SSL *ssl,
const char *hint,
char *identity,
unsigned max_identity_len,
228 unsigned char *psk,
unsigned max_psk_len)
232 Q_UNUSED(max_identity_len);
234 Q_UNUSED(max_psk_len);
237 auto tls =
static_cast<TlsCryptographOpenSSL *>(q_SSL_get_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData));
240 Q_ASSERT(tls->d->tlsMode() == QSslSocket::SslClientMode);
247 if (qEnvironmentVariableIsSet(
"QT_USE_TLS_1_3_PSK"))
255static int q_ssl_psk_use_session_callback(SSL *ssl,
const EVP_MD *md,
const unsigned char **id,
256 size_t *idlen, SSL_SESSION **sess)
264 auto *tls =
static_cast<TlsCryptographOpenSSL *>(q_SSL_get_ex_data(ssl, QTlsBackendOpenSSL::s_indexForSSLExtraData));
267 Q_ASSERT(tls->d->tlsMode() == QSslSocket::SslClientMode);
276int q_ssl_sess_set_new_cb(SSL *ssl, SSL_SESSION *session)
279 qCWarning(lcTlsBackend,
"Invalid SSL (nullptr)");
283 qCWarning(lcTlsBackend,
"Invalid SSL_SESSION (nullptr)");
332#ifdef QSSLSOCKET_DEBUG
333 qCWarning(lcTlsBackend,
"Invalid 'connection' parameter (nullptr)");
343#ifdef QSSLSOCKET_DEBUG
344 qCWarning(lcTlsBackend,
"No external data (socket backend) found for parameter 'connection'");
349 if (!(from & SSL_CB_ALERT)) {
354 if (from & SSL_CB_WRITE)
483 ocspResponses.clear();
484 ocspResponseDer.clear();
486 systemOrSslErrorDetected =
false;
487 handshakeInterrupted =
false;
489 fetchAuthorityInformation =
false;
501 return sslContextPointer;
511 if (!initSslContext()) {
513 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
514 QSslSocket::tr(
"Unable to init SSL Context: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
526 if (!initSslContext()) {
528 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
529 QSslSocket::tr(
"Unable to init SSL Context: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
546 using ScopedBool = QScopedValueRollback<
bool>;
548 if (inSetAndEmitError)
551 const auto mode = d->tlsMode();
553 pendingFatalAlert =
false;
554 errorsReportedFromCallback =
false;
555 QList<QSslErrorEntry> lastErrors;
562 int result = (mode == QSslSocket::SslClientMode) ? q_SSL_connect(ssl) : q_SSL_accept(ssl);
569 if (!lastErrors.isEmpty() || errorsReportedFromCallback)
574 auto configuration = q->sslConfiguration();
575 if (!errorsReportedFromCallback) {
576 const auto &peerCertificateChain = configuration.peerCertificateChain();
577 for (
const auto ¤tError : std::as_const(lastErrors)) {
578 emit q->peerVerifyError(QTlsPrivate::X509CertificateOpenSSL::openSSLErrorToQSslError(currentError.code,
579 peerCertificateChain.value(currentError.depth)));
580 if (q->state() != QAbstractSocket::ConnectedState)
585 errorList << lastErrors;
588 if (q->state() != QAbstractSocket::ConnectedState)
594 case SSL_ERROR_WANT_READ:
595 case SSL_ERROR_WANT_WRITE:
599 QString errorString = QTlsBackendOpenSSL::msgErrorsDuringHandshake();
600#ifdef QSSLSOCKET_DEBUG
601 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::startHandshake: error!" << errorString;
604 const ScopedBool bg(inSetAndEmitError,
true);
605 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, errorString);
606 if (pendingFatalAlert) {
608 pendingFatalAlert =
false;
620 QList<QSslError> errors;
623 configuration = q->sslConfiguration();
625 const auto &peerCertificateChain = configuration.peerCertificateChain();
626 for (
const QSslCertificate &cert : peerCertificateChain) {
627 if (QSslCertificatePrivate::isBlacklisted(cert)) {
628 QSslError error(QSslError::CertificateBlacklisted, cert);
630 emit q->peerVerifyError(error);
631 if (q->state() != QAbstractSocket::ConnectedState)
636 const bool doVerifyPeer = configuration.peerVerifyMode() == QSslSocket::VerifyPeer
637 || (configuration.peerVerifyMode() == QSslSocket::AutoVerifyPeer
638 && mode == QSslSocket::SslClientMode);
643 if (!configuration.peerCertificate().isNull() && configuration.ocspStaplingEnabled() && doVerifyPeer) {
644 if (!checkOcspStatus()) {
645 if (ocspErrors.isEmpty()) {
647 const ScopedBool bg(inSetAndEmitError,
true);
648 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, ocspErrorDescription);
654 for (
const QSslError &error : ocspErrors) {
656 emit q->peerVerifyError(error);
657 if (q->state() != QAbstractSocket::ConnectedState)
667 if (!configuration.peerCertificate().isNull()) {
670 const auto verificationPeerName = d->verificationName();
671 if (mode == QSslSocket::SslClientMode) {
672 QString peerName = (verificationPeerName.isEmpty () ? q->peerName() : verificationPeerName);
674 if (!isMatchingHostname(configuration.peerCertificate(), peerName)) {
676 QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate());
678 emit q->peerVerifyError(error);
679 if (q->state() != QAbstractSocket::ConnectedState)
687 QSslError error(QSslError::NoPeerCertificate);
689 emit q->peerVerifyError(error);
690 if (q->state() != QAbstractSocket::ConnectedState)
696 errors.reserve(errors.size() + errorList.size());
697 for (
const auto &error : std::as_const(errorList))
698 errors << X509CertificateOpenSSL::openSSLErrorToQSslError(error.code, peerCertificateChain.value(error.depth));
700 if (!errors.isEmpty()) {
703 const bool fetchEnabled = QSslSocketPrivate::rootCertOnDemandLoadingSupported()
704 && d->isRootsOnDemandAllowed();
709 QSslCertificate certToFetch;
710 if (doVerifyPeer && !d->verifyErrorsHaveBeenIgnored())
711 certToFetch = findCertificateToFetch(sslErrors, !fetchEnabled);
714 if (!certToFetch.isNull()) {
715 fetchAuthorityInformation = !fetchEnabled;
722 fetchCaRootForCert(certToFetch);
731 if (q->state() != QAbstractSocket::ConnectedState)
743 handshakeInterrupted =
false;
748 fetchAuthorityInformation =
false;
757 auto *plainSocket = d->plainTcpSocket();
758 Q_ASSERT(plainSocket);
760 const auto mode = d->tlsMode();
763 if (
const auto maxSize = d->maxReadBufferSize())
764 plainSocket->setReadBufferSize(maxSize);
766 if (q_SSL_session_reused(ssl))
767 QTlsBackend::setPeerSessionShared(d,
true);
769#ifdef QT_DECRYPT_SSL_TRAFFIC
770 if (q_SSL_get_session(ssl)) {
771 size_t master_key_len = q_SSL_SESSION_get_master_key(q_SSL_get_session(ssl),
nullptr, 0);
772 size_t client_random_len = q_SSL_get_client_random(ssl,
nullptr, 0);
773 QByteArray masterKey(
int(master_key_len), Qt::Uninitialized);
774 QByteArray clientRandom(
int(client_random_len), Qt::Uninitialized);
776 q_SSL_SESSION_get_master_key(q_SSL_get_session(ssl),
777 reinterpret_cast<
unsigned char*>(masterKey.data()),
779 q_SSL_get_client_random(ssl,
reinterpret_cast<
unsigned char *>(clientRandom.data()),
780 clientRandom.size());
782 QByteArray debugLineClientRandom(
"CLIENT_RANDOM ");
783 debugLineClientRandom.append(clientRandom.toHex().toUpper());
784 debugLineClientRandom.append(
" ");
785 debugLineClientRandom.append(masterKey.toHex().toUpper());
786 debugLineClientRandom.append(
"\n");
788 QString sslKeyFile = QDir::tempPath() +
"/qt-ssl-keys"_L1;
789 QFile file(sslKeyFile);
790 if (!file.open(QIODevice::Append))
791 qCWarning(lcTlsBackend) <<
"could not open file" << sslKeyFile <<
"for appending";
792 if (!file.write(debugLineClientRandom))
793 qCWarning(lcTlsBackend) <<
"could not write to file" << sslKeyFile;
796 qCWarning(lcTlsBackend,
"could not decrypt SSL traffic");
800 const auto &configuration = q->sslConfiguration();
802 if (!(configuration.testSslOption(QSsl::SslOptionDisableSessionSharing))) {
803 if (!sslContextPointer->cacheSession(ssl)) {
804 sslContextPointer.reset();
807 if (!(configuration.testSslOption(QSsl::SslOptionDisableSessionPersistence))) {
808 if (!sslContextPointer->sessionASN1().isEmpty())
809 QTlsBackend::setSessionAsn1(d, sslContextPointer->sessionASN1());
810 QTlsBackend::setSessionLifetimeHint(d, sslContextPointer->sessionTicketLifeTimeHint());
815#if !defined(OPENSSL_NO_NEXTPROTONEG)
817 QTlsBackend::setAlpnStatus(d, sslContextPointer->npnContext().status);
818 if (sslContextPointer->npnContext().status == QSslConfiguration::NextProtocolNegotiationUnsupported) {
822 QTlsBackend::setNegotiatedProtocol(d, QByteArrayLiteral(
"http/1.1"));
824 const unsigned char *proto =
nullptr;
825 unsigned int proto_len = 0;
828 if (proto_len && mode == QSslSocket::SslClientMode) {
830 QTlsBackend::setAlpnStatus(d, QSslConfiguration::NextProtocolNegotiationNegotiated);
838 QTlsBackend::setNegotiatedProtocol(d, QByteArray(
reinterpret_cast<
const char *>(proto), proto_len));
840 QTlsBackend::setNegotiatedProtocol(d,{});
844 if (mode == QSslSocket::SslClientMode) {
847 QTlsBackend::setEphemeralKey(d, QSslKey(key, QSsl::PublicKey));
850 d->setEncrypted(
true);
852 if (d->isAutoStartingHandshake() && d->isPendingClose()) {
853 d->setPendingClose(
false);
854 q->disconnectFromHost();
863 using ScopedBool = QScopedValueRollback<
bool>;
865 if (inSetAndEmitError)
872 auto &writeBuffer = d->tlsWriteBuffer();
873 auto &buffer = d->tlsBuffer();
874 auto *plainSocket = d->plainTcpSocket();
875 Q_ASSERT(plainSocket);
876 bool &emittedBytesWritten = d->tlsEmittedBytesWritten();
880 transmitting =
false;
884 if (q->isEncrypted() && !writeBuffer.isEmpty()) {
885 qint64 totalBytesWritten = 0;
886 int nextDataBlockSize;
887 while ((nextDataBlockSize = writeBuffer.nextDataBlockSize()) > 0) {
888 int writtenBytes = q_SSL_write(ssl, writeBuffer.readPointer(), nextDataBlockSize);
889 if (writtenBytes <= 0) {
892 if (error == SSL_ERROR_WANT_WRITE) {
895 }
else if (error == SSL_ERROR_WANT_READ) {
897 transmitting =
false;
901 const ScopedBool bg(inSetAndEmitError,
true);
902 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
903 QSslSocket::tr(
"Unable to write data: %1").arg(
904 QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
908#ifdef QSSLSOCKET_DEBUG
909 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: encrypted" << writtenBytes <<
"bytes";
911 writeBuffer.free(writtenBytes);
912 totalBytesWritten += writtenBytes;
914 if (writtenBytes < nextDataBlockSize) {
921 if (totalBytesWritten > 0) {
923 if (!emittedBytesWritten) {
924 emittedBytesWritten =
true;
925 emit q->bytesWritten(totalBytesWritten);
926 emittedBytesWritten =
false;
928 emit q->channelBytesWritten(0, totalBytesWritten);
933 QVarLengthArray<
char, 4096> data;
935 while (plainSocket->isValid() && (pendingBytes =
q_BIO_pending(writeBio)) > 0
936 && plainSocket->openMode() != QIODevice::NotOpen) {
938 data.resize(pendingBytes);
939 int encryptedBytesRead = q_BIO_read(writeBio, data.data(), pendingBytes);
942 qint64 actualWritten = plainSocket->write(data.constData(), encryptedBytesRead);
943#ifdef QSSLSOCKET_DEBUG
944 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: wrote" << encryptedBytesRead
945 <<
"encrypted bytes to the socket" << actualWritten <<
"actual.";
947 if (actualWritten < 0) {
949 const ScopedBool bg(inSetAndEmitError,
true);
950 setErrorAndEmit(d, plainSocket->error(), plainSocket->errorString());
957 if (!q->isEncrypted() || !d->maxReadBufferSize() || buffer.size() < d->maxReadBufferSize())
958 while ((pendingBytes = plainSocket->bytesAvailable()) > 0) {
960 data.resize(pendingBytes);
962 int encryptedBytesRead = plainSocket->peek(data.data(), pendingBytes);
964#ifdef QSSLSOCKET_DEBUG
965 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: read" << encryptedBytesRead <<
"encrypted bytes from the socket";
968 int writtenToBio = q_BIO_write(readBio, data.constData(), encryptedBytesRead);
971 if (writtenToBio > 0) {
972 plainSocket->skip(writtenToBio);
975 const ScopedBool bg(inSetAndEmitError,
true);
976 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
977 QSslSocket::tr(
"Unable to decrypt data: %1")
978 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
987 if (!q->isEncrypted()) {
988#ifdef QSSLSOCKET_DEBUG
989 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: testing encryption";
992#ifdef QSSLSOCKET_DEBUG
993 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: encryption established";
995 d->setEncrypted(
true);
997 }
else if (plainSocket->state() != QAbstractSocket::ConnectedState) {
998#ifdef QSSLSOCKET_DEBUG
999 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: connection lost";
1002 }
else if (d->isPaused()) {
1006#ifdef QSSLSOCKET_DEBUG
1007 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: encryption not done yet";
1022 const int bytesToRead = 4096;
1024 if (q->readChannelCount() == 0) {
1030 readBytes = q_SSL_read(ssl, buffer.reserve(bytesToRead), bytesToRead);
1033 renegotiated =
false;
1034 X509 *x509 = q_SSL_get_peer_certificate(ssl);
1035 const auto peerCertificate =
1036 QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1038 if (peerCertificate != q->peerCertificate()) {
1039 const ScopedBool bg(inSetAndEmitError,
true);
1041 d, QAbstractSocket::RemoteHostClosedError,
1043 "TLS certificate unexpectedly changed during renegotiation!"));
1048 if (readBytes > 0) {
1049#ifdef QSSLSOCKET_DEBUG
1050 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: decrypted" << readBytes <<
"bytes";
1052 buffer.chop(bytesToRead - readBytes);
1054 if (
bool *readyReadEmittedPointer = d->readyReadPointer())
1055 *readyReadEmittedPointer =
true;
1056 emit q->readyRead();
1057 emit q->channelReadyRead(0);
1058 transmitting =
true;
1061 buffer.chop(bytesToRead);
1065 case SSL_ERROR_WANT_READ:
1066 case SSL_ERROR_WANT_WRITE:
1069 case SSL_ERROR_ZERO_RETURN:
1071#ifdef QSSLSOCKET_DEBUG
1072 qCDebug(lcTlsBackend) <<
"TlsCryptographOpenSSL::transmit: remote disconnect";
1076 const ScopedBool bg(inSetAndEmitError,
true);
1077 setErrorAndEmit(d, QAbstractSocket::RemoteHostClosedError,
1078 QSslSocket::tr(
"The TLS/SSL connection has been closed"));
1081 case SSL_ERROR_SYSCALL:
1085 systemOrSslErrorDetected =
true;
1087 const ScopedBool bg(inSetAndEmitError,
true);
1088 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1089 QSslSocket::tr(
"Error while reading: %1")
1090 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1100 const ScopedBool bg(inSetAndEmitError,
true);
1101 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1102 QSslSocket::tr(
"Error while reading: %1")
1103 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1107 }
while (ssl && readBytes > 0);
1108 }
while (ssl && transmitting);
1124 auto *plainSocket = d->plainTcpSocket();
1125 Q_ASSERT(plainSocket);
1126 plainSocket->disconnectFromHost();
1132 auto *plainSocket = d->plainTcpSocket();
1133 Q_ASSERT(plainSocket);
1134 d->setEncrypted(
false);
1136 if (plainSocket->bytesAvailable() <= 0) {
1137 destroySslContext();
1140 const qint64 tmpReadBufferMaxSize = d->maxReadBufferSize();
1142 d->setMaxReadBufferSize(0);
1144 d->setMaxReadBufferSize(tmpReadBufferMaxSize);
1156 return sessionCipher ? QTlsBackendOpenSSL::qt_OpenSSL_cipher_to_QSslCipher(sessionCipher) : QSslCipher{};
1162 return QSsl::UnknownProtocol;
1167QT_WARNING_DISABLE_DEPRECATED
1169 return QSsl::TlsV1_0;
1171 return QSsl::TlsV1_1;
1174 return QSsl::TlsV1_2;
1176 return QSsl::TlsV1_3;
1179 return QSsl::UnknownProtocol;
1184 return ocspResponses;
1192 if (sslErrors.isEmpty())
1195 emit q->sslErrors(sslErrors);
1197 const auto vfyMode = q->peerVerifyMode();
1198 const auto mode = d->tlsMode();
1200 bool doVerifyPeer = vfyMode == QSslSocket::VerifyPeer || (vfyMode == QSslSocket::AutoVerifyPeer
1201 && mode == QSslSocket::SslClientMode);
1202 bool doEmitSslError = !d->verifyErrorsHaveBeenIgnored();
1204 if (doVerifyPeer && doEmitSslError) {
1205 if (q->pauseMode() & QAbstractSocket::PauseOnSslErrors) {
1206 QSslSocketPrivate::pauseSocketNotifiers(q);
1209 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError, sslErrors.constFirst().errorString());
1210 auto *plainSocket = d->plainTcpSocket();
1211 Q_ASSERT(plainSocket);
1212 plainSocket->disconnectFromHost();
1224 Q_ASSERT(connection);
1229 if (q->sslConfiguration().testSslOption(QSsl::SslOptionDisableSessionPersistence)) {
1235 if (!currentSession) {
1236 qCWarning(lcTlsBackend,
1237 "New session ticket callback, the session is invalid (nullptr)");
1246#ifdef TLS1_3_VERSION
1247 if (!q_SSL_SESSION_is_resumable(currentSession)) {
1248 qCDebug(lcTlsBackend,
"New session ticket, but the session is non-resumable");
1254 if (sessionSize <= 0) {
1255 qCWarning(lcTlsBackend,
"could not store persistent version of SSL session");
1260 QByteArray sessionTicket(sessionSize, 0);
1261 auto data =
reinterpret_cast<
unsigned char *>(sessionTicket.data());
1262 if (!q_i2d_SSL_SESSION(currentSession, &data)) {
1263 qCWarning(lcTlsBackend,
"could not store persistent version of SSL session");
1267 QTlsBackend::setSessionAsn1(d, sessionTicket);
1268 QTlsBackend::setSessionLifetimeHint(d, q_SSL_SESSION_get_ticket_lifetime_hint(currentSession));
1270 emit q->newSessionTicketReceived();
1279 const auto level = tlsAlertLevel(value);
1280 if (level == QSsl::AlertLevel::Fatal && !q->isEncrypted()) {
1282 pendingFatalAlert =
true;
1285 emit q->alertSent(level, tlsAlertType(value), tlsAlertDescription(value));
1293 emit q->alertReceived(tlsAlertLevel(value), tlsAlertType(value), tlsAlertDescription(value));
1303 using ScopedBool = QScopedValueRollback<
bool>;
1307 const ScopedBool bg(inSetAndEmitError,
true);
1311 qCWarning(lcTlsBackend,
"Could not obtain the certificate (that failed to verify)");
1315 const QSslCertificate certificate = QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1317 const QSslError tlsError = QTlsPrivate::X509CertificateOpenSSL::openSSLErrorToQSslError(errorAndDepth.code, certificate);
1319 errorsReportedFromCallback =
true;
1320 handshakeInterrupted =
true;
1321 emit q->handshakeInterruptedOnError(tlsError);
1329 errorList->append(errorAndDepth);
1333 return !handshakeInterrupted;
1338 Q_ASSERT(pendingFatalAlert);
1341 auto *plainSocket = d->plainTcpSocket();
1343 pendingFatalAlert =
false;
1344 QVarLengthArray<
char, 4096> data;
1345 int pendingBytes = 0;
1346 while (plainSocket->isValid() && (pendingBytes =
q_BIO_pending(writeBio)) > 0
1347 && plainSocket->openMode() != QIODevice::NotOpen) {
1349 data.resize(pendingBytes);
1350 const int bioReadBytes = q_BIO_read(writeBio, data.data(), pendingBytes);
1353 qint64 actualWritten = plainSocket->write(data.constData(), bioReadBytes);
1354 if (actualWritten < 0)
1356 plainSocket->flush();
1367 const auto mode = d->tlsMode();
1368 const auto configuration = q->sslConfiguration();
1369 if (!sslContextPointer)
1370 sslContextPointer = QSslContext::sharedFromConfiguration(mode, configuration, d->isRootsOnDemandAllowed());
1372 if (sslContextPointer->error() != QSslError::NoError) {
1373 setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError, sslContextPointer->errorString());
1374 sslContextPointer.reset();
1379 if (!(ssl = sslContextPointer->createSsl())) {
1380 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1381 QSslSocket::tr(
"Error creating SSL session, %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1385 if (configuration.protocol() != QSsl::UnknownProtocol && mode == QSslSocket::SslClientMode) {
1386 const auto verificationPeerName = d->verificationName();
1388 QString tlsHostName = verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName;
1389 if (tlsHostName.isEmpty())
1390 tlsHostName = d->tlsHostName();
1391 QByteArray ace = QUrl::toAce(tlsHostName);
1394 && !QHostAddress().setAddress(tlsHostName)
1395 && !(configuration.testSslOption(QSsl::SslOptionDisableServerNameIndication))) {
1398 if (ace.endsWith(
'.'))
1400 if (!q_SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, ace.data()))
1401 qCWarning(lcTlsBackend,
"could not set SSL_CTRL_SET_TLSEXT_HOSTNAME, Server Name Indication disabled");
1411 if (!readBio || !writeBio) {
1412 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1413 QSslSocket::tr(
"Error creating SSL session: %1").arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1424 if (mode == QSslSocket::SslClientMode)
1431#ifndef OPENSSL_NO_PSK
1433 if (mode == QSslSocket::SslClientMode)
1435 else if (mode == QSslSocket::SslServerMode)
1438#if OPENSSL_VERSION_NUMBER
>= 0x10101006L
1440 if (mode == QSslSocket::SslClientMode
1441 && QSslSocket::sslLibraryBuildVersionNumber() >= 0x10101006L) {
1442 q_SSL_set_psk_use_session_callback(ssl, &q_ssl_psk_use_session_callback);
1449 if (configuration.ocspStaplingEnabled()) {
1450 if (mode == QSslSocket::SslServerMode) {
1451 setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError,
1452 QSslSocket::tr(
"Server-side QSslSocket does not support OCSP stapling"));
1455 if (q_SSL_set_tlsext_status_type(ssl, TLSEXT_STATUSTYPE_ocsp) != 1) {
1456 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1457 QSslSocket::tr(
"Failed to enable OCSP stapling"));
1462 ocspResponseDer.clear();
1463 const auto backendConfig = configuration.backendConfiguration();
1464 auto responsePos = backendConfig.find(
"Qt-OCSP-response");
1465 if (responsePos != backendConfig.end()) {
1469 const QVariant data(responsePos.value());
1470 if (data.canConvert<QByteArray>())
1471 ocspResponseDer = data.toByteArray();
1474 if (ocspResponseDer.size()) {
1475 if (mode != QSslSocket::SslServerMode) {
1476 setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError,
1477 QSslSocket::tr(
"Client-side sockets do not send OCSP responses"));
1495 const auto errors = QTlsBackendOpenSSL::getErrorsFromOpenSsl();
1502 sslContextPointer.reset();
1513 X509 *x509 = q_SSL_get_peer_certificate(ssl);
1515 const auto peerCertificate = QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1516 QTlsBackend::storePeerCertificate(d, peerCertificate);
1518 auto peerCertificateChain = q->peerCertificateChain();
1519 if (peerCertificateChain.isEmpty()) {
1520 peerCertificateChain = QTlsPrivate::X509CertificateOpenSSL::stackOfX509ToQSslCertificates(q_SSL_get_peer_cert_chain(ssl));
1521 if (!peerCertificate.isNull() && d->tlsMode() == QSslSocket::SslServerMode)
1522 peerCertificateChain.prepend(peerCertificate);
1523 QTlsBackend::storePeerCertificateChain(d, peerCertificateChain);
1709 unsigned max_identity_len,
1710 unsigned char *psk,
unsigned max_psk_len)
1714 QSslPreSharedKeyAuthenticator authenticator;
1716 const int hintLength = hint ?
int(std::strlen(hint)) : 0;
1717 QTlsBackend::setupClientPskAuth(&authenticator, hint, hintLength, max_identity_len, max_psk_len);
1719 emit q->preSharedKeyAuthenticationRequired(&authenticator);
1722 if (authenticator.preSharedKey().isEmpty())
1726 const int identityLength = qMin(authenticator.identity().size(), authenticator.maximumIdentityLength());
1727 std::memcpy(identity, authenticator.identity().constData(), identityLength);
1728 identity[identityLength] = 0;
1730 const int pskLength = qMin(authenticator.preSharedKey().size(), authenticator.maximumPreSharedKeyLength());
1731 std::memcpy(psk, authenticator.preSharedKey().constData(), pskLength);
1736 unsigned max_psk_len)
1740 QSslPreSharedKeyAuthenticator authenticator;
1743 QTlsBackend::setupServerPskAuth(&authenticator, identity, q->sslConfiguration().preSharedKeyIdentityHint(),
1745 emit q->preSharedKeyAuthenticationRequired(&authenticator);
1748 if (authenticator.preSharedKey().isEmpty())
1752 const int pskLength = qMin(authenticator.preSharedKey().size(), authenticator.maximumPreSharedKeyLength());
1753 std::memcpy(psk, authenticator.preSharedKey().constData(), pskLength);
1764 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)
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)