Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qtls_schannel.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:cryptography
4
5// #define QSSLSOCKET_DEBUG
6
11#include "../shared/qasn1element_p.h"
12
13#include <QtNetwork/private/qsslcertificate_p.h>
14#include <QtNetwork/private/qsslcipher_p.h>
15#include <QtNetwork/private/qssl_p.h>
16
17#include <QtNetwork/qsslcertificate.h>
18#include <QtNetwork/qsslcertificateextension.h>
19#include <QtNetwork/qsslsocket.h>
20
21#include <QtCore/qscopeguard.h>
22#include <QtCore/qoperatingsystemversion.h>
23#include <QtCore/qregularexpression.h>
24#include <QtCore/qdatastream.h>
25#include <QtCore/qmutex.h>
26
27#define SECURITY_WIN32
28#include <security.h>
29#include <schnlsp.h>
30
31#if NTDDI_VERSION >= NTDDI_WINBLUE && defined(SECBUFFER_APPLICATION_PROTOCOLS)
32// ALPN = Application Layer Protocol Negotiation
33#define SUPPORTS_ALPN 1
34#endif
35
36// Not defined in MinGW
37#ifndef SECBUFFER_ALERT
38#define SECBUFFER_ALERT 17
39#endif
40#ifndef SECPKG_ATTR_APPLICATION_PROTOCOL
41#define SECPKG_ATTR_APPLICATION_PROTOCOL 35
42#endif
43
44// Another missing MinGW define
45#ifndef SEC_E_APPLICATION_PROTOCOL_MISMATCH
46#define SEC_E_APPLICATION_PROTOCOL_MISMATCH _HRESULT_TYPEDEF_(0x80090367L)
47#endif
48
49// Also not defined in MinGW.......
50#ifndef SP_PROT_TLS1_SERVER
51#define SP_PROT_TLS1_SERVER 0x00000040
52#endif
53#ifndef SP_PROT_TLS1_CLIENT
54#define SP_PROT_TLS1_CLIENT 0x00000080
55#endif
56#ifndef SP_PROT_TLS1_0_SERVER
57#define SP_PROT_TLS1_0_SERVER SP_PROT_TLS1_SERVER
58#endif
59#ifndef SP_PROT_TLS1_0_CLIENT
60#define SP_PROT_TLS1_0_CLIENT SP_PROT_TLS1_CLIENT
61#endif
62#ifndef SP_PROT_TLS1_0
64#endif
65#ifndef SP_PROT_TLS1_1_SERVER
66#define SP_PROT_TLS1_1_SERVER 0x00000100
67#endif
68#ifndef SP_PROT_TLS1_1_CLIENT
69#define SP_PROT_TLS1_1_CLIENT 0x00000200
70#endif
71#ifndef SP_PROT_TLS1_1
73#endif
74#ifndef SP_PROT_TLS1_2_SERVER
75#define SP_PROT_TLS1_2_SERVER 0x00000400
76#endif
77#ifndef SP_PROT_TLS1_2_CLIENT
78#define SP_PROT_TLS1_2_CLIENT 0x00000800
79#endif
80#ifndef SP_PROT_TLS1_2
82#endif
83#ifndef SP_PROT_TLS1_3_SERVER
84#define SP_PROT_TLS1_3_SERVER 0x00001000
85#endif
86#ifndef SP_PROT_TLS1_3_CLIENT
87#define SP_PROT_TLS1_3_CLIENT 0x00002000
88#endif
89#ifndef SP_PROT_TLS1_3
91#endif
92#ifndef BCRYPT_ECDH_ALGORITHM
93#define BCRYPT_ECDH_ALGORITHM L"ECDH"
94#endif
95#ifndef BCRYPT_ECDSA_ALGORITHM
96#define BCRYPT_ECDSA_ALGORITHM L"ECDSA"
97#endif
98
99/*
100 @future!:
101
102 - Transmitting intermediate certificates
103 - Look for a way to avoid putting intermediate certificates in the certificate store
104 - No documentation on how to send the chain
105 - A stackoverflow question on this from 3 years ago implies schannel only sends intermediate
106 certificates if it's "in the system or user certificate store".
107 - https://stackoverflow.com/q/30156584/2493610
108 - This can be done by users, but we shouldn't add any and all local intermediate
109 certs to the stores automatically.
110 - PSK support
111 - Was added in Windows 10 (it seems), documentation at time of writing is sparse/non-existent.
112 - Specifically about how to supply credentials when they're requested.
113 - Or how to recognize that they're requested in the first place.
114 - Skip certificate verification.
115 - Check if "PSK-only" is still required to do PSK _at all_ (all-around bad solution).
116 - Check if SEC_I_INCOMPLETE_CREDENTIALS is still returned for both "missing certificate" and
117 "missing PSK" when calling InitializeSecurityContext in "performHandshake".
118
119 Low priority:
120 - Possibly make RAII wrappers for SecBuffer (which I commonly create QScopeGuards for)
121
122*/
123
125
126using namespace Qt::StringLiterals;
127
128Q_LOGGING_CATEGORY(lcTlsBackendSchannel, "qt.tlsbackend.schannel");
129
130// Defined in qsslsocket_qt.cpp.
131extern QByteArray _q_makePkcs12(const QList<QSslCertificate> &certs, const QSslKey &key,
132 const QString &passPhrase);
133extern QAsn1Element _q_PKCS12_key(const QSslKey &key);
134
135namespace {
136bool supportsTls13();
137}
138
139namespace QTlsPrivate {
140
142
153
154// The list of supported ciphers according to
155// https://learn.microsoft.com/en-us/windows/win32/secauthn/tls-cipher-suites-in-windows-server-2022
156QT_WARNING_PUSH
157QT_WARNING_DISABLE_DEPRECATED
159 {"TLS_AES_256_GCM_SHA384", "TLS_AES_256_GCM_SHA384", "", "", "AES", 256, "SHA384", {QSsl::TlsV1_3}},
160 {"TLS_AES_128_GCM_SHA256", "TLS_AES_128_GCM_SHA256", "", "", "AES", 128, "SHA256", {QSsl::TlsV1_3}},
161 {"ECDHE-ECDSA-AES256-GCM-SHA384", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "ECDH", "ECDSA", "AES", 256, "SHA384", {QSsl::TlsV1_2}},
162 {"ECDHE-ECDSA-AES128-GCM-SHA256", "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "ECDH", "ECDSA", "AES", 128, "SHA256", {QSsl::TlsV1_2}},
163 {"ECDHE-RSA-AES256-GCM-SHA384", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "ECDH", "RSA", "AES", 256, "SHA384", {QSsl::TlsV1_2}},
164 {"ECDHE-RSA-AES128-GCM-SHA256", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "ECDH", "RSA", "AES", 128, "SHA256", {QSsl::TlsV1_2}},
165 {"DHE-RSA-AES256-GCM-SHA384", "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", "DH", "RSA", "AES", 256, "SHA384", {QSsl::TlsV1_2}},
166 {"DHE-RSA-AES128-GCM-SHA256", "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", "DH", "RSA", "AES", 128, "SHA256", {QSsl::TlsV1_2}},
167 {"ECDHE-ECDSA-AES256-SHA384", "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "ECDH", "ECDSA", "AES", 256, "SHA384", {QSsl::TlsV1_2}},
168 {"ECDHE-ECDSA-AES128-SHA256", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "ECDH", "ECDSA", "AES", 128, "SHA256", {QSsl::TlsV1_2}},
169 {"ECDHE-RSA-AES256-SHA384", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", "ECDH", "RSA", "AES", 256, "SHA384", {QSsl::TlsV1_2}},
170 {"ECDHE-RSA-AES128-SHA256", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", "ECDH", "RSA", "AES", 128, "SHA256", {QSsl::TlsV1_2}},
171 {"ECDHE-ECDSA-AES256-SHA", "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", "ECDH", "ECDSA", "AES", 256, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
172 {"ECDHE-ECDSA-AES128-SHA", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", "ECDH", "ECDSA", "AES", 128, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
173 {"ECDHE-RSA-AES256-SHA", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", "ECDH", "RSA", "AES", 256, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
174 {"ECDHE-RSA-AES128-SHA", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", "ECDH", "RSA", "AES", 128, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
175 {"AES256-GCM-SHA384", "TLS_RSA_WITH_AES_256_GCM_SHA384", "RSA", "RSA", "AES", 256, "SHA384", {QSsl::TlsV1_2}},
176 {"AES128-GCM-SHA256", "TLS_RSA_WITH_AES_128_GCM_SHA256", "RSA", "RSA", "AES", 128, "SHA256", {QSsl::TlsV1_2}},
177 {"AES256-SHA256", "TLS_RSA_WITH_AES_256_CBC_SHA256", "RSA", "RSA", "AES", 256, "SHA256", {QSsl::TlsV1_2}},
178 {"AES128-SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA256", "RSA", "RSA", "AES", 128, "SHA256", {QSsl::TlsV1_2}},
179 {"AES256-SHA", "TLS_RSA_WITH_AES_256_CBC_SHA", "RSA", "RSA", "AES", 256, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
180 {"AES128-SHA", "TLS_RSA_WITH_AES_128_CBC_SHA", "RSA", "RSA", "AES", 128, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
181 {"DES-CBC3-SHA", "TLS_RSA_WITH_3DES_EDE_CBC_SHA", "RSA", "RSA", "3DES", 168, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
182 {"NULL-SHA256", "TLS_RSA_WITH_NULL_SHA256", "RSA", "RSA", "", 0, "SHA256", {QSsl::TlsV1_2}},
183 {"NULL-SHA", "TLS_RSA_WITH_NULL_SHA", "RSA", "RSA", "", 0, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
184
185 // the following cipher suites are not enabled by default in schannel provider
186 {"TLS_CHACHA20_POLY1305_SHA256", "TLS_CHACHA20_POLY1305_SHA256", "", "", "CHACHA20_POLY1305", 0, "", {QSsl::TlsV1_3}},
187 {"DHE-RSA-AES256-SHA", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "DH", "RSA", "AES", 256, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
188 {"DHE-RSA-AES128-SHA", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "DH", "RSA", "AES", 128, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
189 {"DHE-DSS-AES256-SHA256", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", "DH", "DSA", "AES", 256, "SHA256", {QSsl::TlsV1_2}},
190 {"DHE-DSS-AES128-SHA256", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", "DH", "DSA", "AES", 128, "SHA256", {QSsl::TlsV1_2}},
191 {"DHE-DSS-AES256-SHA", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", "DH", "DSA", "AES", 256, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
192 {"DHE-DSS-AES128-SHA", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", "DH", "DSA", "AES", 128, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
193 {"EDH-DSS-DES-CBC3-SHA", "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", "DH", "DSA", "3DES", 168, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
194 {"RC4-SHA", "TLS_RSA_WITH_RC4_128_SHA", "RSA", "RSA", "RC4", 128, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
195 {"RC4-MD5", "TLS_RSA_WITH_RC4_128_MD5", "RSA", "RSA", "RC4", 128, "MD5", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
196 {"DES-CBC-SHA", "TLS_RSA_WITH_DES_CBC_SHA", "RSA", "RSA", "DES", 56, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
197 {"EDH-DSS-DES-CBC-SHA", "TLS_DHE_DSS_WITH_DES_CBC_SHA", "DH", "DSA", "DES", 56, "SHA1", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
198 {"NULL-MD5", "TLS_RSA_WITH_NULL_MD5", "RSA", "RSA", "", 0, "MD5", {QSsl::TlsV1_2, QSsl::TlsV1_1, QSsl::TlsV1_0}},
199
200 // PSK cipher suites
201 {"PSK-AES256-GCM-SHA384", "TLS_PSK_WITH_AES_256_GCM_SHA384", "PSK", "", "AES", 256, "SHA384", {QSsl::TlsV1_2}},
202 {"PSK-AES128-GCM-SHA256", "TLS_PSK_WITH_AES_128_GCM_SHA256", "PSK", "", "AES", 128, "SHA256", {QSsl::TlsV1_2}},
203 {"PSK-AES256-CBC-SHA384", "TLS_PSK_WITH_AES_256_CBC_SHA384", "PSK", "", "AES", 256, "SHA384", {QSsl::TlsV1_2}},
204 {"PSK-AES128-CBC-SHA256", "TLS_PSK_WITH_AES_128_CBC_SHA256", "PSK", "", "AES", 128, "SHA256", {QSsl::TlsV1_2}},
205 {"PSK-NULL-SHA384", "TLS_PSK_WITH_NULL_SHA384", "PSK", "", "", 0, "SHA384", {QSsl::TlsV1_2}},
206 {"PSK-NULL-SHA256", "TLS_PSK_WITH_NULL_SHA256", "PSK", "", "", 0, "SHA256", {QSsl::TlsV1_2}},
207}};
208QT_WARNING_POP
209
210const SchannelCipherInfo *cipherInfoByOpenSslName(const QString &name)
211{
212 for (const auto &cipherInfo : schannelCipherInfo) {
214 return &cipherInfo;
215 }
216
217 return nullptr;
218}
219
225
231
232/**
233 Determines which algorithms are not used by the requested ciphers to build
234 up a black list that can be passed to SCH_CREDENTIALS.
235 */
236QList<CRYPTO_SETTINGS> cryptoSettingsForCiphers(const QList<QSslCipher> &ciphers)
237{
238 static const QList<QSslCipher> defaultCipherList = defaultCiphers();
239
240 if (defaultCipherList == ciphers) {
241 // the ciphers have not been restricted for this session, so no black listing needed
242 return {};
243 }
244
245 QList<const SchannelCipherInfo*> cipherInfo;
246
247 for (const auto &cipher : ciphers) {
248 if (cipher.isNull())
249 continue;
250
251 const auto *info = cipherInfoByOpenSslName(cipher.name());
252 if (!cipherInfo.contains(info))
253 cipherInfo.append(info);
254 }
255
256 QList<CRYPTO_SETTINGS> cryptoSettings;
257
258 const auto assignUnicodeString = [](UNICODE_STRING &unicodeString, const wchar_t *characters) {
259 unicodeString.Length = static_cast<USHORT>(wcslen(characters) * sizeof(WCHAR));
260 unicodeString.MaximumLength = unicodeString.Length + sizeof(UNICODE_NULL);
261 unicodeString.Buffer = const_cast<wchar_t*>(characters);
262 };
263
264 // black list of key exchange algorithms
265 const auto allKeyExchangeAlgorithms = {BCRYPT_RSA_ALGORITHM,
267 BCRYPT_DH_ALGORITHM};
268
269 for (const auto &algorithm : allKeyExchangeAlgorithms) {
270 const auto method = QStringView(algorithm);
271
272 const auto usesMethod = [method](const SchannelCipherInfo *info) {
273 return QLatin1StringView(info->keyExchangeMethod) == method;
274 };
275
276 const bool exclude = std::none_of(cipherInfo.cbegin(), cipherInfo.cend(), usesMethod);
277
278 if (exclude) {
279 CRYPTO_SETTINGS settings = {};
280 settings.eAlgorithmUsage = TlsParametersCngAlgUsageKeyExchange;
281 assignUnicodeString(settings.strCngAlgId, algorithm);
282 cryptoSettings.append(settings);
283 }
284 }
285
286 // black list of authentication algorithms
287 const auto allAuthenticationAlgorithms = {BCRYPT_RSA_ALGORITHM,
288 BCRYPT_DSA_ALGORITHM,
290 BCRYPT_DH_ALGORITHM};
291
292 for (const auto &algorithm : allAuthenticationAlgorithms) {
293 const auto method = QStringView(algorithm);
294
295 const auto usesMethod = [method](const SchannelCipherInfo *info) {
296 return QLatin1StringView(info->authenticationMethod) == method;
297 };
298
299 const bool exclude = std::none_of(cipherInfo.begin(), cipherInfo.end(), usesMethod);
300
301 if (exclude) {
302 CRYPTO_SETTINGS settings = {};
303 settings.eAlgorithmUsage = TlsParametersCngAlgUsageSignature;
304 assignUnicodeString(settings.strCngAlgId, algorithm);
305 cryptoSettings.append(settings);
306 }
307 }
308
309
310 // black list of encryption algorithms
311 const auto allEncryptionAlgorithms = {BCRYPT_AES_ALGORITHM,
312 BCRYPT_RC4_ALGORITHM,
313 BCRYPT_DES_ALGORITHM,
314 BCRYPT_3DES_ALGORITHM};
315
316 for (const auto &algorithm : allEncryptionAlgorithms) {
317 const auto method = QStringView(algorithm);
318
319 if (method == QLatin1StringView("AES")) {
320 bool uses128Bit = false;
321 bool uses256Bit = false;
322 bool usesGcm = false;
323 bool usesCbc = false;
324 for (const auto *info : cipherInfo) {
325 if (QLatin1StringView(info->encryptionMethod) == method) {
326 uses128Bit = uses128Bit || (info->encryptionBits == 128);
327 uses256Bit = uses256Bit || (info->encryptionBits == 256);
328 usesGcm = usesGcm ||
329 QLatin1StringView(info->schannelCipherSuite).contains("_GCM_"_L1);
330 usesCbc = usesCbc ||
331 QLatin1StringView(info->schannelCipherSuite).contains("_CBC_"_L1);
332 }
333 }
334
335 CRYPTO_SETTINGS settings = {};
336 settings.eAlgorithmUsage = TlsParametersCngAlgUsageCipher;
337 assignUnicodeString(settings.strCngAlgId, algorithm);
338
339 if (usesGcm && !usesCbc) {
340 settings.cChainingModes = 1;
341 settings.rgstrChainingModes = &cbcChainingMode;
342 } else if (!usesGcm && usesCbc) {
343 settings.cChainingModes = 1;
344 settings.rgstrChainingModes = &gcmChainingMode;
345 }
346
347 if (!uses128Bit && uses256Bit) {
348 settings.dwMinBitLength = 256;
349 cryptoSettings.append(settings);
350 } else if (uses128Bit && !uses256Bit) {
351 settings.dwMaxBitLength = 128;
352 cryptoSettings.append(settings);
353 } else if (!uses128Bit && !uses256Bit) {
354 cryptoSettings.append(settings);
355 }
356 } else {
357 const auto usesMethod = [method](const SchannelCipherInfo *info) {
358 return QLatin1StringView(info->encryptionMethod) == method;
359 };
360
361 const bool exclude = std::none_of(cipherInfo.begin(), cipherInfo.end(), usesMethod);
362
363 if (exclude) {
364 CRYPTO_SETTINGS settings = {};
365 settings.eAlgorithmUsage = TlsParametersCngAlgUsageCipher;
366 assignUnicodeString(settings.strCngAlgId, algorithm);
367 cryptoSettings.append(settings);
368 }
369 }
370 }
371
372 // black list of hash algorithms
373 const auto allHashAlgorithms = {BCRYPT_MD5_ALGORITHM,
374 BCRYPT_SHA1_ALGORITHM,
375 BCRYPT_SHA256_ALGORITHM,
376 BCRYPT_SHA384_ALGORITHM};
377
378 for (const auto &algorithm : allHashAlgorithms) {
379 const auto method = QStringView(algorithm);
380
381 const auto usesMethod = [method](const SchannelCipherInfo *info) {
382 return QLatin1StringView(info->hashMethod) == method;
383 };
384
385 const bool exclude = std::none_of(cipherInfo.begin(), cipherInfo.end(), usesMethod);
386
387 if (exclude) {
388 CRYPTO_SETTINGS settings = {};
389 settings.eAlgorithmUsage = TlsParametersCngAlgUsageDigest;
390 assignUnicodeString(settings.strCngAlgId, algorithm);
391 cryptoSettings.append(settings);
392 }
393 }
394
395 return cryptoSettings;
396}
397
398QList<QSslCipher> ciphersByName(QStringView schannelSuiteName)
399{
400 QList<QSslCipher> ciphers;
401
402 for (const auto &cipher : schannelCipherInfo) {
403 if (QLatin1StringView(cipher.schannelCipherSuite) == schannelSuiteName) {
404 for (const auto &protocol : cipher.protocols) {
405QT_WARNING_PUSH
406QT_WARNING_DISABLE_DEPRECATED
407 const QString protocolName = (
408 protocol == QSsl::TlsV1_0 ? QStringLiteral("TLSv1.0") :
409 protocol == QSsl::TlsV1_1 ? QStringLiteral("TLSv1.1") :
410 protocol == QSsl::TlsV1_2 ? QStringLiteral("TLSv1.2") :
411 protocol == QSsl::TlsV1_3 ? QStringLiteral("TLSv1.3") :
412 QString());
413QT_WARNING_POP
414
415 ciphers.append(QTlsBackend::createCiphersuite(QLatin1StringView(cipher.openSslCipherSuite),
416 QLatin1StringView(cipher.keyExchangeMethod),
417 QLatin1StringView(cipher.encryptionMethod),
418 QLatin1StringView(cipher.authenticationMethod),
419 cipher.encryptionBits,
420 protocol, protocolName));
421 }
422 }
423 }
424
425 return ciphers;
426}
427
429{
430 ULONG contextFunctionsCount = {};
431 PCRYPT_CONTEXT_FUNCTIONS contextFunctions = {};
432
433 const auto status = BCryptEnumContextFunctions(CRYPT_LOCAL, L"SSL", NCRYPT_SCHANNEL_INTERFACE,
434 &contextFunctionsCount, &contextFunctions);
435 if (!NT_SUCCESS(status)) {
436 qCWarning(lcTlsBackendSchannel, "Failed to enumerate ciphers");
437 return {};
438 }
439
440 const bool supportsV13 = supportsTls13();
441
442 QList<QSslCipher> ciphers;
443
444 for (ULONG index = 0; index < contextFunctions->cFunctions; ++index) {
445 const auto suiteName = QStringView(contextFunctions->rgpszFunctions[index]);
446
447 const QList<QSslCipher> allCiphers = ciphersByName(suiteName);
448
449 for (const auto &cipher : allCiphers) {
450 if (!supportsV13 && (cipher.protocol() == QSsl::TlsV1_3))
451 continue;
452
453 ciphers.append(cipher);
454 }
455 }
456
457 BCryptFreeBuffer(contextFunctions);
458
459 return ciphers;
460}
461
462bool containsTls13Cipher(const QList<QSslCipher> &ciphers)
463{
464 return std::any_of(ciphers.cbegin(), ciphers.cend(),
465 [](const QSslCipher &cipher) { return cipher.protocol() == QSsl::TlsV1_3; });
466}
467
468} // namespace QTlsPrivate
469
470bool QSchannelBackend::s_loadedCiphersAndCerts = false;
472
473long QSchannelBackend::tlsLibraryVersionNumber() const
474{
475 const auto os = QOperatingSystemVersion::current();
476 return (os.majorVersion() << 24) | ((os.minorVersion() & 0xFF) << 16) | (os.microVersion() & 0xFFFF);
477}
478
479QString QSchannelBackend::tlsLibraryVersionString() const
480{
481 const auto os = QOperatingSystemVersion::current();
482 return "Secure Channel, %1 %2.%3.%4"_L1
483 .arg(os.name(),
484 QString::number(os.majorVersion()),
485 QString::number(os.minorVersion()),
486 QString::number(os.microVersion()));
487}
488
489long QSchannelBackend::tlsLibraryBuildVersionNumber() const
490{
491 return NTDDI_VERSION;
492}
493
494QString QSchannelBackend::tlsLibraryBuildVersionString() const
495{
496 return "Secure Channel (NTDDI: 0x%1)"_L1
497 .arg(QString::number(NTDDI_VERSION, 16).toUpper());
498}
499
500void QSchannelBackend::ensureInitialized() const
501{
502 ensureInitializedImplementation();
503}
504
505void QSchannelBackend::ensureInitializedImplementation()
506{
507 const QMutexLocker<QRecursiveMutex> locker(qt_schannel_mutex);
508 if (s_loadedCiphersAndCerts)
509 return;
510 s_loadedCiphersAndCerts = true;
511
512 setDefaultCaCertificates(systemCaCertificatesImplementation());
513 // setDefaultCaCertificates sets it to false, re-enable it:
514 QSslSocketPrivate::setRootCertOnDemandLoadingSupported(true);
515
516 resetDefaultCiphers();
517}
518
519void QSchannelBackend::resetDefaultCiphers()
520{
521 setDefaultSupportedCiphers(QTlsPrivate::defaultCiphers());
522 setDefaultCiphers(QTlsPrivate::defaultCiphers());
523}
524
525QString QSchannelBackend::backendName() const
526{
527 return builtinBackendNames[nameIndexSchannel];
528}
529
530QList<QSsl::SslProtocol> QSchannelBackend::supportedProtocols() const
531{
532 QList<QSsl::SslProtocol> protocols;
533
534 protocols << QSsl::AnyProtocol;
535 protocols << QSsl::SecureProtocols;
536QT_WARNING_PUSH
537QT_WARNING_DISABLE_DEPRECATED
538 protocols << QSsl::TlsV1_0;
539 protocols << QSsl::TlsV1_0OrLater;
540 protocols << QSsl::TlsV1_1;
541 protocols << QSsl::TlsV1_1OrLater;
542QT_WARNING_POP
543 protocols << QSsl::TlsV1_2;
544 protocols << QSsl::TlsV1_2OrLater;
545
546 if (supportsTls13()) {
547 protocols << QSsl::TlsV1_3;
548 protocols << QSsl::TlsV1_3OrLater;
549 }
550
551 return protocols;
552}
553
554QList<QSsl::SupportedFeature> QSchannelBackend::supportedFeatures() const
555{
556 QList<QSsl::SupportedFeature> features;
557
558#ifdef SUPPORTS_ALPN
559 features << QSsl::SupportedFeature::ClientSideAlpn;
560 features << QSsl::SupportedFeature::ServerSideAlpn;
561#endif
562
563 return features;
564}
565
566QList<QSsl::ImplementedClass> QSchannelBackend::implementedClasses() const
567{
568 QList<QSsl::ImplementedClass> classes;
569
570 classes << QSsl::ImplementedClass::Socket;
571 classes << QSsl::ImplementedClass::Certificate;
572 classes << QSsl::ImplementedClass::Key;
573
574 return classes;
575}
576
577QTlsPrivate::TlsKey *QSchannelBackend::createKey() const
578{
579 return new QTlsPrivate::TlsKeySchannel;
580}
581
582QTlsPrivate::X509Certificate *QSchannelBackend::createCertificate() const
583{
585}
586
587QList<QSslCertificate> QSchannelBackend::systemCaCertificates() const
588{
589 return systemCaCertificatesImplementation();
590}
591
592QTlsPrivate::TlsCryptograph *QSchannelBackend::createTlsCryptograph() const
593{
595}
596
597QList<QSslCertificate> QSchannelBackend::systemCaCertificatesImplementation()
598{
599 // Similar to non-Darwin version found in qtlsbackend_openssl.cpp,
600 // QTlsPrivate::systemCaCertificates function.
601 QList<QSslCertificate> systemCerts;
602
603 auto hSystemStore = QHCertStorePointer(
604 CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0,
605 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER, L"ROOT"));
606
607 if (hSystemStore) {
608 PCCERT_CONTEXT pc = nullptr;
609 while ((pc = CertFindCertificateInStore(hSystemStore.get(), X509_ASN_ENCODING, 0,
610 CERT_FIND_ANY, nullptr, pc))) {
611 systemCerts.append(QTlsPrivate::X509CertificateSchannel::QSslCertificate_from_CERT_CONTEXT(pc));
612 }
613 }
614 return systemCerts;
615}
616
617QTlsPrivate::X509PemReaderPtr QSchannelBackend::X509PemReader() const
618{
619 return QTlsPrivate::X509CertificateGeneric::certificatesFromPem;
620}
621
622QTlsPrivate::X509DerReaderPtr QSchannelBackend::X509DerReader() const
623{
624 return QTlsPrivate::X509CertificateGeneric::certificatesFromDer;
625}
626
627QTlsPrivate::X509Pkcs12ReaderPtr QSchannelBackend::X509Pkcs12Reader() const
628{
629 return QTlsPrivate::X509CertificateSchannel::importPkcs12;
630}
631
632namespace {
633
634SecBuffer createSecBuffer(void *ptr, unsigned long length, unsigned long bufferType)
635{
636 return SecBuffer{ length, bufferType, ptr };
637}
638
639SecBuffer createSecBuffer(QByteArray &buffer, unsigned long bufferType)
640{
641 return createSecBuffer(buffer.data(), static_cast<unsigned long>(buffer.length()), bufferType);
642}
643
644QString schannelErrorToString(qint32 status)
645{
646 switch (status) {
647 case SEC_E_INSUFFICIENT_MEMORY:
648 return QSslSocket::tr("Insufficient memory");
649 case SEC_E_INTERNAL_ERROR:
650 return QSslSocket::tr("Internal error");
651 case SEC_E_INVALID_HANDLE:
652 return QSslSocket::tr("An internal handle was invalid");
653 case SEC_E_INVALID_TOKEN:
654 return QSslSocket::tr("An internal token was invalid");
655 case SEC_E_LOGON_DENIED:
656 // According to the link below we get this error when Schannel receives TLS1_ALERT_ACCESS_DENIED
657 // https://docs.microsoft.com/en-us/windows/desktop/secauthn/schannel-error-codes-for-tls-and-ssl-alerts
658 return QSslSocket::tr("Access denied");
659 case SEC_E_NO_AUTHENTICATING_AUTHORITY:
660 return QSslSocket::tr("No authority could be contacted for authorization");
661 case SEC_E_NO_CREDENTIALS:
662 return QSslSocket::tr("No credentials");
663 case SEC_E_TARGET_UNKNOWN:
664 return QSslSocket::tr("The target is unknown or unreachable");
665 case SEC_E_UNSUPPORTED_FUNCTION:
666 return QSslSocket::tr("An unsupported function was requested");
667 case SEC_E_WRONG_PRINCIPAL:
668 // SNI error
669 return QSslSocket::tr("The hostname provided does not match the one received from the peer");
671 return QSslSocket::tr("No common protocol exists between the client and the server");
672 case SEC_E_ILLEGAL_MESSAGE:
673 return QSslSocket::tr("Unexpected or badly-formatted message received");
674 case SEC_E_ENCRYPT_FAILURE:
675 return QSslSocket::tr("The data could not be encrypted");
676 case SEC_E_DECRYPT_FAILURE:
677 return QSslSocket::tr("The data could not be decrypted");
678 case SEC_E_ALGORITHM_MISMATCH:
679 return QSslSocket::tr("No cipher suites in common");
680 case SEC_E_UNKNOWN_CREDENTIALS:
681 // This can mean "invalid argument" in some cases...
682 return QSslSocket::tr("The credentials were not recognized / Invalid argument");
683 case SEC_E_MESSAGE_ALTERED:
684 // According to the Internet it also triggers for messages that are out of order.
685 // https://microsoft.public.platformsdk.security.narkive.com/4JAvlMvD/help-please-schannel-security-contexts-and-decryptmessage
686 return QSslSocket::tr("The message was tampered with, damaged or out of sequence.");
687 case SEC_E_OUT_OF_SEQUENCE:
688 return QSslSocket::tr("A message was received out of sequence.");
689 case SEC_E_CONTEXT_EXPIRED:
690 return QSslSocket::tr("The TLS/SSL connection has been closed");
691 default:
692 return QSslSocket::tr("Unknown error occurred: %1").arg(status);
693 }
694}
695
696bool supportsTls13()
697{
698 static bool supported = []() {
699 const auto current = QOperatingSystemVersion::current();
700 // 20221 just happens to be the preview version I run on my laptop where I tested TLS 1.3.
701 const auto minimum =
702 QOperatingSystemVersion(QOperatingSystemVersion::Windows, 10, 0, 20221);
703 return current >= minimum;
704 }();
705
706 return supported;
707}
708
709DWORD toSchannelProtocol(QSsl::SslProtocol protocol)
710{
711 DWORD protocols = SP_PROT_NONE;
712 switch (protocol) {
713 case QSsl::UnknownProtocol:
714 return DWORD(-1);
715QT_WARNING_PUSH
716QT_WARNING_DISABLE_DEPRECATED
717 case QSsl::DtlsV1_0:
718 case QSsl::DtlsV1_0OrLater:
719QT_WARNING_POP
720 case QSsl::DtlsV1_2:
721 case QSsl::DtlsV1_2OrLater:
722 return DWORD(-1); // Not supported at the moment (@future)
723 case QSsl::AnyProtocol:
725 if (supportsTls13())
726 protocols |= SP_PROT_TLS1_3;
727 break;
728QT_WARNING_PUSH
729QT_WARNING_DISABLE_DEPRECATED
730 case QSsl::TlsV1_0:
731 protocols = SP_PROT_TLS1_0;
732 break;
733 case QSsl::TlsV1_1:
734 protocols = SP_PROT_TLS1_1;
735 break;
736QT_WARNING_POP
737 case QSsl::TlsV1_2:
738 protocols = SP_PROT_TLS1_2;
739 break;
740 case QSsl::TlsV1_3:
741 if (supportsTls13())
742 protocols = SP_PROT_TLS1_3;
743 else
744 protocols = DWORD(-1);
745 break;
746QT_WARNING_PUSH
747QT_WARNING_DISABLE_DEPRECATED
748 case QSsl::TlsV1_0OrLater:
749 // For the "OrLater" protocols we fall through from one to the next, adding all of them
750 // in ascending order
751 protocols = SP_PROT_TLS1_0;
752 Q_FALLTHROUGH();
753 case QSsl::TlsV1_1OrLater:
754 protocols |= SP_PROT_TLS1_1;
755 Q_FALLTHROUGH();
756QT_WARNING_POP
757 case QSsl::SecureProtocols: // TLS v1.2 and later is currently considered secure
758 case QSsl::TlsV1_2OrLater:
759 protocols |= SP_PROT_TLS1_2;
760 Q_FALLTHROUGH();
761 case QSsl::TlsV1_3OrLater:
762 if (supportsTls13())
763 protocols |= SP_PROT_TLS1_3;
764 else if (protocol == QSsl::TlsV1_3OrLater)
765 protocols = DWORD(-1); // if TlsV1_3OrLater was specifically chosen we should fail
766 break;
767 }
768 return protocols;
769}
770
771// In the new API that descended down upon us we are not asked which protocols we want
772// but rather which protocols we don't want. So now we have this function to disable
773// anything that is not enabled.
774DWORD negatedSchannelProtocols(DWORD wantedProtocols)
775{
776 DWORD protocols = SP_PROT_ALL; // all protocols
777 protocols &= ~wantedProtocols; // minus the one(s) we want
778 return protocols;
779}
780
781/*!
782 \internal
783 Used when converting the established session's \a protocol back to
784 Qt's own SslProtocol type.
785
786 Only one protocol should be passed in at a time.
787*/
788QSsl::SslProtocol toQtSslProtocol(DWORD protocol)
789{
790#define MAP_PROTOCOL(sp_protocol, q_protocol)
791 if (protocol & sp_protocol) {
792 Q_ASSERT(!(protocol & ~sp_protocol));
793 return q_protocol;
794 }
795
796QT_WARNING_PUSH
797QT_WARNING_DISABLE_DEPRECATED
798 MAP_PROTOCOL(SP_PROT_TLS1_0, QSsl::TlsV1_0)
799 MAP_PROTOCOL(SP_PROT_TLS1_1, QSsl::TlsV1_1)
800QT_WARNING_POP
801 MAP_PROTOCOL(SP_PROT_TLS1_2, QSsl::TlsV1_2)
802 MAP_PROTOCOL(SP_PROT_TLS1_3, QSsl::TlsV1_3)
803#undef MAP_PROTOCOL
804 Q_UNREACHABLE();
805 return QSsl::UnknownProtocol;
806}
807
808/*!
809 \internal
810 Used by verifyCertContext to check if a client cert is used by a server or vice versa.
811*/
812bool netscapeWrongCertType(const QList<QSslCertificateExtension> &extensions, bool isClient, bool isLeaf)
813{
814 const auto netscapeIt = std::find_if(
815 extensions.cbegin(), extensions.cend(),
816 [](const QSslCertificateExtension &extension) {
817 return extension.oid() == u"2.16.840.1.113730.1.1";
818 });
819 if (netscapeIt != extensions.cend()) {
820 const QByteArray netscapeCertTypeByte = netscapeIt->value().toByteArray();
821 int netscapeCertType = 0;
822 QDataStream dataStream(netscapeCertTypeByte);
823 dataStream >> netscapeCertType;
824 if (dataStream.status() != QDataStream::Status::Ok)
825 return true;
826 const int expectedPeerCertType = [&]() {
827 if (isLeaf) {
828 return isClient ? NETSCAPE_SSL_SERVER_AUTH_CERT_TYPE
829 : NETSCAPE_SSL_CLIENT_AUTH_CERT_TYPE;
830 }
831 return NETSCAPE_SSL_CA_CERT_TYPE;
832 }();
833 if ((netscapeCertType & expectedPeerCertType) == 0)
834 return true;
835 }
836 return false;
837}
838
839/*!
840 \internal
841 Used by verifyCertContext to check the basicConstraints certificate
842 extension to see if the certificate is a certificate authority.
843 Returns false if the certificate does not have the basicConstraints
844 extension or if it is not a certificate authority.
845*/
846bool isCertificateAuthority(const QList<QSslCertificateExtension> &extensions)
847{
848 auto it = std::find_if(extensions.cbegin(), extensions.cend(),
849 [](const QSslCertificateExtension &extension) {
850 return extension.name() == "basicConstraints"_L1;
851 });
852 if (it != extensions.cend()) {
853 QVariantMap basicConstraints = it->value().toMap();
854 return basicConstraints.value("ca"_L1, false).toBool();
855 }
856 return false;
857}
858
859/*!
860 \internal
861 Returns true if the attributes we requested from the context/handshake have
862 been given.
863*/
864bool matchesContextRequirements(DWORD attributes, DWORD requirements,
865 QSslSocket::PeerVerifyMode verifyMode,
866 bool isClient)
867{
868#ifdef QSSLSOCKET_DEBUG
869#define DEBUG_WARN(message) qCWarning(lcTlsBackendSchannel, message)
870#else
871#define DEBUG_WARN(message)
872#endif
873
874#define CHECK_ATTRIBUTE(attributeName)
875 do {
876 const DWORD req##attributeName = isClient ? ISC_REQ_##attributeName : ASC_REQ_##attributeName;
877 const DWORD ret##attributeName = isClient ? ISC_RET_##attributeName : ASC_RET_##attributeName;
878 if (!(requirements & req##attributeName) != !(attributes & ret##attributeName)) {
879 DEBUG_WARN("Missing attribute \"" #attributeName "\"");
880 return false;
881 }
882 } while (false)
883
884 CHECK_ATTRIBUTE(CONFIDENTIALITY);
885 CHECK_ATTRIBUTE(REPLAY_DETECT);
886 CHECK_ATTRIBUTE(SEQUENCE_DETECT);
887 CHECK_ATTRIBUTE(STREAM);
888 if (verifyMode == QSslSocket::PeerVerifyMode::VerifyPeer)
889 CHECK_ATTRIBUTE(MUTUAL_AUTH);
890
891 // This one is manual because there is no server / ASC_ version
892 if (isClient) {
893 const auto reqManualCredValidation = ISC_REQ_MANUAL_CRED_VALIDATION;
894 const auto retManualCredValidation = ISC_RET_MANUAL_CRED_VALIDATION;
895 if (!(requirements & reqManualCredValidation) != !(attributes & retManualCredValidation)) {
896 DEBUG_WARN("Missing attribute \"MANUAL_CRED_VALIDATION\"");
897 return false;
898 }
899 }
900
901 return true;
902#undef CHECK_ATTRIBUTE
903#undef DEBUG_WARN
904}
905
906template<typename Required, typename Actual>
907Required const_reinterpret_cast(Actual *p)
908{
909 return Required(p);
910}
911
912#ifdef SUPPORTS_ALPN
913QByteArray createAlpnString(const QByteArrayList &nextAllowedProtocols)
914{
915 QByteArray alpnString;
916 if (!nextAllowedProtocols.isEmpty()) {
917 const QByteArray names = [&nextAllowedProtocols]() {
918 QByteArray protocolString;
919 for (QByteArray proto : nextAllowedProtocols) {
920 if (proto.size() > 255) {
921 qCWarning(lcTlsBackendSchannel)
922 << "TLS ALPN extension" << proto << "is too long and will be ignored.";
923 continue;
924 } else if (proto.isEmpty()) {
925 continue;
926 }
927 protocolString += char(proto.length()) + proto;
928 }
929 return protocolString;
930 }();
931 if (names.isEmpty())
932 return alpnString;
933
934 const quint16 namesSize = names.size();
935 const quint32 alpnId = SecApplicationProtocolNegotiationExt_ALPN;
936 const quint32 totalSize = sizeof(alpnId) + sizeof(namesSize) + namesSize;
937 alpnString = QByteArray::fromRawData(reinterpret_cast<const char *>(&totalSize), sizeof(totalSize))
938 + QByteArray::fromRawData(reinterpret_cast<const char *>(&alpnId), sizeof(alpnId))
939 + QByteArray::fromRawData(reinterpret_cast<const char *>(&namesSize), sizeof(namesSize))
940 + names;
941 }
942 return alpnString;
943}
944#endif // SUPPORTS_ALPN
945
946qint64 readToBuffer(QByteArray &buffer, QTcpSocket *plainSocket)
947{
948 Q_ASSERT(plainSocket);
949 static const qint64 shrinkCutoff = 1024 * 12;
950 static const qint64 defaultRead = 1024 * 16;
951 qint64 bytesRead = 0;
952
953 const auto toRead = std::min(defaultRead, plainSocket->bytesAvailable());
954 if (toRead > 0) {
955 const auto bufferSize = buffer.size();
956 buffer.reserve(bufferSize + toRead); // avoid growth strategy kicking in
957 buffer.resize(bufferSize + toRead);
958 bytesRead = plainSocket->read(buffer.data() + bufferSize, toRead);
959 buffer.resize(bufferSize + bytesRead);
960 // In case of excessive memory usage we shrink:
961 if (buffer.size() < shrinkCutoff && buffer.capacity() > defaultRead)
962 buffer.shrink_to_fit();
963 }
964
965 return bytesRead;
966}
967
968void retainExtraData(QByteArray &buffer, const SecBuffer &secBuffer)
969{
970 Q_ASSERT(secBuffer.BufferType == SECBUFFER_EXTRA);
971 if (int(secBuffer.cbBuffer) >= buffer.size())
972 return;
973
974#ifdef QSSLSOCKET_DEBUG
975 qCDebug(lcTlsBackendSchannel, "We got SECBUFFER_EXTRA, will retain %lu bytes",
976 secBuffer.cbBuffer);
977#endif
978 std::move(buffer.end() - secBuffer.cbBuffer, buffer.end(), buffer.begin());
979 buffer.resize(secBuffer.cbBuffer);
980}
981
982qint64 checkIncompleteData(const SecBuffer &secBuffer)
983{
984 if (secBuffer.BufferType == SECBUFFER_MISSING) {
985#ifdef QSSLSOCKET_DEBUG
986 qCDebug(lcTlsBackendSchannel, "Need %lu more bytes.", secBuffer.cbBuffer);
987#endif
988 return secBuffer.cbBuffer;
989}
990 return 0;
991}
992
993DWORD defaultCredsFlag()
994{
995 return qEnvironmentVariableIsSet("QT_SCH_DEFAULT_CREDS") ? 0 : SCH_CRED_NO_DEFAULT_CREDS;
996}
997} // anonymous namespace
998
999
1000namespace QTlsPrivate {
1001
1002TlsCryptographSchannel::TlsCryptographSchannel()
1003{
1004 SecInvalidateHandle(&credentialHandle);
1005 SecInvalidateHandle(&contextHandle);
1006 QSchannelBackend::ensureInitializedImplementation();
1007}
1008
1010{
1011 closeCertificateStores();
1012 deallocateContext();
1013 freeCredentialsHandle();
1014}
1015
1016void TlsCryptographSchannel::init(QSslSocket *qObj, QSslSocketPrivate *dObj)
1017{
1018 Q_ASSERT(qObj);
1019 Q_ASSERT(dObj);
1020
1021 q = qObj;
1022 d = dObj;
1023
1024 reset();
1025}
1026
1027bool TlsCryptographSchannel::sendToken(void *token, unsigned long tokenLength, bool emitError)
1028{
1029 if (tokenLength == 0)
1030 return true;
1031
1032 Q_ASSERT(d);
1033 auto *plainSocket = d->plainTcpSocket();
1034 Q_ASSERT(plainSocket);
1035 if (plainSocket->state() == QAbstractSocket::UnconnectedState || !plainSocket->isValid()
1036 || !plainSocket->isOpen()) {
1037 return false;
1038 }
1039
1040 const qint64 written = plainSocket->write(static_cast<const char *>(token), tokenLength);
1041 if (written != qint64(tokenLength)) {
1042 // Failed to write/buffer everything or an error occurred
1043 if (emitError)
1044 setErrorAndEmit(d, plainSocket->error(), plainSocket->errorString());
1045 return false;
1046 }
1047 return true;
1048}
1049
1050QString TlsCryptographSchannel::targetName() const
1051{
1052 // Used for SNI extension
1053 Q_ASSERT(q);
1054 Q_ASSERT(d);
1055
1056 const auto verificationPeerName = d->verificationName();
1057 return verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName;
1058}
1059
1060ULONG TlsCryptographSchannel::getContextRequirements()
1061{
1062 Q_ASSERT(d);
1063 Q_ASSERT(q);
1064
1065 const bool isClient = d->tlsMode() == QSslSocket::SslClientMode;
1066 ULONG req = 0;
1067
1068 req |= ISC_REQ_ALLOCATE_MEMORY; // Allocate memory for buffers automatically
1069 req |= ISC_REQ_CONFIDENTIALITY; // Encrypt messages
1070 req |= ISC_REQ_REPLAY_DETECT; // Detect replayed messages
1071 req |= ISC_REQ_SEQUENCE_DETECT; // Detect out of sequence messages
1072 req |= ISC_REQ_STREAM; // Support a stream-oriented connection
1073
1074 if (isClient) {
1075 req |= ISC_REQ_MANUAL_CRED_VALIDATION; // Manually validate certificate
1076 } else {
1077 switch (q->peerVerifyMode()) {
1078 case QSslSocket::PeerVerifyMode::VerifyNone:
1079 // There doesn't seem to be a way to ask for an optional client cert :-(
1080 case QSslSocket::PeerVerifyMode::AutoVerifyPeer:
1081 case QSslSocket::PeerVerifyMode::QueryPeer:
1082 break;
1083 case QSslSocket::PeerVerifyMode::VerifyPeer:
1084 req |= ISC_REQ_MUTUAL_AUTH;
1085 break;
1086 }
1087 }
1088
1089 return req;
1090}
1091
1092bool TlsCryptographSchannel::acquireCredentialsHandle()
1093{
1094 Q_ASSERT(d);
1095 Q_ASSERT(q);
1096 const auto &configuration = q->sslConfiguration();
1097
1098 Q_ASSERT(schannelState == SchannelState::InitializeHandshake);
1099
1100 const bool isClient = d->tlsMode() == QSslSocket::SslClientMode;
1101 DWORD protocols = toSchannelProtocol(configuration.protocol());
1102 if (protocols == DWORD(-1)) {
1103 setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError,
1104 QSslSocket::tr("Invalid protocol chosen"));
1105 return false;
1106 }
1107
1108 DWORD certsCount = 0;
1109 // Set up our certificate stores before trying to use one...
1110 initializeCertificateStores();
1111
1112 // Check if user has specified a certificate chain but it could not be loaded.
1113 // This happens if there was something wrong with the certificate chain or there was no private
1114 // key.
1115 if (!configuration.localCertificateChain().isEmpty() && !localCertificateStore)
1116 return true; // 'true' because "tst_QSslSocket::setEmptyKey" expects us to not disconnect
1117
1118 PCCERT_CONTEXT localCertificate = nullptr;
1119 if (localCertificateStore != nullptr) {
1120 certsCount = 1;
1121 localCertificate = static_cast<PCCERT_CONTEXT>(configuration.localCertificate().handle());
1122 Q_ASSERT(localCertificate);
1123 }
1124
1125 const QList<QSslCipher> ciphers = configuration.ciphers();
1126 if (!ciphers.isEmpty() && !containsTls13Cipher(ciphers))
1127 protocols &= ~SP_PROT_TLS1_3;
1128
1129 QList<CRYPTO_SETTINGS> cryptoSettings;
1130 if (!ciphers.isEmpty())
1131 cryptoSettings = cryptoSettingsForCiphers(ciphers);
1132
1133 TLS_PARAMETERS tlsParameters = {
1134 0,
1135 nullptr,
1136 negatedSchannelProtocols(protocols), // what protocols to disable
1137 static_cast<DWORD>(cryptoSettings.size()),
1138 (cryptoSettings.isEmpty() ? nullptr : cryptoSettings.data()),
1139 0
1140 };
1141
1142 SCH_CREDENTIALS credentials = {
1143 SCH_CREDENTIALS_VERSION,
1144 0,
1145 certsCount,
1146 &localCertificate,
1147 nullptr,
1148 0,
1149 nullptr,
1150 0,
1151 SCH_CRED_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT | defaultCredsFlag(),
1152 1,
1153 &tlsParameters
1154 };
1155
1156 TimeStamp expiration{};
1157 auto status = AcquireCredentialsHandle(nullptr, // pszPrincipal (unused)
1158 const_cast<wchar_t *>(UNISP_NAME), // pszPackage
1159 isClient ? SECPKG_CRED_OUTBOUND : SECPKG_CRED_INBOUND, // fCredentialUse
1160 nullptr, // pvLogonID (unused)
1161 &credentials, // pAuthData
1162 nullptr, // pGetKeyFn (unused)
1163 nullptr, // pvGetKeyArgument (unused)
1164 &credentialHandle, // phCredential
1165 &expiration // ptsExpir
1166 );
1167
1168 if (status != SEC_E_OK) {
1169 setErrorAndEmit(d, QAbstractSocket::SslInternalError, schannelErrorToString(status));
1170 return false;
1171 }
1172 return true;
1173}
1174
1175void TlsCryptographSchannel::deallocateContext()
1176{
1177 if (SecIsValidHandle(&contextHandle)) {
1178 DeleteSecurityContext(&contextHandle);
1179 SecInvalidateHandle(&contextHandle);
1180 }
1181}
1182
1183void TlsCryptographSchannel::freeCredentialsHandle()
1184{
1185 if (SecIsValidHandle(&credentialHandle)) {
1186 FreeCredentialsHandle(&credentialHandle);
1187 SecInvalidateHandle(&credentialHandle);
1188 }
1189}
1190
1191void TlsCryptographSchannel::closeCertificateStores()
1192{
1193 localCertificateStore.reset();
1194 peerCertificateStore.reset();
1195 caCertificateStore.reset();
1196}
1197
1198bool TlsCryptographSchannel::createContext()
1199{
1200 Q_ASSERT(q);
1201 Q_ASSERT(d);
1202
1203 Q_ASSERT(SecIsValidHandle(&credentialHandle));
1204 Q_ASSERT(schannelState == SchannelState::InitializeHandshake);
1205 Q_ASSERT(d->tlsMode() == QSslSocket::SslClientMode);
1206 ULONG contextReq = getContextRequirements();
1207
1208 SecBuffer outBuffers[3];
1209 outBuffers[0] = createSecBuffer(nullptr, 0, SECBUFFER_TOKEN);
1210 outBuffers[1] = createSecBuffer(nullptr, 0, SECBUFFER_ALERT);
1211 outBuffers[2] = createSecBuffer(nullptr, 0, SECBUFFER_EMPTY);
1212 auto freeBuffers = qScopeGuard([&outBuffers]() {
1213 for (auto i = 0ull; i < ARRAYSIZE(outBuffers); i++) {
1214 if (outBuffers[i].pvBuffer)
1215 FreeContextBuffer(outBuffers[i].pvBuffer);
1216 }
1217 });
1218 SecBufferDesc outputBufferDesc{
1219 SECBUFFER_VERSION,
1220 ARRAYSIZE(outBuffers),
1221 outBuffers
1222 };
1223
1224 TimeStamp expiry;
1225
1226 SecBufferDesc alpnBufferDesc;
1227 bool useAlpn = false;
1228#ifdef SUPPORTS_ALPN
1229 QTlsBackend::setAlpnStatus(d, QSslConfiguration::NextProtocolNegotiationNone);
1230 QByteArray alpnString = createAlpnString(q->sslConfiguration().allowedNextProtocols());
1231 useAlpn = !alpnString.isEmpty();
1232 SecBuffer alpnBuffers[1];
1233 alpnBuffers[0] = createSecBuffer(alpnString, SECBUFFER_APPLICATION_PROTOCOLS);
1234 alpnBufferDesc = {
1235 SECBUFFER_VERSION,
1236 ARRAYSIZE(alpnBuffers),
1237 alpnBuffers
1238 };
1239#endif
1240
1241 const QString encodedTargetName = QUrl::fromUserInput(targetName()).host(QUrl::EncodeUnicode);
1242 auto status = InitializeSecurityContext(&credentialHandle, // phCredential
1243 nullptr, // phContext
1244 const_reinterpret_cast<SEC_WCHAR *>(encodedTargetName.utf16()), // pszTargetName
1245 contextReq, // fContextReq
1246 0, // Reserved1
1247 0, // TargetDataRep (unused)
1248 useAlpn ? &alpnBufferDesc : nullptr, // pInput
1249 0, // Reserved2
1250 &contextHandle, // phNewContext
1251 &outputBufferDesc, // pOutput
1252 &contextAttributes, // pfContextAttr
1253 &expiry // ptsExpiry
1254 );
1255
1256 // This is the first call to InitializeSecurityContext, so theoretically "CONTINUE_NEEDED"
1257 // should be the only non-error return-code here.
1258 if (status != SEC_I_CONTINUE_NEEDED) {
1259 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1260 QSslSocket::tr("Error creating SSL context (%1)").arg(schannelErrorToString(status)));
1261 return false;
1262 }
1263
1264 if (!sendToken(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer))
1265 return false;
1266 schannelState = SchannelState::PerformHandshake;
1267 return true;
1268}
1269
1270bool TlsCryptographSchannel::acceptContext()
1271{
1272 Q_ASSERT(d);
1273 Q_ASSERT(q);
1274
1275 auto *plainSocket = d->plainTcpSocket();
1276 Q_ASSERT(plainSocket);
1277
1278 Q_ASSERT(SecIsValidHandle(&credentialHandle));
1279 Q_ASSERT(schannelState == SchannelState::InitializeHandshake);
1280 Q_ASSERT(d->tlsMode() == QSslSocket::SslServerMode);
1281 ULONG contextReq = getContextRequirements();
1282
1283 if (missingData > plainSocket->bytesAvailable())
1284 return true;
1285
1286 missingData = 0;
1287 readToBuffer(intermediateBuffer, plainSocket);
1288 if (intermediateBuffer.isEmpty())
1289 return true; // definitely need more data..
1290
1291 SecBuffer inBuffers[2];
1292 inBuffers[0] = createSecBuffer(intermediateBuffer, SECBUFFER_TOKEN);
1293
1294#ifdef SUPPORTS_ALPN
1295 QTlsBackend::setAlpnStatus(d, QSslConfiguration::NextProtocolNegotiationNone);
1296 // The string must be alive when we call AcceptSecurityContext
1297 QByteArray alpnString = createAlpnString(q->sslConfiguration().allowedNextProtocols());
1298 if (!alpnString.isEmpty()) {
1299 inBuffers[1] = createSecBuffer(alpnString, SECBUFFER_APPLICATION_PROTOCOLS);
1300 } else
1301#endif
1302 {
1303 inBuffers[1] = createSecBuffer(nullptr, 0, SECBUFFER_EMPTY);
1304 }
1305
1306 SecBufferDesc inputBufferDesc{
1307 SECBUFFER_VERSION,
1308 ARRAYSIZE(inBuffers),
1309 inBuffers
1310 };
1311
1312 SecBuffer outBuffers[3];
1313 outBuffers[0] = createSecBuffer(nullptr, 0, SECBUFFER_TOKEN);
1314 outBuffers[1] = createSecBuffer(nullptr, 0, SECBUFFER_ALERT);
1315 outBuffers[2] = createSecBuffer(nullptr, 0, SECBUFFER_EMPTY);
1316 auto freeBuffers = qScopeGuard([&outBuffers]() {
1317 for (auto i = 0ull; i < ARRAYSIZE(outBuffers); i++) {
1318 if (outBuffers[i].pvBuffer)
1319 FreeContextBuffer(outBuffers[i].pvBuffer);
1320 }
1321 });
1322 SecBufferDesc outputBufferDesc{
1323 SECBUFFER_VERSION,
1324 ARRAYSIZE(outBuffers),
1325 outBuffers
1326 };
1327
1328 TimeStamp expiry;
1329 auto status = AcceptSecurityContext(
1330 &credentialHandle, // phCredential
1331 nullptr, // phContext
1332 &inputBufferDesc, // pInput
1333 contextReq, // fContextReq
1334 0, // TargetDataRep (unused)
1335 &contextHandle, // phNewContext
1336 &outputBufferDesc, // pOutput
1337 &contextAttributes, // pfContextAttr
1338 &expiry // ptsTimeStamp
1339 );
1340
1341 if (status == SEC_E_INCOMPLETE_MESSAGE) {
1342 // Need more data
1343 missingData = checkIncompleteData(outBuffers[0]);
1344 return true;
1345 }
1346
1347 if (inBuffers[1].BufferType == SECBUFFER_EXTRA) {
1348 // https://docs.microsoft.com/en-us/windows/desktop/secauthn/extra-buffers-returned-by-schannel
1349 // inBuffers[1].cbBuffer indicates the amount of bytes _NOT_ processed, the rest need to
1350 // be stored.
1351 retainExtraData(intermediateBuffer, inBuffers[1]);
1352 } else { /* No 'extra' data, message not incomplete */
1353 intermediateBuffer.resize(0);
1354 }
1355
1356 if (status != SEC_I_CONTINUE_NEEDED) {
1357 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
1358 QSslSocket::tr("Error creating SSL context (%1)").arg(schannelErrorToString(status)));
1359 return false;
1360 }
1361 if (!sendToken(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer))
1362 return false;
1363 schannelState = SchannelState::PerformHandshake;
1364 return true;
1365}
1366
1367bool TlsCryptographSchannel::performHandshake()
1368{
1369 Q_ASSERT(d);
1370 auto *plainSocket = d->plainTcpSocket();
1371 Q_ASSERT(plainSocket);
1372
1373 if (plainSocket->state() == QAbstractSocket::UnconnectedState || !plainSocket->isValid()
1374 || !plainSocket->isOpen()) {
1375 setErrorAndEmit(d, QAbstractSocket::RemoteHostClosedError,
1376 QSslSocket::tr("The TLS/SSL connection has been closed"));
1377 return false;
1378 }
1379 Q_ASSERT(SecIsValidHandle(&credentialHandle));
1380 Q_ASSERT(SecIsValidHandle(&contextHandle));
1381 Q_ASSERT(schannelState == SchannelState::PerformHandshake);
1382
1383#ifdef QSSLSOCKET_DEBUG
1384 qCDebug(lcTlsBackendSchannel, "Bytes available from socket: %lld",
1385 plainSocket->bytesAvailable());
1386 qCDebug(lcTlsBackendSchannel, "intermediateBuffer size: %d", intermediateBuffer.size());
1387#endif
1388
1389 if (missingData > plainSocket->bytesAvailable())
1390 return true;
1391
1392 missingData = 0;
1393 readToBuffer(intermediateBuffer, plainSocket);
1394 if (intermediateBuffer.isEmpty())
1395 return true; // no data, will fail
1396
1397 SecBuffer outBuffers[3] = {};
1398 const auto freeOutBuffers = [&outBuffers]() {
1399 for (auto i = 0ull; i < ARRAYSIZE(outBuffers); i++) {
1400 if (outBuffers[i].pvBuffer)
1401 FreeContextBuffer(outBuffers[i].pvBuffer);
1402 }
1403 };
1404 const auto outBuffersGuard = qScopeGuard(freeOutBuffers);
1405 // For this call to InitializeSecurityContext we may need to call it twice.
1406 // In some cases us not having a certificate isn't actually an error, but just a request.
1407 // With Schannel, to ignore this warning, we need to call InitializeSecurityContext again
1408 // when we get SEC_I_INCOMPLETE_CREDENTIALS! As far as I can tell it's not documented anywhere.
1409 // https://stackoverflow.com/a/47479968/2493610
1410 SECURITY_STATUS status;
1411 short attempts = 2;
1412 do {
1413 SecBuffer inputBuffers[2];
1414 inputBuffers[0] = createSecBuffer(intermediateBuffer, SECBUFFER_TOKEN);
1415 inputBuffers[1] = createSecBuffer(nullptr, 0, SECBUFFER_EMPTY);
1416 SecBufferDesc inputBufferDesc{
1417 SECBUFFER_VERSION,
1418 ARRAYSIZE(inputBuffers),
1419 inputBuffers
1420 };
1421
1422 freeOutBuffers(); // free buffers from any previous attempt
1423 outBuffers[0] = createSecBuffer(nullptr, 0, SECBUFFER_TOKEN);
1424 outBuffers[1] = createSecBuffer(nullptr, 0, SECBUFFER_ALERT);
1425 outBuffers[2] = createSecBuffer(nullptr, 0, SECBUFFER_EMPTY);
1426 SecBufferDesc outputBufferDesc{
1427 SECBUFFER_VERSION,
1428 ARRAYSIZE(outBuffers),
1429 outBuffers
1430 };
1431
1432 ULONG contextReq = getContextRequirements();
1433 TimeStamp expiry;
1434 status = InitializeSecurityContext(
1435 &credentialHandle, // phCredential
1436 &contextHandle, // phContext
1437 const_reinterpret_cast<SEC_WCHAR *>(targetName().utf16()), // pszTargetName
1438 contextReq, // fContextReq
1439 0, // Reserved1
1440 0, // TargetDataRep (unused)
1441 &inputBufferDesc, // pInput
1442 0, // Reserved2
1443 nullptr, // phNewContext (we already have one)
1444 &outputBufferDesc, // pOutput
1445 &contextAttributes, // pfContextAttr
1446 &expiry // ptsExpiry
1447 );
1448
1449 if (inputBuffers[1].BufferType == SECBUFFER_EXTRA) {
1450 // https://docs.microsoft.com/en-us/windows/desktop/secauthn/extra-buffers-returned-by-schannel
1451 // inputBuffers[1].cbBuffer indicates the amount of bytes _NOT_ processed, the rest need
1452 // to be stored.
1453 retainExtraData(intermediateBuffer, inputBuffers[1]);
1454 } else if (status != SEC_E_INCOMPLETE_MESSAGE) {
1455 // Clear the buffer if we weren't asked for more data
1456 intermediateBuffer.resize(0);
1457 }
1458
1459 --attempts;
1460 } while (status == SEC_I_INCOMPLETE_CREDENTIALS && attempts > 0);
1461
1462 switch (status) {
1463 case SEC_E_OK:
1464 // Need to transmit a final token in the handshake if 'cbBuffer' is non-zero.
1465 if (!sendToken(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer))
1466 return false;
1467 schannelState = SchannelState::VerifyHandshake;
1468 return true;
1469 case SEC_I_CONTINUE_NEEDED:
1470 if (!sendToken(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer))
1471 return false;
1472 // Must call InitializeSecurityContext again later (done through continueHandshake)
1473 return true;
1474 case SEC_I_INCOMPLETE_CREDENTIALS:
1475 // Schannel takes care of picking certificate to send (other than the one we can specify),
1476 // so if we get here then that means we don't have a certificate the server accepts.
1477 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
1478 QSslSocket::tr("Server did not accept any certificate we could present."));
1479 return false;
1480 case SEC_I_CONTEXT_EXPIRED:
1481 // "The message sender has finished using the connection and has initiated a shutdown."
1482 if (outBuffers[0].BufferType == SECBUFFER_TOKEN) {
1483 if (!sendToken(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer))
1484 return false;
1485 }
1486 if (!shutdown) { // we did not initiate this
1487 setErrorAndEmit(d, QAbstractSocket::RemoteHostClosedError,
1488 QSslSocket::tr("The TLS/SSL connection has been closed"));
1489 }
1490 return true;
1491 case SEC_E_INCOMPLETE_MESSAGE:
1492 // Simply incomplete, wait for more data
1493 missingData = checkIncompleteData(outBuffers[0]);
1494 return true;
1495 case SEC_E_ALGORITHM_MISMATCH:
1496 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
1497 QSslSocket::tr("Algorithm mismatch"));
1498 shutdown = true; // skip sending the "Shutdown" alert
1499 return false;
1500 }
1501
1502 // Note: We can get here if the connection is using TLS 1.2 and the server certificate uses
1503 // MD5, which is not allowed in Schannel. This causes an "invalid token" error during handshake.
1504 // (If you came here investigating an error: md5 is insecure, update your certificate)
1505 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
1506 QSslSocket::tr("Handshake failed: %1").arg(schannelErrorToString(status)));
1507 return false;
1508}
1509
1510bool TlsCryptographSchannel::verifyHandshake()
1511{
1512 Q_ASSERT(d);
1513 Q_ASSERT(q);
1514 const auto &configuration = q->sslConfiguration();
1515
1516 sslErrors.clear();
1517
1518 const bool isClient = d->tlsMode() == QSslSocket::SslClientMode;
1519#define CHECK_STATUS(status)
1520 if (status != SEC_E_OK) {
1521 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1522 QSslSocket::tr("Failed to query the TLS context: %1")
1523 .arg(schannelErrorToString(status)));
1524 return false;
1525 }
1526
1527 // Everything is set up, now make sure there's nothing wrong and query some attributes...
1528 if (!matchesContextRequirements(contextAttributes, getContextRequirements(),
1529 configuration.peerVerifyMode(), isClient)) {
1530 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
1531 QSslSocket::tr("Did not get the required attributes for the connection."));
1532 return false;
1533 }
1534
1535 // Get stream sizes (to know the max size of a message and the size of the header and trailer)
1536 auto status = QueryContextAttributes(&contextHandle,
1537 SECPKG_ATTR_STREAM_SIZES,
1538 &streamSizes);
1539 CHECK_STATUS(status);
1540
1541 // Get session cipher info
1542 status = QueryContextAttributes(&contextHandle,
1543 SECPKG_ATTR_CIPHER_INFO,
1544 &cipherInfo);
1545 CHECK_STATUS(status);
1546
1547 status = QueryContextAttributes(&contextHandle,
1548 SECPKG_ATTR_CONNECTION_INFO,
1549 &connectionInfo);
1550 CHECK_STATUS(status);
1551
1552#ifdef SUPPORTS_ALPN
1553 const auto allowedProtos = configuration.allowedNextProtocols();
1554 if (!allowedProtos.isEmpty()) {
1555 SecPkgContext_ApplicationProtocol alpn;
1556 status = QueryContextAttributes(&contextHandle,
1557 SECPKG_ATTR_APPLICATION_PROTOCOL,
1558 &alpn);
1559 CHECK_STATUS(status);
1560 if (alpn.ProtoNegoStatus == SecApplicationProtocolNegotiationStatus_Success) {
1561 QByteArray negotiatedProto = QByteArray((const char *)alpn.ProtocolId,
1562 alpn.ProtocolIdSize);
1563 if (!allowedProtos.contains(negotiatedProto)) {
1564 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
1565 QSslSocket::tr("Unwanted protocol was negotiated"));
1566 return false;
1567 }
1568 QTlsBackend::setNegotiatedProtocol(d, negotiatedProto);
1569 QTlsBackend::setAlpnStatus(d, QSslConfiguration::NextProtocolNegotiationNegotiated);
1570 } else {
1571 QTlsBackend::setNegotiatedProtocol(d, {});
1572 QTlsBackend::setAlpnStatus(d, QSslConfiguration::NextProtocolNegotiationUnsupported);
1573 }
1574 }
1575#endif // supports ALPN
1576
1577#undef CHECK_STATUS
1578
1579 // Verify certificate
1580 CERT_CONTEXT *certificateContext = nullptr;
1581 auto freeCertificate = qScopeGuard([&certificateContext]() {
1582 if (certificateContext)
1583 CertFreeCertificateContext(certificateContext);
1584 });
1585 status = QueryContextAttributes(&contextHandle,
1586 SECPKG_ATTR_REMOTE_CERT_CONTEXT,
1587 &certificateContext);
1588
1589 // QueryPeer can (currently) not work in Schannel since Schannel itself doesn't have a way to
1590 // ask for a certificate and then still be OK if it's not received.
1591 // To work around this we don't request a certificate at all for QueryPeer.
1592 // For servers AutoVerifyPeer is supposed to be treated the same as QueryPeer.
1593 // This means that servers using Schannel will only request client certificate for "VerifyPeer".
1594 if ((!isClient && configuration.peerVerifyMode() == QSslSocket::PeerVerifyMode::VerifyPeer)
1595 || (isClient && configuration.peerVerifyMode() != QSslSocket::PeerVerifyMode::VerifyNone
1596 && configuration.peerVerifyMode() != QSslSocket::PeerVerifyMode::QueryPeer)) {
1597 if (status != SEC_E_OK) {
1598#ifdef QSSLSOCKET_DEBUG
1599 qCDebug(lcTlsBackendSchannel) << "Couldn't retrieve peer certificate, status:"
1600 << schannelErrorToString(status);
1601#endif
1602 const QSslError error{ QSslError::NoPeerCertificate };
1603 sslErrors += error;
1604 emit q->peerVerifyError(error);
1605 if (q->state() != QAbstractSocket::ConnectedState)
1606 return false;
1607 }
1608 }
1609
1610 // verifyCertContext returns false if the user disconnected while it was checking errors.
1611 if (certificateContext && !verifyCertContext(certificateContext))
1612 return false;
1613
1614 if (!checkSslErrors() || q->state() != QAbstractSocket::ConnectedState) {
1615#ifdef QSSLSOCKET_DEBUG
1616 qCDebug(lcTlsBackendSchannel) << __func__ << "was unsuccessful. Paused:" << d->isPaused();
1617#endif
1618 // If we're paused then checkSslErrors returned false, but it's not an error
1619 return d->isPaused() && q->state() == QAbstractSocket::ConnectedState;
1620 }
1621
1622 schannelState = SchannelState::Done;
1623 return true;
1624}
1625
1626bool TlsCryptographSchannel::renegotiate()
1627{
1628 Q_ASSERT(d);
1629
1630 SecBuffer outBuffers[3];
1631 outBuffers[0] = createSecBuffer(nullptr, 0, SECBUFFER_TOKEN);
1632 outBuffers[1] = createSecBuffer(nullptr, 0, SECBUFFER_ALERT);
1633 outBuffers[2] = createSecBuffer(nullptr, 0, SECBUFFER_EMPTY);
1634 auto freeBuffers = qScopeGuard([&outBuffers]() {
1635 for (auto i = 0ull; i < ARRAYSIZE(outBuffers); i++) {
1636 if (outBuffers[i].pvBuffer)
1637 FreeContextBuffer(outBuffers[i].pvBuffer);
1638 }
1639 });
1640 SecBufferDesc outputBufferDesc{
1641 SECBUFFER_VERSION,
1642 ARRAYSIZE(outBuffers),
1643 outBuffers
1644 };
1645
1646 ULONG contextReq = getContextRequirements();
1647 TimeStamp expiry;
1648 SECURITY_STATUS status;
1649 if (d->tlsMode() == QSslSocket::SslClientMode) {
1650 status = InitializeSecurityContext(&credentialHandle, // phCredential
1651 &contextHandle, // phContext
1652 const_reinterpret_cast<SEC_WCHAR *>(targetName().utf16()), // pszTargetName
1653 contextReq, // fContextReq
1654 0, // Reserved1
1655 0, // TargetDataRep (unused)
1656 nullptr, // pInput (nullptr for renegotiate)
1657 0, // Reserved2
1658 nullptr, // phNewContext (we already have one)
1659 &outputBufferDesc, // pOutput
1660 &contextAttributes, // pfContextAttr
1661 &expiry // ptsExpiry
1662 );
1663 } else {
1664 status = AcceptSecurityContext(
1665 &credentialHandle, // phCredential
1666 &contextHandle, // phContext
1667 nullptr, // pInput
1668 contextReq, // fContextReq
1669 0, // TargetDataRep (unused)
1670 nullptr, // phNewContext
1671 &outputBufferDesc, // pOutput
1672 &contextAttributes, // pfContextAttr,
1673 &expiry // ptsTimeStamp
1674 );
1675 }
1676 if (status == SEC_I_CONTINUE_NEEDED) {
1677 schannelState = SchannelState::PerformHandshake;
1678 return sendToken(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer);
1679 } else if (status == SEC_E_OK) {
1680 schannelState = SchannelState::PerformHandshake;
1681 return true;
1682 }
1683 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
1684 QSslSocket::tr("Renegotiation was unsuccessful: %1").arg(schannelErrorToString(status)));
1685 return false;
1686}
1687
1688/*!
1689 \internal
1690 reset the state in preparation for reuse of socket
1691*/
1692void TlsCryptographSchannel::reset()
1693{
1694 Q_ASSERT(d);
1695
1696 closeCertificateStores(); // certificate stores could've changed
1697 deallocateContext();
1698 freeCredentialsHandle(); // in case we already had one (@future: session resumption requires re-use)
1699
1700 cipherInfo = {};
1701 connectionInfo = {};
1702 streamSizes = {};
1703
1704 contextAttributes = 0;
1705 intermediateBuffer.clear();
1706 schannelState = SchannelState::InitializeHandshake;
1707
1708
1709 d->setEncrypted(false);
1710 shutdown = false;
1711 renegotiating = false;
1712
1713 missingData = 0;
1714}
1715
1717{
1718 Q_ASSERT(q);
1719
1720 if (q->isEncrypted())
1721 return; // let's not mess up the connection...
1722 reset();
1724}
1725
1727{
1728 Q_ASSERT(q);
1729
1730 if (q->isEncrypted())
1731 return; // let's not mess up the connection...
1732 reset();
1734}
1735
1736auto TlsCryptographSchannel::getNextEncryptedMessage() -> MessageBufferResult
1737{
1738 MessageBufferResult result;
1739 QByteArray &fullMessage = result.messageBuffer;
1740
1741 Q_ASSERT(d);
1742 auto &writeBuffer = d->tlsWriteBuffer();
1743
1744 auto allocateMessage = [&fullMessage](qsizetype size) -> QSpan<char> {
1745 auto targetSize = fullMessage.size() + size;
1746 if (fullMessage.capacity() < targetSize) {
1747 qsizetype newSize = fullMessage.capacity() * 2;
1748 if (newSize < targetSize)
1749 newSize = targetSize;
1750 fullMessage.reserve(newSize);
1751 }
1752 fullMessage.resizeForOverwrite(targetSize);
1753 return QSpan(fullMessage).subspan(fullMessage.size() - size);
1754 };
1755
1756 const int headerSize = int(streamSizes.cbHeader);
1757 const int trailerSize = int(streamSizes.cbTrailer);
1758 constexpr qsizetype MessageBufferThreshold = 128 * 1024;
1759
1760 qint64 writeBufferSize = 0;
1761 while ((writeBufferSize = writeBuffer.size()) > 0
1762 && fullMessage.size() < MessageBufferThreshold) {
1763 // Try to read 'cbMaximumMessage' bytes from buffer before encrypting.
1764 const int bodySize = int(std::min(writeBufferSize, qint64(streamSizes.cbMaximumMessage)));
1765 const qsizetype messageSize = headerSize + bodySize + trailerSize;
1766 QSpan buffer = allocateMessage(messageSize);
1767 char *header = buffer.data();
1768 char *body = header + headerSize;
1769 char *trailer = body + bodySize;
1770 {
1771 // Use peek() here instead of read() so we don't lose data if encryption fails.
1772 qint64 copied = writeBuffer.peek(body, bodySize);
1773 Q_ASSERT(copied == bodySize);
1774 }
1775
1776 SecBuffer inputBuffers[] = {
1777 createSecBuffer(header, headerSize, SECBUFFER_STREAM_HEADER),
1778 createSecBuffer(body, bodySize, SECBUFFER_DATA),
1779 createSecBuffer(trailer, trailerSize, SECBUFFER_STREAM_TRAILER),
1780 createSecBuffer(nullptr, 0, SECBUFFER_EMPTY)
1781 };
1782 SecBufferDesc message = {
1783 SECBUFFER_VERSION,
1784 ARRAYSIZE(inputBuffers),
1785 inputBuffers
1786 };
1787
1788 if (auto status = EncryptMessage(&contextHandle, 0, &message, 0); status != SEC_E_OK) {
1789 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1790 QSslSocket::tr("Schannel failed to encrypt data: %1")
1791 .arg(schannelErrorToString(status)));
1792 result.messageBuffer.chop(messageSize);
1793 return result;
1794 }
1795 // Data was encrypted successfully, so we free() what we peek()ed earlier
1796 writeBuffer.free(bodySize);
1797
1798 // The trailer's size is not final, so resize fullMessage to not send trailing junk
1799 auto finalSize = qsizetype(inputBuffers[0].cbBuffer + inputBuffers[1].cbBuffer
1800 + inputBuffers[2].cbBuffer);
1801 fullMessage.chop(messageSize - finalSize);
1802 }
1803 result.ok = true;
1804 return result;
1805}
1806
1808{
1809 Q_ASSERT(q);
1810 Q_ASSERT(d);
1811 auto *plainSocket = d->plainTcpSocket();
1812 Q_ASSERT(plainSocket);
1813
1814 if (d->tlsMode() == QSslSocket::UnencryptedMode)
1815 return; // This function should not have been called
1816
1817 // Can happen if called through QSslSocket::abort->QSslSocket::close->QSslSocket::flush->here
1818 if (plainSocket->state() == QAbstractSocket::UnconnectedState || !plainSocket->isValid()
1819 || !plainSocket->isOpen()) {
1820 return;
1821 }
1822
1823 if (schannelState != SchannelState::Done) {
1825 return;
1826 }
1827
1828 auto &buffer = d->tlsBuffer();
1829 if (q->isEncrypted()) { // encrypt data in writeBuffer and write it to plainSocket
1830 qint64 totalBytesWritten = 0;
1831 while (d->tlsWriteBuffer().size() > 0) {
1832 MessageBufferResult r = getNextEncryptedMessage();
1833 if (r.messageBuffer.isEmpty() && !r.ok)
1834 return;
1835 QByteArray fullMessage = std::move(r.messageBuffer);
1836 const qint64 bytesWritten = plainSocket->write(fullMessage);
1837 if (!r.ok && bytesWritten < 0)
1838 break; // We might have to emit bytesWritten, so break instead of return
1839#ifdef QSSLSOCKET_DEBUG
1840 qCDebug(lcTlsBackendSchannel, "Wrote %lld of total %d bytes", bytesWritten,
1841 fullMessage.size());
1842#endif
1843 if (bytesWritten >= 0) {
1844 totalBytesWritten += bytesWritten;
1845 } else {
1846 setErrorAndEmit(d, plainSocket->error(), plainSocket->errorString());
1847 return;
1848 }
1849 }
1850
1851 if (totalBytesWritten > 0) {
1852 // Don't emit bytesWritten() recursively.
1853 bool &emittedBytesWritten = d->tlsEmittedBytesWritten();
1854 if (!emittedBytesWritten) {
1855 emittedBytesWritten = true;
1856 emit q->bytesWritten(totalBytesWritten);
1857 emittedBytesWritten = false;
1858 }
1859 emit q->channelBytesWritten(0, totalBytesWritten);
1860 }
1861 }
1862
1863 int totalRead = 0;
1864 bool hadIncompleteData = false;
1865 const auto readBufferMaxSize = d->maxReadBufferSize();
1866 while (!readBufferMaxSize || buffer.size() < readBufferMaxSize) {
1867 if (missingData > plainSocket->bytesAvailable()
1868 && (!readBufferMaxSize || readBufferMaxSize >= missingData)) {
1869#ifdef QSSLSOCKET_DEBUG
1870 qCDebug(lcTlsBackendSchannel, "We're still missing %lld bytes, will check later.",
1871 missingData);
1872#endif
1873 break;
1874 }
1875
1876 missingData = 0;
1877 const qint64 bytesRead = readToBuffer(intermediateBuffer, plainSocket);
1878#ifdef QSSLSOCKET_DEBUG
1879 qCDebug(lcTlsBackendSchannel, "Read %lld encrypted bytes from the socket", bytesRead);
1880#endif
1881 if (intermediateBuffer.length() == 0 || (hadIncompleteData && bytesRead == 0)) {
1882#ifdef QSSLSOCKET_DEBUG
1883 qCDebug(lcTlsBackendSchannel,
1884 hadIncompleteData ? "No new data received, leaving loop!"
1885 : "Nothing to decrypt, leaving loop!");
1886#endif
1887 break;
1888 }
1889 hadIncompleteData = false;
1890#ifdef QSSLSOCKET_DEBUG
1891 qCDebug(lcTlsBackendSchannel, "Total amount of bytes to decrypt: %d",
1892 intermediateBuffer.length());
1893#endif
1894
1895 SecBuffer dataBuffer[4]{
1896 createSecBuffer(intermediateBuffer, SECBUFFER_DATA),
1897 createSecBuffer(nullptr, 0, SECBUFFER_EMPTY),
1898 createSecBuffer(nullptr, 0, SECBUFFER_EMPTY),
1899 createSecBuffer(nullptr, 0, SECBUFFER_EMPTY)
1900 };
1901 SecBufferDesc message{
1902 SECBUFFER_VERSION,
1903 ARRAYSIZE(dataBuffer),
1904 dataBuffer
1905 };
1906 auto status = DecryptMessage(&contextHandle, &message, 0, nullptr);
1907 if (status == SEC_E_OK || status == SEC_I_RENEGOTIATE || status == SEC_I_CONTEXT_EXPIRED) {
1908 // There can still be 0 output even if it succeeds, this is fine
1909 if (dataBuffer[1].cbBuffer > 0) {
1910 // It is always decrypted in-place.
1911 // But [0] is the STREAM_HEADER, [1] is the DATA and [2] is the STREAM_TRAILER.
1912 // The pointers in all of those still point into 'intermediateBuffer'.
1913 buffer.append(static_cast<char *>(dataBuffer[1].pvBuffer),
1914 dataBuffer[1].cbBuffer);
1915 totalRead += dataBuffer[1].cbBuffer;
1916#ifdef QSSLSOCKET_DEBUG
1917 qCDebug(lcTlsBackendSchannel, "Decrypted %lu bytes. New read buffer size: %d",
1918 dataBuffer[1].cbBuffer, buffer.size());
1919#endif
1920 }
1921 if (dataBuffer[3].BufferType == SECBUFFER_EXTRA) {
1922 // https://docs.microsoft.com/en-us/windows/desktop/secauthn/extra-buffers-returned-by-schannel
1923 // dataBuffer[3].cbBuffer indicates the amount of bytes _NOT_ processed,
1924 // the rest need to be stored.
1925 retainExtraData(intermediateBuffer, dataBuffer[3]);
1926 } else {
1927 intermediateBuffer.resize(0);
1928 }
1929 }
1930
1931 if (status == SEC_E_INCOMPLETE_MESSAGE) {
1932 missingData = checkIncompleteData(dataBuffer[0]);
1933#ifdef QSSLSOCKET_DEBUG
1934 qCDebug(lcTlsBackendSchannel, "We didn't have enough data to decrypt anything, will try again!");
1935#endif
1936 // We try again, but if we don't get any more data then we leave
1937 hadIncompleteData = true;
1938 } else if (status == SEC_E_INVALID_HANDLE) {
1939 // I don't think this should happen, if it does we're done...
1940 qCWarning(lcTlsBackendSchannel, "The internal SSPI handle is invalid!");
1941 Q_UNREACHABLE();
1942 } else if (status == SEC_E_INVALID_TOKEN) {
1943 // Supposedly we have an invalid token, it's under-documented what
1944 // this means, so to be safe we disconnect.
1945 shutdown = true;
1947 setErrorAndEmit(d, QAbstractSocket::SslInternalError, schannelErrorToString(status));
1948 break;
1949 } else if (status == SEC_E_MESSAGE_ALTERED) {
1950 // The message has been altered, disconnect now.
1951 shutdown = true; // skips sending the shutdown alert
1953 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1954 schannelErrorToString(status));
1955 break;
1956 } else if (status == SEC_E_OUT_OF_SEQUENCE) {
1957 // @todo: I don't know if this one is actually "fatal"..
1958 // This path might never be hit as it seems this is for connection-oriented connections,
1959 // while SEC_E_MESSAGE_ALTERED is for stream-oriented ones (what we use).
1960 shutdown = true; // skips sending the shutdown alert
1962 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1963 schannelErrorToString(status));
1964 break;
1965 } else if (status == SEC_E_DECRYPT_FAILURE) {
1966 // It's not documented as a possible return value for DecryptMessage,
1967 // but we see that this may happen - supposed to be a bug in Schannel (with TLS 1.3?)
1968 shutdown = true; // skips sending the shutdown alert
1970 setErrorAndEmit(d, QAbstractSocket::SslInternalError, schannelErrorToString(status));
1971 break;
1972 } else if (status == SEC_I_CONTEXT_EXPIRED) {
1973 // 'remote' has initiated a shutdown
1975 break;
1976 } else if (status == SEC_I_RENEGOTIATE) {
1977 // 'remote' wants to renegotiate
1978#ifdef QSSLSOCKET_DEBUG
1979 qCDebug(lcTlsBackendSchannel, "The peer wants to renegotiate.");
1980#endif
1981 schannelState = SchannelState::Renegotiate;
1982 renegotiating = true;
1983
1984 // We need to call 'continueHandshake' or else there's no guarantee it ever gets called
1986 break;
1987 }
1988 }
1989
1990 if (totalRead) {
1991 if (bool *readyReadEmittedPointer = d->readyReadPointer())
1992 *readyReadEmittedPointer = true;
1993 emit q->readyRead();
1994 emit q->channelReadyRead(0);
1995 }
1996}
1997
1998void TlsCryptographSchannel::sendShutdown()
1999{
2000 Q_ASSERT(d);
2001
2002 const bool isClient = d->tlsMode() == QSslSocket::SslClientMode;
2003 DWORD shutdownToken = SCHANNEL_SHUTDOWN;
2004 SecBuffer buffer = createSecBuffer(&shutdownToken, sizeof(DWORD), SECBUFFER_TOKEN);
2005 SecBufferDesc token{
2006 SECBUFFER_VERSION,
2007 1,
2008 &buffer
2009 };
2010 auto status = ApplyControlToken(&contextHandle, &token);
2011
2012 if (status != SEC_E_OK) {
2013#ifdef QSSLSOCKET_DEBUG
2014 qCDebug(lcTlsBackendSchannel)
2015 << "Failed to apply shutdown control token:" << schannelErrorToString(status);
2016#endif
2017 return;
2018 }
2019
2020 SecBuffer outBuffers[3];
2021 outBuffers[0] = createSecBuffer(nullptr, 0, SECBUFFER_TOKEN);
2022 outBuffers[1] = createSecBuffer(nullptr, 0, SECBUFFER_ALERT);
2023 outBuffers[2] = createSecBuffer(nullptr, 0, SECBUFFER_EMPTY);
2024 auto freeBuffers = qScopeGuard([&outBuffers]() {
2025 for (auto i = 0ull; i < ARRAYSIZE(outBuffers); i++) {
2026 if (outBuffers[i].pvBuffer)
2027 FreeContextBuffer(outBuffers[i].pvBuffer);
2028 }
2029 });
2030 SecBufferDesc outputBufferDesc{
2031 SECBUFFER_VERSION,
2032 ARRAYSIZE(outBuffers),
2033 outBuffers
2034 };
2035
2036 ULONG contextReq = getContextRequirements();
2037 TimeStamp expiry;
2038 if (isClient) {
2039 status = InitializeSecurityContext(&credentialHandle, // phCredential
2040 &contextHandle, // phContext
2041 const_reinterpret_cast<SEC_WCHAR *>(targetName().utf16()), // pszTargetName
2042 contextReq, // fContextReq
2043 0, // Reserved1
2044 0, // TargetDataRep (unused)
2045 nullptr, // pInput
2046 0, // Reserved2
2047 nullptr, // phNewContext (we already have one)
2048 &outputBufferDesc, // pOutput
2049 &contextAttributes, // pfContextAttr
2050 &expiry // ptsExpiry
2051 );
2052 } else {
2053 status = AcceptSecurityContext(
2054 &credentialHandle, // phCredential
2055 &contextHandle, // phContext
2056 nullptr, // pInput
2057 contextReq, // fContextReq
2058 0, // TargetDataRep (unused)
2059 nullptr, // phNewContext
2060 &outputBufferDesc, // pOutput
2061 &contextAttributes, // pfContextAttr,
2062 &expiry // ptsTimeStamp
2063 );
2064 }
2065 if (status == SEC_E_OK || status == SEC_I_CONTEXT_EXPIRED) {
2066 if (!sendToken(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer, false)) {
2067 // We failed to send the shutdown message, but it's not that important since we're
2068 // shutting down anyway.
2069 return;
2070 }
2071 } else {
2072#ifdef QSSLSOCKET_DEBUG
2073 qCDebug(lcTlsBackendSchannel)
2074 << "Failed to initialize shutdown:" << schannelErrorToString(status);
2075#endif
2076 }
2077}
2078
2080{
2081 Q_ASSERT(q);
2082 Q_ASSERT(d);
2083 auto *plainSocket = d->plainTcpSocket();
2084 Q_ASSERT(plainSocket);
2085
2086 if (SecIsValidHandle(&contextHandle)) {
2087 if (!shutdown) {
2088 shutdown = true;
2089 if (plainSocket->state() != QAbstractSocket::UnconnectedState && q->isEncrypted()) {
2090 sendShutdown();
2091 transmit();
2092 }
2093 }
2094 }
2095 plainSocket->disconnectFromHost();
2096}
2097
2099{
2100 Q_ASSERT(d);
2101 auto *plainSocket = d->plainTcpSocket();
2102 Q_ASSERT(plainSocket);
2103 d->setEncrypted(false);
2104
2105 shutdown = true;
2106 if (plainSocket->bytesAvailable() > 0 || hasUndecryptedData()) {
2107 // Read as much as possible because this is likely our last chance
2108 qint64 tempMax = d->maxReadBufferSize();
2109 d->setMaxReadBufferSize(0); // Unlimited
2110 transmit();
2111 d->setMaxReadBufferSize(tempMax);
2112 // Since there were bytes still available we don't want to deallocate
2113 // our context yet. It will happen later, when the socket is re-used or
2114 // destroyed.
2115 } else {
2116 deallocateContext();
2117 freeCredentialsHandle();
2118 }
2119}
2120
2122{
2123 Q_ASSERT(q);
2124
2125 if (!q->isEncrypted())
2126 return {};
2127
2128 const auto sessionProtocol = toQtSslProtocol(connectionInfo.dwProtocol);
2129
2130 const auto ciphers = ciphersByName(QStringView(cipherInfo.szCipherSuite));
2131 for (const auto& cipher : ciphers) {
2132 if (cipher.protocol() == sessionProtocol)
2133 return cipher;
2134 }
2135
2136 return {};
2137}
2138
2140{
2141 if (!q->isEncrypted())
2142 return QSsl::SslProtocol::UnknownProtocol;
2143 return toQtSslProtocol(connectionInfo.dwProtocol);
2144}
2145
2147{
2148 Q_ASSERT(q);
2149 Q_ASSERT(d);
2150 auto *plainSocket = d->plainTcpSocket();
2151 Q_ASSERT(plainSocket);
2152
2153 const bool isServer = d->tlsMode() == QSslSocket::SslServerMode;
2154 switch (schannelState) {
2155 case SchannelState::InitializeHandshake:
2156 if (!SecIsValidHandle(&credentialHandle) && !acquireCredentialsHandle()) {
2158 return;
2159 }
2160 if (!SecIsValidHandle(&credentialHandle)) // Needed to support tst_QSslSocket::setEmptyKey
2161 return;
2162 if (!SecIsValidHandle(&contextHandle) && !(isServer ? acceptContext() : createContext())) {
2164 return;
2165 }
2166 if (schannelState != SchannelState::PerformHandshake)
2167 break;
2168 Q_FALLTHROUGH();
2169 case SchannelState::PerformHandshake:
2170 if (!performHandshake()) {
2172 return;
2173 }
2174 if (schannelState != SchannelState::VerifyHandshake)
2175 break;
2176 Q_FALLTHROUGH();
2177 case SchannelState::VerifyHandshake:
2178 // if we're in shutdown or renegotiating then we might not need to verify
2179 // (since we already did)
2180 if (!verifyHandshake()) {
2181 shutdown = true; // Skip sending shutdown alert
2182 q->abort(); // We don't want to send buffered data
2184 return;
2185 }
2186 if (schannelState != SchannelState::Done)
2187 break;
2188 Q_FALLTHROUGH();
2189 case SchannelState::Done:
2190 // connectionEncrypted is already true if we come here from a renegotiation
2191 if (!q->isEncrypted()) {
2192 d->setEncrypted(true); // all is done
2193 emit q->encrypted();
2194 }
2195 renegotiating = false;
2196 if (d->isPendingClose()) {
2197 d->setPendingClose(false);
2199 } else {
2200 transmit();
2201 }
2202 break;
2203 case SchannelState::Renegotiate:
2204 if (!renegotiate()) {
2206 return;
2207 } else if (intermediateBuffer.size() || plainSocket->bytesAvailable()) {
2209 }
2210 break;
2211 }
2212}
2213
2215{
2216 return sslErrors;
2217}
2218
2219/*
2220 Copied from qsslsocket_mac.cpp, which was copied from qsslsocket_openssl.cpp
2221*/
2222bool TlsCryptographSchannel::checkSslErrors()
2223{
2224 if (sslErrors.isEmpty())
2225 return true;
2226
2227 Q_ASSERT(q);
2228 Q_ASSERT(d);
2229 const auto &configuration = q->sslConfiguration();
2230 auto *plainSocket = d->plainTcpSocket();
2231
2232 emit q->sslErrors(sslErrors);
2233
2234 const bool doVerifyPeer = configuration.peerVerifyMode() == QSslSocket::VerifyPeer
2235 || (configuration.peerVerifyMode() == QSslSocket::AutoVerifyPeer
2236 && d->tlsMode() == QSslSocket::SslClientMode);
2237 const bool doEmitSslError = !d->verifyErrorsHaveBeenIgnored();
2238 // check whether we need to emit an SSL handshake error
2239 if (doVerifyPeer && doEmitSslError) {
2240 if (q->pauseMode() & QAbstractSocket::PauseOnSslErrors) {
2241 QSslSocketPrivate::pauseSocketNotifiers(q);
2242 d->setPaused(true);
2243 } else {
2244 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
2245 sslErrors.constFirst().errorString());
2246 plainSocket->disconnectFromHost();
2247 }
2248 return false;
2249 }
2250
2251 return true;
2252}
2253
2254static void attachPrivateKeyToCertificate(const QSslCertificate &certificate,
2255 const QSslKey &privateKey)
2256{
2257 QAsn1Element elem = _q_PKCS12_key(privateKey);
2258 QByteArray buffer;
2259 QDataStream stream(&buffer, QDataStream::WriteOnly);
2260 elem.write(stream);
2261 NCRYPT_PROV_HANDLE provider = 0;
2262 SECURITY_STATUS status = NCryptOpenStorageProvider(&provider, MS_KEY_STORAGE_PROVIDER, 0);
2263 if (status != SEC_E_OK) {
2264 qCWarning(lcTlsBackendSchannel())
2265 << "Failed to open ncrypt storage provider:" << schannelErrorToString(status);
2266 return;
2267 }
2268 const auto freeProvider = qScopeGuard([provider]() { NCryptFreeObject(provider); });
2269
2270 const QString certName = certificate.subjectInfo(QSslCertificate::CommonName).front();
2271 QSpan<const QChar> nameSpan(certName);
2272 NCryptBuffer nbuffer{ ULONG(nameSpan.size_bytes() + sizeof(char16_t)),
2273 NCRYPTBUFFER_PKCS_KEY_NAME,
2274 const_reinterpret_cast<void *>(nameSpan.data()) };
2275 NCryptBufferDesc bufferDesc{ NCRYPTBUFFER_VERSION, 1, &nbuffer };
2276 NCRYPT_KEY_HANDLE ncryptKey = 0;
2277 status = NCryptImportKey(provider, 0, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, &bufferDesc, &ncryptKey,
2278 PBYTE(buffer.data()), buffer.size(), 0);
2279 if (status != SEC_E_OK) {
2280 qCWarning(lcTlsBackendSchannel())
2281 << "Failed to import private key:" << schannelErrorToString(status);
2282 return;
2283 }
2284 const auto freeKey = qScopeGuard([ncryptKey]() { NCryptFreeObject(ncryptKey); });
2285
2286 CERT_CONTEXT *context = PCERT_CONTEXT(certificate.handle());
2287 Q_ASSERT(context);
2288
2289 CRYPT_DATA_BLOB keyBlob = { sizeof(ncryptKey), PBYTE(&ncryptKey) };
2290 BOOL ok =
2291 CertSetCertificateContextProperty(context, CERT_NCRYPT_KEY_HANDLE_PROP_ID, 0, &keyBlob);
2292 if (!ok) {
2293 auto error = GetLastError();
2294 if (lcTlsBackendSchannel().isWarningEnabled())
2295 qErrnoWarning(int(error), "Failed to set ncrypt handle property.");
2296 return;
2297 }
2298
2299 CRYPT_KEY_PROV_INFO provInfo{
2300 const_reinterpret_cast<LPWSTR>(certName.constData()),
2301 const_cast<LPWSTR>(MS_KEY_STORAGE_PROVIDER),
2302 0,
2303 CERT_SET_KEY_PROV_HANDLE_PROP_ID | CERT_SET_KEY_CONTEXT_PROP_ID,
2304 0,
2305 nullptr,
2306 0,
2307 };
2308 ok = CertSetCertificateContextProperty(context, CERT_KEY_PROV_INFO_PROP_ID,
2309 CERT_SET_PROPERTY_INHIBIT_PERSIST_FLAG, &provInfo);
2310 if (!ok) {
2311 auto error = GetLastError();
2312 if (lcTlsBackendSchannel().isWarningEnabled())
2313 qErrnoWarning(int(error), "Failed to set key provider info property.");
2314 return;
2315 }
2316}
2317
2318void TlsCryptographSchannel::initializeCertificateStores()
2319{
2320 //// helper function which turns a chain into a certificate store
2321 Q_ASSERT(d);
2322 Q_ASSERT(q);
2323 const auto &configuration = q->sslConfiguration();
2324
2325 auto createStoreFromCertificateChain = [](const QList<QSslCertificate> certChain, const QSslKey &privateKey) {
2326 const wchar_t *passphrase = L"";
2327 // Need to embed the private key in the certificate
2328 QByteArray pkcs12 = _q_makePkcs12(certChain,
2329 privateKey,
2330 QString::fromWCharArray(passphrase, 0));
2331 CRYPT_DATA_BLOB pfxBlob;
2332 pfxBlob.cbData = DWORD(pkcs12.length());
2333 pfxBlob.pbData = reinterpret_cast<unsigned char *>(pkcs12.data());
2334 // ALWAYS_CNG to import using "Cryptography API: Next Generation (CNG)"
2335 // NO_PERSIST_KEY to request not persisting anything imported to disk
2336 constexpr DWORD flags = PKCS12_ALWAYS_CNG_KSP | PKCS12_NO_PERSIST_KEY;
2337 return QHCertStorePointer(PFXImportCertStore(&pfxBlob, passphrase, flags));
2338 };
2339
2340 if (!configuration.localCertificateChain().isEmpty()) {
2341 if (configuration.privateKey().isNull()) {
2342 setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError,
2343 QSslSocket::tr("Cannot provide a certificate with no key"));
2344 return;
2345 }
2346 if (localCertificateStore == nullptr) {
2347 localCertificateStore =
2348 createStoreFromCertificateChain(configuration.localCertificateChain(), {});
2349 if (localCertificateStore) {
2350 const CERT_CONTEXT *certificateContext = CertFindCertificateInStore(
2351 localCertificateStore.get(), X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0,
2352 CERT_FIND_ANY, nullptr, nullptr);
2353 if (certificateContext) {
2354 auto *backend = QTlsBackend::backend<X509CertificateSchannel>(
2355 configuration.localCertificate());
2356 backend->certificateContext.reset(
2357 CertDuplicateCertificateContext(certificateContext));
2358
2359 DWORD keySpec = 0;
2360 BOOL mustFree = FALSE;
2361 NCRYPT_KEY_HANDLE testKey = 0;
2362 BOOL ok = CryptAcquireCertificatePrivateKey(
2363 certificateContext, CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG, nullptr,
2364 &testKey, &keySpec, &mustFree);
2365 if (mustFree)
2366 NCryptFreeObject(testKey);
2367 if (!ok) {
2368 attachPrivateKeyToCertificate(configuration.localCertificate(),
2369 configuration.privateKey());
2370 }
2371 }
2372 } else {
2373 qCWarning(lcTlsBackendSchannel, "Failed to load certificate chain!");
2374 }
2375 }
2376 }
2377
2378 if (!configuration.caCertificates().isEmpty() && !caCertificateStore) {
2379 caCertificateStore = createStoreFromCertificateChain(configuration.caCertificates(),
2380 {}); // No private key for the CA certs
2381 }
2382}
2383
2384bool TlsCryptographSchannel::verifyCertContext(CERT_CONTEXT *certContext)
2385{
2386 Q_ASSERT(certContext);
2387 Q_ASSERT(q);
2388 Q_ASSERT(d);
2389
2390 const bool isClient = d->tlsMode() == QSslSocket::SslClientMode;
2391
2392 // Create a collection of stores so we can pass in multiple stores as additional locations to
2393 // search for the certificate chain
2394 auto tempCertCollection = QHCertStorePointer(CertOpenStore(CERT_STORE_PROV_COLLECTION,
2395 X509_ASN_ENCODING,
2396 0,
2397 CERT_STORE_CREATE_NEW_FLAG,
2398 nullptr));
2399 if (!tempCertCollection) {
2400#ifdef QSSLSOCKET_DEBUG
2401 qCWarning(lcTlsBackendSchannel, "Failed to create certificate store collection!");
2402#endif
2403 return false;
2404 }
2405
2406 if (rootCertOnDemandLoadingAllowed()) {
2407 // @future(maybe): following the OpenSSL backend these certificates should be added into
2408 // the Ca list, not just included during verification.
2409 // That being said, it's not trivial to add the root certificates (if and only if they
2410 // came from the system root store). And I don't see this mentioned in our documentation.
2411 auto rootStore = QHCertStorePointer(
2412 CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0,
2413 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER, L"ROOT"));
2414
2415 if (!rootStore) {
2416#ifdef QSSLSOCKET_DEBUG
2417 qCWarning(lcTlsBackendSchannel, "Failed to open the system root CA certificate store!");
2418#endif
2419 return false;
2420 } else if (!CertAddStoreToCollection(tempCertCollection.get(), rootStore.get(), 0, 1)) {
2421#ifdef QSSLSOCKET_DEBUG
2422 qCWarning(lcTlsBackendSchannel,
2423 "Failed to add the system root CA certificate store to the certificate store "
2424 "collection!");
2425#endif
2426 return false;
2427 }
2428 }
2429 if (caCertificateStore) {
2430 if (!CertAddStoreToCollection(tempCertCollection.get(), caCertificateStore.get(), 0, 1)) {
2431#ifdef QSSLSOCKET_DEBUG
2432 qCWarning(lcTlsBackendSchannel,
2433 "Failed to add the user's CA certificate store to the certificate store "
2434 "collection!");
2435#endif
2436 return false;
2437 }
2438 }
2439
2440 if (!CertAddStoreToCollection(tempCertCollection.get(), certContext->hCertStore, 0, 0)) {
2441#ifdef QSSLSOCKET_DEBUG
2442 qCWarning(lcTlsBackendSchannel,
2443 "Failed to add certificate's origin store to the certificate store collection!");
2444#endif
2445 return false;
2446 }
2447
2448 CERT_CHAIN_PARA parameters;
2449 ZeroMemory(&parameters, sizeof(parameters));
2450 parameters.cbSize = sizeof(CERT_CHAIN_PARA);
2451 parameters.RequestedUsage.dwType = USAGE_MATCH_TYPE_AND;
2452 parameters.RequestedUsage.Usage.cUsageIdentifier = 1;
2453 LPSTR oid = LPSTR(isClient ? szOID_PKIX_KP_SERVER_AUTH
2454 : szOID_PKIX_KP_CLIENT_AUTH);
2455 parameters.RequestedUsage.Usage.rgpszUsageIdentifier = &oid;
2456
2457 QTlsBackend::clearPeerCertificates(d);
2458 const CERT_CHAIN_CONTEXT *chainContext = nullptr;
2459 auto freeCertChain = qScopeGuard([&chainContext]() {
2460 if (chainContext)
2461 CertFreeCertificateChain(chainContext);
2462 });
2463 BOOL status = CertGetCertificateChain(nullptr, // hChainEngine, default
2464 certContext, // pCertContext
2465 nullptr, // pTime, 'now'
2466 tempCertCollection.get(), // hAdditionalStore, additional cert store
2467 &parameters, // pChainPara
2468 CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT, // dwFlags
2469 nullptr, // reserved
2470 &chainContext // ppChainContext
2471 );
2472 if (status == FALSE || !chainContext || chainContext->cChain == 0) {
2473 QSslError error(QSslError::UnableToVerifyFirstCertificate);
2474 sslErrors += error;
2475 emit q->peerVerifyError(error);
2476 return q->state() == QAbstractSocket::ConnectedState;
2477 }
2478
2479 // Helper-function to get a QSslCertificate given a CERT_CHAIN_ELEMENT
2480 static auto getCertificateFromChainElement = [](CERT_CHAIN_ELEMENT *element) {
2481 if (!element)
2482 return QSslCertificate();
2483
2484 const CERT_CONTEXT *certContext = element->pCertContext;
2485 return QTlsPrivate::X509CertificateSchannel::QSslCertificate_from_CERT_CONTEXT(certContext);
2486 };
2487
2488 // Pick a chain to use as the certificate chain, if multiple are available:
2489 // According to https://docs.microsoft.com/en-gb/windows/desktop/api/wincrypt/ns-wincrypt-_cert_chain_context
2490 // this seems to be the best way to get a trusted chain.
2491 CERT_SIMPLE_CHAIN *chain = chainContext->rgpChain[chainContext->cChain - 1];
2492
2493 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_PARTIAL_CHAIN) {
2494 auto error = QSslError(QSslError::SslError::UnableToGetIssuerCertificate,
2495 getCertificateFromChainElement(chain->rgpElement[chain->cElement - 1]));
2496 sslErrors += error;
2497 emit q->peerVerifyError(error);
2498 if (q->state() != QAbstractSocket::ConnectedState)
2499 return false;
2500 }
2501 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_INVALID_BASIC_CONSTRAINTS) {
2502 // @Note: This is actually one of two errors:
2503 // "either the certificate cannot be used to issue other certificates, or the chain path length has been exceeded."
2504 // But here we are checking the chain's status, so we assume the "issuing" error cannot occur here.
2505 auto error = QSslError(QSslError::PathLengthExceeded);
2506 sslErrors += error;
2507 emit q->peerVerifyError(error);
2508 if (q->state() != QAbstractSocket::ConnectedState)
2509 return false;
2510 }
2511 static const DWORD leftoverCertChainErrorMask = CERT_TRUST_IS_CYCLIC | CERT_TRUST_INVALID_EXTENSION
2512 | CERT_TRUST_INVALID_POLICY_CONSTRAINTS | CERT_TRUST_INVALID_NAME_CONSTRAINTS
2513 | CERT_TRUST_CTL_IS_NOT_TIME_VALID | CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID
2514 | CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE;
2515 if (chain->TrustStatus.dwErrorStatus & leftoverCertChainErrorMask) {
2516 auto error = QSslError(QSslError::SslError::UnspecifiedError);
2517 sslErrors += error;
2518 emit q->peerVerifyError(error);
2519 if (q->state() != QAbstractSocket::ConnectedState)
2520 return false;
2521 }
2522
2523 DWORD verifyDepth = chain->cElement;
2524 if (q->peerVerifyDepth() > 0 && DWORD(q->peerVerifyDepth()) < verifyDepth)
2525 verifyDepth = DWORD(q->peerVerifyDepth());
2526
2527 const auto &caCertificates = q->sslConfiguration().caCertificates();
2528
2529 if (!rootCertOnDemandLoadingAllowed()
2530 && !(chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_PARTIAL_CHAIN)
2531 && (q->peerVerifyMode() == QSslSocket::VerifyPeer
2532 || (isClient && q->peerVerifyMode() == QSslSocket::AutoVerifyPeer))) {
2533 // When verifying a peer Windows "helpfully" builds a chain that
2534 // may include roots from the system store. But we don't want that if
2535 // the user has set their own CA certificates.
2536 // Since Windows claims this is not a partial chain the root is included
2537 // and we have to check that it is one of our configured CAs.
2538 CERT_CHAIN_ELEMENT *element = chain->rgpElement[chain->cElement - 1];
2539 QSslCertificate certificate = getCertificateFromChainElement(element);
2540 if (!caCertificates.contains(certificate)) {
2541 auto error = QSslError(QSslError::CertificateUntrusted, certificate);
2542 sslErrors += error;
2543 emit q->peerVerifyError(error);
2544 if (q->state() != QAbstractSocket::ConnectedState)
2545 return false;
2546 }
2547 }
2548
2549 QList<QSslCertificate> peerCertificateChain;
2550 for (DWORD i = 0; i < verifyDepth; i++) {
2551 CERT_CHAIN_ELEMENT *element = chain->rgpElement[i];
2552 QSslCertificate certificate = getCertificateFromChainElement(element);
2553 if (certificate.isNull()) {
2554 const auto &previousCert = !peerCertificateChain.isEmpty() ? peerCertificateChain.last()
2555 : QSslCertificate();
2556 auto error = QSslError(QSslError::SslError::UnableToGetIssuerCertificate, previousCert);
2557 sslErrors += error;
2558 emit q->peerVerifyError(error);
2559 if (previousCert.isNull() || q->state() != QAbstractSocket::ConnectedState)
2560 return false;
2561 }
2562 const QList<QSslCertificateExtension> extensions = certificate.extensions();
2563
2564#ifdef QSSLSOCKET_DEBUG
2565 qCDebug(lcTlsBackendSchannel) << "issuer:" << certificate.issuerDisplayName()
2566 << "\nsubject:" << certificate.subjectDisplayName()
2567 << "\nQSslCertificate info:" << certificate
2568 << "\nextended error info:" << element->pwszExtendedErrorInfo
2569 << "\nerror status:" << element->TrustStatus.dwErrorStatus;
2570#endif
2571
2572 peerCertificateChain.append(certificate);
2573 QTlsBackend::storePeerCertificateChain(d, peerCertificateChain);
2574
2575 if (certificate.isBlacklisted()) {
2576 const auto error = QSslError(QSslError::CertificateBlacklisted, certificate);
2577 sslErrors += error;
2578 emit q->peerVerifyError(error);
2579 if (q->state() != QAbstractSocket::ConnectedState)
2580 return false;
2581 }
2582
2583 LONG result = CertVerifyTimeValidity(nullptr /*== now */, element->pCertContext->pCertInfo);
2584 if (result != 0) {
2585 auto error = QSslError(result == -1 ? QSslError::CertificateNotYetValid
2586 : QSslError::CertificateExpired,
2587 certificate);
2588 sslErrors += error;
2589 emit q->peerVerifyError(error);
2590 if (q->state() != QAbstractSocket::ConnectedState)
2591 return false;
2592 }
2593
2594 //// Errors
2595 if (element->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID) {
2596 // handled right above
2597 Q_ASSERT(!sslErrors.isEmpty());
2598 }
2599 if (element->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED) {
2600 auto error = QSslError(QSslError::CertificateRevoked, certificate);
2601 sslErrors += error;
2602 emit q->peerVerifyError(error);
2603 if (q->state() != QAbstractSocket::ConnectedState)
2604 return false;
2605 }
2606 if (element->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_SIGNATURE_VALID) {
2607 auto error = QSslError(QSslError::CertificateSignatureFailed, certificate);
2608 sslErrors += error;
2609 emit q->peerVerifyError(error);
2610 if (q->state() != QAbstractSocket::ConnectedState)
2611 return false;
2612 }
2613
2614 // While netscape shouldn't be relevant now it defined an extension which is
2615 // still in use. Schannel does not check this automatically, so we do it here.
2616 // It is used to differentiate between client and server certificates.
2617 if (netscapeWrongCertType(extensions, isClient, i == 0))
2618 element->TrustStatus.dwErrorStatus |= CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
2619
2620 if (element->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_VALID_FOR_USAGE) {
2621 auto error = QSslError(QSslError::InvalidPurpose, certificate);
2622 sslErrors += error;
2623 emit q->peerVerifyError(error);
2624 if (q->state() != QAbstractSocket::ConnectedState)
2625 return false;
2626 }
2627 if (element->TrustStatus.dwErrorStatus & CERT_TRUST_IS_UNTRUSTED_ROOT) {
2628 // Override this error if we have the certificate inside our trusted CAs list.
2629 const bool isTrustedRoot = caCertificates.contains(certificate);
2630 if (!isTrustedRoot) {
2631 auto error = QSslError(QSslError::CertificateUntrusted, certificate);
2632 sslErrors += error;
2633 emit q->peerVerifyError(error);
2634 if (q->state() != QAbstractSocket::ConnectedState)
2635 return false;
2636 }
2637 }
2638 static const DWORD certRevocationCheckUnavailableError = CERT_TRUST_IS_OFFLINE_REVOCATION
2639 | CERT_TRUST_REVOCATION_STATUS_UNKNOWN;
2640 if (element->TrustStatus.dwErrorStatus & certRevocationCheckUnavailableError) {
2641 // @future(maybe): Do something with this
2642 }
2643
2644 // Dumping ground of errors that don't fit our specific errors
2645 static const DWORD leftoverCertErrorMask = CERT_TRUST_IS_CYCLIC
2646 | CERT_TRUST_INVALID_EXTENSION | CERT_TRUST_INVALID_NAME_CONSTRAINTS
2647 | CERT_TRUST_INVALID_POLICY_CONSTRAINTS
2648 | CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT
2649 | CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT
2650 | CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT
2651 | CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT
2652 | CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
2653 if (element->TrustStatus.dwErrorStatus & leftoverCertErrorMask) {
2654 auto error = QSslError(QSslError::UnspecifiedError, certificate);
2655 sslErrors += error;
2656 emit q->peerVerifyError(error);
2657 if (q->state() != QAbstractSocket::ConnectedState)
2658 return false;
2659 }
2660 if (element->TrustStatus.dwErrorStatus & CERT_TRUST_INVALID_BASIC_CONSTRAINTS) {
2661 auto it = std::find_if(extensions.cbegin(), extensions.cend(),
2662 [](const QSslCertificateExtension &extension) {
2663 return extension.name() == "basicConstraints"_L1;
2664 });
2665 if (it != extensions.cend()) {
2666 // @Note: This is actually one of two errors:
2667 // "either the certificate cannot be used to issue other certificates,
2668 // or the chain path length has been exceeded."
2669 QVariantMap basicConstraints = it->value().toMap();
2670 QSslError error;
2671 if (i > 0 && !basicConstraints.value("ca"_L1, false).toBool())
2672 error = QSslError(QSslError::InvalidPurpose, certificate);
2673 else
2674 error = QSslError(QSslError::PathLengthExceeded, certificate);
2675 sslErrors += error;
2676 emit q->peerVerifyError(error);
2677 if (q->state() != QAbstractSocket::ConnectedState)
2678 return false;
2679 }
2680 }
2681 if (element->TrustStatus.dwErrorStatus & CERT_TRUST_IS_EXPLICIT_DISTRUST) {
2682 auto error = QSslError(QSslError::CertificateBlacklisted, certificate);
2683 sslErrors += error;
2684 emit q->peerVerifyError(error);
2685 if (q->state() != QAbstractSocket::ConnectedState)
2686 return false;
2687 }
2688
2689 if (element->TrustStatus.dwInfoStatus & CERT_TRUST_IS_SELF_SIGNED) {
2690 // If it's self-signed *and* a CA then we can assume it's a root CA certificate
2691 // and we can ignore the "self-signed" note:
2692 // We check the basicConstraints certificate extension when possible, but this didn't
2693 // exist for version 1, so we can only guess in that case
2694 const bool isRootCertificateAuthority = isCertificateAuthority(extensions)
2695 || certificate.version() == "1";
2696
2697 // Root certificate tends to be signed by themselves, so ignore self-signed status.
2698 if (!isRootCertificateAuthority) {
2699 auto error = QSslError(QSslError::SelfSignedCertificate, certificate);
2700 sslErrors += error;
2701 emit q->peerVerifyError(error);
2702 if (q->state() != QAbstractSocket::ConnectedState)
2703 return false;
2704 }
2705 }
2706 }
2707
2708 if (!peerCertificateChain.isEmpty())
2709 QTlsBackend::storePeerCertificate(d, peerCertificateChain.constFirst());
2710
2711 const auto &configuration = q->sslConfiguration(); // Probably, updated by QTlsBackend::storePeerCertificate etc.
2712 // @Note: Somewhat copied from qsslsocket_mac.cpp
2713 const bool doVerifyPeer = q->peerVerifyMode() == QSslSocket::VerifyPeer
2714 || (q->peerVerifyMode() == QSslSocket::AutoVerifyPeer
2715 && d->tlsMode() == QSslSocket::SslClientMode);
2716 // Check the peer certificate itself. First try the subject's common name
2717 // (CN) as a wildcard, then try all alternate subject name DNS entries the
2718 // same way.
2719 if (!configuration.peerCertificate().isNull()) {
2720 // but only if we're a client connecting to a server
2721 // if we're the server, don't check CN
2722 if (d->tlsMode() == QSslSocket::SslClientMode) {
2723 const auto verificationPeerName = d->verificationName();
2724 const QString peerName(verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName);
2725 if (!isMatchingHostname(configuration.peerCertificate(), peerName)) {
2726 // No matches in common names or alternate names.
2727 const QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate());
2728 sslErrors += error;
2729 emit q->peerVerifyError(error);
2730 if (q->state() != QAbstractSocket::ConnectedState)
2731 return false;
2732 }
2733 }
2734 } else if (doVerifyPeer) {
2735 // No peer certificate presented. Report as error if the socket
2736 // expected one.
2737 const QSslError error(QSslError::NoPeerCertificate);
2738 sslErrors += error;
2739 emit q->peerVerifyError(error);
2740 if (q->state() != QAbstractSocket::ConnectedState)
2741 return false;
2742 }
2743
2744 return true;
2745}
2746
2747bool TlsCryptographSchannel::rootCertOnDemandLoadingAllowed()
2748{
2749 Q_ASSERT(d);
2750 return d->isRootsOnDemandAllowed() && QSslSocketPrivate::rootCertOnDemandLoadingSupported();
2751}
2752
2753} // namespace QTlsPrivate
2754
2755QT_END_NAMESPACE
void init(QSslSocket *q, QSslSocketPrivate *d) override
QSsl::SslProtocol sessionProtocol() const override
bool hasUndecryptedData() const override
QSslCipher sessionCipher() const override
QList< QSslError > tlsErrors() const override
Q_DISABLE_COPY_MOVE(X509CertificateSchannel)
Combined button and popup list for selecting options.
Namespace containing onternal types that TLS backends implement.
QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED std::array< SchannelCipherInfo, 44 > schannelCipherInfo
QList< QSslCipher > defaultCiphers()
UNICODE_STRING cbcChainingMode
QList< CRYPTO_SETTINGS > cryptoSettingsForCiphers(const QList< QSslCipher > &ciphers)
bool containsTls13Cipher(const QList< QSslCipher > &ciphers)
UNICODE_STRING gcmChainingMode
QList< QSslCipher > ciphersByName(QStringView schannelSuiteName)
static void attachPrivateKeyToCertificate(const QSslCertificate &certificate, const QSslKey &privateKey)
Q_LOGGING_CATEGORY(lcEventDispatcher, "qt.eventdispatcher")
Q_GLOBAL_STATIC(QReadWriteLock, g_updateMutex)
#define SP_PROT_TLS1_0_SERVER
#define SP_PROT_TLS1_1_SERVER
#define SP_PROT_TLS1_2_SERVER
#define BCRYPT_ECDSA_ALGORITHM
#define SP_PROT_TLS1_2
#define SP_PROT_TLS1_3_SERVER
#define MAP_PROTOCOL(sp_protocol, q_protocol)
#define SP_PROT_TLS1_0
#define SP_PROT_TLS1_3
#define CHECK_STATUS(status)
#define CHECK_ATTRIBUTE(attributeName)
#define DEBUG_WARN(message)
QByteArray _q_makePkcs12(const QList< QSslCertificate > &certs, const QSslKey &key, const QString &passPhrase)
#define SP_PROT_TLS1_1_CLIENT
#define SP_PROT_TLS1_SERVER
QAsn1Element _q_PKCS12_key(const QSslKey &key)
#define BCRYPT_ECDH_ALGORITHM
#define SP_PROT_TLS1_3_CLIENT
#define SP_PROT_TLS1_1
#define SEC_E_APPLICATION_PROTOCOL_MISMATCH
#define SP_PROT_TLS1_CLIENT
#define SP_PROT_TLS1_0_CLIENT
#define SECBUFFER_ALERT
#define SP_PROT_TLS1_2_CLIENT
QList< QSsl::SslProtocol > protocols