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 auto status = InitializeSecurityContext(&credentialHandle, // phCredential
1242 nullptr, // phContext
1243 const_reinterpret_cast<SEC_WCHAR *>(targetName().utf16()), // pszTargetName
1244 contextReq, // fContextReq
1245 0, // Reserved1
1246 0, // TargetDataRep (unused)
1247 useAlpn ? &alpnBufferDesc : nullptr, // pInput
1248 0, // Reserved2
1249 &contextHandle, // phNewContext
1250 &outputBufferDesc, // pOutput
1251 &contextAttributes, // pfContextAttr
1252 &expiry // ptsExpiry
1253 );
1254
1255 // This is the first call to InitializeSecurityContext, so theoretically "CONTINUE_NEEDED"
1256 // should be the only non-error return-code here.
1257 if (status != SEC_I_CONTINUE_NEEDED) {
1258 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1259 QSslSocket::tr("Error creating SSL context (%1)").arg(schannelErrorToString(status)));
1260 return false;
1261 }
1262
1263 if (!sendToken(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer))
1264 return false;
1265 schannelState = SchannelState::PerformHandshake;
1266 return true;
1267}
1268
1269bool TlsCryptographSchannel::acceptContext()
1270{
1271 Q_ASSERT(d);
1272 Q_ASSERT(q);
1273
1274 auto *plainSocket = d->plainTcpSocket();
1275 Q_ASSERT(plainSocket);
1276
1277 Q_ASSERT(SecIsValidHandle(&credentialHandle));
1278 Q_ASSERT(schannelState == SchannelState::InitializeHandshake);
1279 Q_ASSERT(d->tlsMode() == QSslSocket::SslServerMode);
1280 ULONG contextReq = getContextRequirements();
1281
1282 if (missingData > plainSocket->bytesAvailable())
1283 return true;
1284
1285 missingData = 0;
1286 readToBuffer(intermediateBuffer, plainSocket);
1287 if (intermediateBuffer.isEmpty())
1288 return true; // definitely need more data..
1289
1290 SecBuffer inBuffers[2];
1291 inBuffers[0] = createSecBuffer(intermediateBuffer, SECBUFFER_TOKEN);
1292
1293#ifdef SUPPORTS_ALPN
1294 QTlsBackend::setAlpnStatus(d, QSslConfiguration::NextProtocolNegotiationNone);
1295 // The string must be alive when we call AcceptSecurityContext
1296 QByteArray alpnString = createAlpnString(q->sslConfiguration().allowedNextProtocols());
1297 if (!alpnString.isEmpty()) {
1298 inBuffers[1] = createSecBuffer(alpnString, SECBUFFER_APPLICATION_PROTOCOLS);
1299 } else
1300#endif
1301 {
1302 inBuffers[1] = createSecBuffer(nullptr, 0, SECBUFFER_EMPTY);
1303 }
1304
1305 SecBufferDesc inputBufferDesc{
1306 SECBUFFER_VERSION,
1307 ARRAYSIZE(inBuffers),
1308 inBuffers
1309 };
1310
1311 SecBuffer outBuffers[3];
1312 outBuffers[0] = createSecBuffer(nullptr, 0, SECBUFFER_TOKEN);
1313 outBuffers[1] = createSecBuffer(nullptr, 0, SECBUFFER_ALERT);
1314 outBuffers[2] = createSecBuffer(nullptr, 0, SECBUFFER_EMPTY);
1315 auto freeBuffers = qScopeGuard([&outBuffers]() {
1316 for (auto i = 0ull; i < ARRAYSIZE(outBuffers); i++) {
1317 if (outBuffers[i].pvBuffer)
1318 FreeContextBuffer(outBuffers[i].pvBuffer);
1319 }
1320 });
1321 SecBufferDesc outputBufferDesc{
1322 SECBUFFER_VERSION,
1323 ARRAYSIZE(outBuffers),
1324 outBuffers
1325 };
1326
1327 TimeStamp expiry;
1328 auto status = AcceptSecurityContext(
1329 &credentialHandle, // phCredential
1330 nullptr, // phContext
1331 &inputBufferDesc, // pInput
1332 contextReq, // fContextReq
1333 0, // TargetDataRep (unused)
1334 &contextHandle, // phNewContext
1335 &outputBufferDesc, // pOutput
1336 &contextAttributes, // pfContextAttr
1337 &expiry // ptsTimeStamp
1338 );
1339
1340 if (status == SEC_E_INCOMPLETE_MESSAGE) {
1341 // Need more data
1342 missingData = checkIncompleteData(outBuffers[0]);
1343 return true;
1344 }
1345
1346 if (inBuffers[1].BufferType == SECBUFFER_EXTRA) {
1347 // https://docs.microsoft.com/en-us/windows/desktop/secauthn/extra-buffers-returned-by-schannel
1348 // inBuffers[1].cbBuffer indicates the amount of bytes _NOT_ processed, the rest need to
1349 // be stored.
1350 retainExtraData(intermediateBuffer, inBuffers[1]);
1351 } else { /* No 'extra' data, message not incomplete */
1352 intermediateBuffer.resize(0);
1353 }
1354
1355 if (status != SEC_I_CONTINUE_NEEDED) {
1356 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
1357 QSslSocket::tr("Error creating SSL context (%1)").arg(schannelErrorToString(status)));
1358 return false;
1359 }
1360 if (!sendToken(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer))
1361 return false;
1362 schannelState = SchannelState::PerformHandshake;
1363 return true;
1364}
1365
1366bool TlsCryptographSchannel::performHandshake()
1367{
1368 Q_ASSERT(d);
1369 auto *plainSocket = d->plainTcpSocket();
1370 Q_ASSERT(plainSocket);
1371
1372 if (plainSocket->state() == QAbstractSocket::UnconnectedState || !plainSocket->isValid()
1373 || !plainSocket->isOpen()) {
1374 setErrorAndEmit(d, QAbstractSocket::RemoteHostClosedError,
1375 QSslSocket::tr("The TLS/SSL connection has been closed"));
1376 return false;
1377 }
1378 Q_ASSERT(SecIsValidHandle(&credentialHandle));
1379 Q_ASSERT(SecIsValidHandle(&contextHandle));
1380 Q_ASSERT(schannelState == SchannelState::PerformHandshake);
1381
1382#ifdef QSSLSOCKET_DEBUG
1383 qCDebug(lcTlsBackendSchannel, "Bytes available from socket: %lld",
1384 plainSocket->bytesAvailable());
1385 qCDebug(lcTlsBackendSchannel, "intermediateBuffer size: %d", intermediateBuffer.size());
1386#endif
1387
1388 if (missingData > plainSocket->bytesAvailable())
1389 return true;
1390
1391 missingData = 0;
1392 readToBuffer(intermediateBuffer, plainSocket);
1393 if (intermediateBuffer.isEmpty())
1394 return true; // no data, will fail
1395
1396 SecBuffer outBuffers[3] = {};
1397 const auto freeOutBuffers = [&outBuffers]() {
1398 for (auto i = 0ull; i < ARRAYSIZE(outBuffers); i++) {
1399 if (outBuffers[i].pvBuffer)
1400 FreeContextBuffer(outBuffers[i].pvBuffer);
1401 }
1402 };
1403 const auto outBuffersGuard = qScopeGuard(freeOutBuffers);
1404 // For this call to InitializeSecurityContext we may need to call it twice.
1405 // In some cases us not having a certificate isn't actually an error, but just a request.
1406 // With Schannel, to ignore this warning, we need to call InitializeSecurityContext again
1407 // when we get SEC_I_INCOMPLETE_CREDENTIALS! As far as I can tell it's not documented anywhere.
1408 // https://stackoverflow.com/a/47479968/2493610
1409 SECURITY_STATUS status;
1410 short attempts = 2;
1411 do {
1412 SecBuffer inputBuffers[2];
1413 inputBuffers[0] = createSecBuffer(intermediateBuffer, SECBUFFER_TOKEN);
1414 inputBuffers[1] = createSecBuffer(nullptr, 0, SECBUFFER_EMPTY);
1415 SecBufferDesc inputBufferDesc{
1416 SECBUFFER_VERSION,
1417 ARRAYSIZE(inputBuffers),
1418 inputBuffers
1419 };
1420
1421 freeOutBuffers(); // free buffers from any previous attempt
1422 outBuffers[0] = createSecBuffer(nullptr, 0, SECBUFFER_TOKEN);
1423 outBuffers[1] = createSecBuffer(nullptr, 0, SECBUFFER_ALERT);
1424 outBuffers[2] = createSecBuffer(nullptr, 0, SECBUFFER_EMPTY);
1425 SecBufferDesc outputBufferDesc{
1426 SECBUFFER_VERSION,
1427 ARRAYSIZE(outBuffers),
1428 outBuffers
1429 };
1430
1431 ULONG contextReq = getContextRequirements();
1432 TimeStamp expiry;
1433 status = InitializeSecurityContext(
1434 &credentialHandle, // phCredential
1435 &contextHandle, // phContext
1436 const_reinterpret_cast<SEC_WCHAR *>(targetName().utf16()), // pszTargetName
1437 contextReq, // fContextReq
1438 0, // Reserved1
1439 0, // TargetDataRep (unused)
1440 &inputBufferDesc, // pInput
1441 0, // Reserved2
1442 nullptr, // phNewContext (we already have one)
1443 &outputBufferDesc, // pOutput
1444 &contextAttributes, // pfContextAttr
1445 &expiry // ptsExpiry
1446 );
1447
1448 if (inputBuffers[1].BufferType == SECBUFFER_EXTRA) {
1449 // https://docs.microsoft.com/en-us/windows/desktop/secauthn/extra-buffers-returned-by-schannel
1450 // inputBuffers[1].cbBuffer indicates the amount of bytes _NOT_ processed, the rest need
1451 // to be stored.
1452 retainExtraData(intermediateBuffer, inputBuffers[1]);
1453 } else if (status != SEC_E_INCOMPLETE_MESSAGE) {
1454 // Clear the buffer if we weren't asked for more data
1455 intermediateBuffer.resize(0);
1456 }
1457
1458 --attempts;
1459 } while (status == SEC_I_INCOMPLETE_CREDENTIALS && attempts > 0);
1460
1461 switch (status) {
1462 case SEC_E_OK:
1463 // Need to transmit a final token in the handshake if 'cbBuffer' is non-zero.
1464 if (!sendToken(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer))
1465 return false;
1466 schannelState = SchannelState::VerifyHandshake;
1467 return true;
1468 case SEC_I_CONTINUE_NEEDED:
1469 if (!sendToken(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer))
1470 return false;
1471 // Must call InitializeSecurityContext again later (done through continueHandshake)
1472 return true;
1473 case SEC_I_INCOMPLETE_CREDENTIALS:
1474 // Schannel takes care of picking certificate to send (other than the one we can specify),
1475 // so if we get here then that means we don't have a certificate the server accepts.
1476 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
1477 QSslSocket::tr("Server did not accept any certificate we could present."));
1478 return false;
1479 case SEC_I_CONTEXT_EXPIRED:
1480 // "The message sender has finished using the connection and has initiated a shutdown."
1481 if (outBuffers[0].BufferType == SECBUFFER_TOKEN) {
1482 if (!sendToken(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer))
1483 return false;
1484 }
1485 if (!shutdown) { // we did not initiate this
1486 setErrorAndEmit(d, QAbstractSocket::RemoteHostClosedError,
1487 QSslSocket::tr("The TLS/SSL connection has been closed"));
1488 }
1489 return true;
1490 case SEC_E_INCOMPLETE_MESSAGE:
1491 // Simply incomplete, wait for more data
1492 missingData = checkIncompleteData(outBuffers[0]);
1493 return true;
1494 case SEC_E_ALGORITHM_MISMATCH:
1495 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
1496 QSslSocket::tr("Algorithm mismatch"));
1497 shutdown = true; // skip sending the "Shutdown" alert
1498 return false;
1499 }
1500
1501 // Note: We can get here if the connection is using TLS 1.2 and the server certificate uses
1502 // MD5, which is not allowed in Schannel. This causes an "invalid token" error during handshake.
1503 // (If you came here investigating an error: md5 is insecure, update your certificate)
1504 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
1505 QSslSocket::tr("Handshake failed: %1").arg(schannelErrorToString(status)));
1506 return false;
1507}
1508
1509bool TlsCryptographSchannel::verifyHandshake()
1510{
1511 Q_ASSERT(d);
1512 Q_ASSERT(q);
1513 const auto &configuration = q->sslConfiguration();
1514
1515 sslErrors.clear();
1516
1517 const bool isClient = d->tlsMode() == QSslSocket::SslClientMode;
1518#define CHECK_STATUS(status)
1519 if (status != SEC_E_OK) {
1520 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1521 QSslSocket::tr("Failed to query the TLS context: %1")
1522 .arg(schannelErrorToString(status)));
1523 return false;
1524 }
1525
1526 // Everything is set up, now make sure there's nothing wrong and query some attributes...
1527 if (!matchesContextRequirements(contextAttributes, getContextRequirements(),
1528 configuration.peerVerifyMode(), isClient)) {
1529 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
1530 QSslSocket::tr("Did not get the required attributes for the connection."));
1531 return false;
1532 }
1533
1534 // Get stream sizes (to know the max size of a message and the size of the header and trailer)
1535 auto status = QueryContextAttributes(&contextHandle,
1536 SECPKG_ATTR_STREAM_SIZES,
1537 &streamSizes);
1538 CHECK_STATUS(status);
1539
1540 // Get session cipher info
1541 status = QueryContextAttributes(&contextHandle,
1542 SECPKG_ATTR_CIPHER_INFO,
1543 &cipherInfo);
1544 CHECK_STATUS(status);
1545
1546 status = QueryContextAttributes(&contextHandle,
1547 SECPKG_ATTR_CONNECTION_INFO,
1548 &connectionInfo);
1549 CHECK_STATUS(status);
1550
1551#ifdef SUPPORTS_ALPN
1552 const auto allowedProtos = configuration.allowedNextProtocols();
1553 if (!allowedProtos.isEmpty()) {
1554 SecPkgContext_ApplicationProtocol alpn;
1555 status = QueryContextAttributes(&contextHandle,
1556 SECPKG_ATTR_APPLICATION_PROTOCOL,
1557 &alpn);
1558 CHECK_STATUS(status);
1559 if (alpn.ProtoNegoStatus == SecApplicationProtocolNegotiationStatus_Success) {
1560 QByteArray negotiatedProto = QByteArray((const char *)alpn.ProtocolId,
1561 alpn.ProtocolIdSize);
1562 if (!allowedProtos.contains(negotiatedProto)) {
1563 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
1564 QSslSocket::tr("Unwanted protocol was negotiated"));
1565 return false;
1566 }
1567 QTlsBackend::setNegotiatedProtocol(d, negotiatedProto);
1568 QTlsBackend::setAlpnStatus(d, QSslConfiguration::NextProtocolNegotiationNegotiated);
1569 } else {
1570 QTlsBackend::setNegotiatedProtocol(d, {});
1571 QTlsBackend::setAlpnStatus(d, QSslConfiguration::NextProtocolNegotiationUnsupported);
1572 }
1573 }
1574#endif // supports ALPN
1575
1576#undef CHECK_STATUS
1577
1578 // Verify certificate
1579 CERT_CONTEXT *certificateContext = nullptr;
1580 auto freeCertificate = qScopeGuard([&certificateContext]() {
1581 if (certificateContext)
1582 CertFreeCertificateContext(certificateContext);
1583 });
1584 status = QueryContextAttributes(&contextHandle,
1585 SECPKG_ATTR_REMOTE_CERT_CONTEXT,
1586 &certificateContext);
1587
1588 // QueryPeer can (currently) not work in Schannel since Schannel itself doesn't have a way to
1589 // ask for a certificate and then still be OK if it's not received.
1590 // To work around this we don't request a certificate at all for QueryPeer.
1591 // For servers AutoVerifyPeer is supposed to be treated the same as QueryPeer.
1592 // This means that servers using Schannel will only request client certificate for "VerifyPeer".
1593 if ((!isClient && configuration.peerVerifyMode() == QSslSocket::PeerVerifyMode::VerifyPeer)
1594 || (isClient && configuration.peerVerifyMode() != QSslSocket::PeerVerifyMode::VerifyNone
1595 && configuration.peerVerifyMode() != QSslSocket::PeerVerifyMode::QueryPeer)) {
1596 if (status != SEC_E_OK) {
1597#ifdef QSSLSOCKET_DEBUG
1598 qCDebug(lcTlsBackendSchannel) << "Couldn't retrieve peer certificate, status:"
1599 << schannelErrorToString(status);
1600#endif
1601 const QSslError error{ QSslError::NoPeerCertificate };
1602 sslErrors += error;
1603 emit q->peerVerifyError(error);
1604 if (q->state() != QAbstractSocket::ConnectedState)
1605 return false;
1606 }
1607 }
1608
1609 // verifyCertContext returns false if the user disconnected while it was checking errors.
1610 if (certificateContext && !verifyCertContext(certificateContext))
1611 return false;
1612
1613 if (!checkSslErrors() || q->state() != QAbstractSocket::ConnectedState) {
1614#ifdef QSSLSOCKET_DEBUG
1615 qCDebug(lcTlsBackendSchannel) << __func__ << "was unsuccessful. Paused:" << d->isPaused();
1616#endif
1617 // If we're paused then checkSslErrors returned false, but it's not an error
1618 return d->isPaused() && q->state() == QAbstractSocket::ConnectedState;
1619 }
1620
1621 schannelState = SchannelState::Done;
1622 return true;
1623}
1624
1625bool TlsCryptographSchannel::renegotiate()
1626{
1627 Q_ASSERT(d);
1628
1629 SecBuffer outBuffers[3];
1630 outBuffers[0] = createSecBuffer(nullptr, 0, SECBUFFER_TOKEN);
1631 outBuffers[1] = createSecBuffer(nullptr, 0, SECBUFFER_ALERT);
1632 outBuffers[2] = createSecBuffer(nullptr, 0, SECBUFFER_EMPTY);
1633 auto freeBuffers = qScopeGuard([&outBuffers]() {
1634 for (auto i = 0ull; i < ARRAYSIZE(outBuffers); i++) {
1635 if (outBuffers[i].pvBuffer)
1636 FreeContextBuffer(outBuffers[i].pvBuffer);
1637 }
1638 });
1639 SecBufferDesc outputBufferDesc{
1640 SECBUFFER_VERSION,
1641 ARRAYSIZE(outBuffers),
1642 outBuffers
1643 };
1644
1645 ULONG contextReq = getContextRequirements();
1646 TimeStamp expiry;
1647 SECURITY_STATUS status;
1648 if (d->tlsMode() == QSslSocket::SslClientMode) {
1649 status = InitializeSecurityContext(&credentialHandle, // phCredential
1650 &contextHandle, // phContext
1651 const_reinterpret_cast<SEC_WCHAR *>(targetName().utf16()), // pszTargetName
1652 contextReq, // fContextReq
1653 0, // Reserved1
1654 0, // TargetDataRep (unused)
1655 nullptr, // pInput (nullptr for renegotiate)
1656 0, // Reserved2
1657 nullptr, // phNewContext (we already have one)
1658 &outputBufferDesc, // pOutput
1659 &contextAttributes, // pfContextAttr
1660 &expiry // ptsExpiry
1661 );
1662 } else {
1663 status = AcceptSecurityContext(
1664 &credentialHandle, // phCredential
1665 &contextHandle, // phContext
1666 nullptr, // pInput
1667 contextReq, // fContextReq
1668 0, // TargetDataRep (unused)
1669 nullptr, // phNewContext
1670 &outputBufferDesc, // pOutput
1671 &contextAttributes, // pfContextAttr,
1672 &expiry // ptsTimeStamp
1673 );
1674 }
1675 if (status == SEC_I_CONTINUE_NEEDED) {
1676 schannelState = SchannelState::PerformHandshake;
1677 return sendToken(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer);
1678 } else if (status == SEC_E_OK) {
1679 schannelState = SchannelState::PerformHandshake;
1680 return true;
1681 }
1682 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
1683 QSslSocket::tr("Renegotiation was unsuccessful: %1").arg(schannelErrorToString(status)));
1684 return false;
1685}
1686
1687/*!
1688 \internal
1689 reset the state in preparation for reuse of socket
1690*/
1691void TlsCryptographSchannel::reset()
1692{
1693 Q_ASSERT(d);
1694
1695 closeCertificateStores(); // certificate stores could've changed
1696 deallocateContext();
1697 freeCredentialsHandle(); // in case we already had one (@future: session resumption requires re-use)
1698
1699 cipherInfo = {};
1700 connectionInfo = {};
1701 streamSizes = {};
1702
1703 contextAttributes = 0;
1704 intermediateBuffer.clear();
1705 schannelState = SchannelState::InitializeHandshake;
1706
1707
1708 d->setEncrypted(false);
1709 shutdown = false;
1710 renegotiating = false;
1711
1712 missingData = 0;
1713}
1714
1716{
1717 Q_ASSERT(q);
1718
1719 if (q->isEncrypted())
1720 return; // let's not mess up the connection...
1721 reset();
1723}
1724
1726{
1727 Q_ASSERT(q);
1728
1729 if (q->isEncrypted())
1730 return; // let's not mess up the connection...
1731 reset();
1733}
1734
1735auto TlsCryptographSchannel::getNextEncryptedMessage() -> MessageBufferResult
1736{
1737 MessageBufferResult result;
1738 QByteArray &fullMessage = result.messageBuffer;
1739
1740 Q_ASSERT(d);
1741 auto &writeBuffer = d->tlsWriteBuffer();
1742
1743 auto allocateMessage = [&fullMessage](qsizetype size) -> QSpan<char> {
1744 auto targetSize = fullMessage.size() + size;
1745 if (fullMessage.capacity() < targetSize) {
1746 qsizetype newSize = fullMessage.capacity() * 2;
1747 if (newSize < targetSize)
1748 newSize = targetSize;
1749 fullMessage.reserve(newSize);
1750 }
1751 fullMessage.resizeForOverwrite(targetSize);
1752 return QSpan(fullMessage).subspan(fullMessage.size() - size);
1753 };
1754
1755 const int headerSize = int(streamSizes.cbHeader);
1756 const int trailerSize = int(streamSizes.cbTrailer);
1757 constexpr qsizetype MessageBufferThreshold = 128 * 1024;
1758
1759 qint64 writeBufferSize = 0;
1760 while ((writeBufferSize = writeBuffer.size()) > 0
1761 && fullMessage.size() < MessageBufferThreshold) {
1762 // Try to read 'cbMaximumMessage' bytes from buffer before encrypting.
1763 const int bodySize = int(std::min(writeBufferSize, qint64(streamSizes.cbMaximumMessage)));
1764 const qsizetype messageSize = headerSize + bodySize + trailerSize;
1765 QSpan buffer = allocateMessage(messageSize);
1766 char *header = buffer.data();
1767 char *body = header + headerSize;
1768 char *trailer = body + bodySize;
1769 {
1770 // Use peek() here instead of read() so we don't lose data if encryption fails.
1771 qint64 copied = writeBuffer.peek(body, bodySize);
1772 Q_ASSERT(copied == bodySize);
1773 }
1774
1775 SecBuffer inputBuffers[] = {
1776 createSecBuffer(header, headerSize, SECBUFFER_STREAM_HEADER),
1777 createSecBuffer(body, bodySize, SECBUFFER_DATA),
1778 createSecBuffer(trailer, trailerSize, SECBUFFER_STREAM_TRAILER),
1779 createSecBuffer(nullptr, 0, SECBUFFER_EMPTY)
1780 };
1781 SecBufferDesc message = {
1782 SECBUFFER_VERSION,
1783 ARRAYSIZE(inputBuffers),
1784 inputBuffers
1785 };
1786
1787 if (auto status = EncryptMessage(&contextHandle, 0, &message, 0); status != SEC_E_OK) {
1788 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1789 QSslSocket::tr("Schannel failed to encrypt data: %1")
1790 .arg(schannelErrorToString(status)));
1791 result.messageBuffer.chop(messageSize);
1792 return result;
1793 }
1794 // Data was encrypted successfully, so we free() what we peek()ed earlier
1795 writeBuffer.free(bodySize);
1796
1797 // The trailer's size is not final, so resize fullMessage to not send trailing junk
1798 auto finalSize = qsizetype(inputBuffers[0].cbBuffer + inputBuffers[1].cbBuffer
1799 + inputBuffers[2].cbBuffer);
1800 fullMessage.chop(messageSize - finalSize);
1801 }
1802 result.ok = true;
1803 return result;
1804}
1805
1807{
1808 Q_ASSERT(q);
1809 Q_ASSERT(d);
1810 auto *plainSocket = d->plainTcpSocket();
1811 Q_ASSERT(plainSocket);
1812
1813 if (d->tlsMode() == QSslSocket::UnencryptedMode)
1814 return; // This function should not have been called
1815
1816 // Can happen if called through QSslSocket::abort->QSslSocket::close->QSslSocket::flush->here
1817 if (plainSocket->state() == QAbstractSocket::UnconnectedState || !plainSocket->isValid()
1818 || !plainSocket->isOpen()) {
1819 return;
1820 }
1821
1822 if (schannelState != SchannelState::Done) {
1824 return;
1825 }
1826
1827 auto &buffer = d->tlsBuffer();
1828 if (q->isEncrypted()) { // encrypt data in writeBuffer and write it to plainSocket
1829 qint64 totalBytesWritten = 0;
1830 while (d->tlsWriteBuffer().size() > 0) {
1831 MessageBufferResult r = getNextEncryptedMessage();
1832 if (r.messageBuffer.isEmpty() && !r.ok)
1833 return;
1834 QByteArray fullMessage = std::move(r.messageBuffer);
1835 const qint64 bytesWritten = plainSocket->write(fullMessage);
1836 if (!r.ok && bytesWritten < 0)
1837 break; // We might have to emit bytesWritten, so break instead of return
1838#ifdef QSSLSOCKET_DEBUG
1839 qCDebug(lcTlsBackendSchannel, "Wrote %lld of total %d bytes", bytesWritten,
1840 fullMessage.size());
1841#endif
1842 if (bytesWritten >= 0) {
1843 totalBytesWritten += bytesWritten;
1844 } else {
1845 setErrorAndEmit(d, plainSocket->error(), plainSocket->errorString());
1846 return;
1847 }
1848 }
1849
1850 if (totalBytesWritten > 0) {
1851 // Don't emit bytesWritten() recursively.
1852 bool &emittedBytesWritten = d->tlsEmittedBytesWritten();
1853 if (!emittedBytesWritten) {
1854 emittedBytesWritten = true;
1855 emit q->bytesWritten(totalBytesWritten);
1856 emittedBytesWritten = false;
1857 }
1858 emit q->channelBytesWritten(0, totalBytesWritten);
1859 }
1860 }
1861
1862 int totalRead = 0;
1863 bool hadIncompleteData = false;
1864 const auto readBufferMaxSize = d->maxReadBufferSize();
1865 while (!readBufferMaxSize || buffer.size() < readBufferMaxSize) {
1866 if (missingData > plainSocket->bytesAvailable()
1867 && (!readBufferMaxSize || readBufferMaxSize >= missingData)) {
1868#ifdef QSSLSOCKET_DEBUG
1869 qCDebug(lcTlsBackendSchannel, "We're still missing %lld bytes, will check later.",
1870 missingData);
1871#endif
1872 break;
1873 }
1874
1875 missingData = 0;
1876 const qint64 bytesRead = readToBuffer(intermediateBuffer, plainSocket);
1877#ifdef QSSLSOCKET_DEBUG
1878 qCDebug(lcTlsBackendSchannel, "Read %lld encrypted bytes from the socket", bytesRead);
1879#endif
1880 if (intermediateBuffer.length() == 0 || (hadIncompleteData && bytesRead == 0)) {
1881#ifdef QSSLSOCKET_DEBUG
1882 qCDebug(lcTlsBackendSchannel,
1883 hadIncompleteData ? "No new data received, leaving loop!"
1884 : "Nothing to decrypt, leaving loop!");
1885#endif
1886 break;
1887 }
1888 hadIncompleteData = false;
1889#ifdef QSSLSOCKET_DEBUG
1890 qCDebug(lcTlsBackendSchannel, "Total amount of bytes to decrypt: %d",
1891 intermediateBuffer.length());
1892#endif
1893
1894 SecBuffer dataBuffer[4]{
1895 createSecBuffer(intermediateBuffer, SECBUFFER_DATA),
1896 createSecBuffer(nullptr, 0, SECBUFFER_EMPTY),
1897 createSecBuffer(nullptr, 0, SECBUFFER_EMPTY),
1898 createSecBuffer(nullptr, 0, SECBUFFER_EMPTY)
1899 };
1900 SecBufferDesc message{
1901 SECBUFFER_VERSION,
1902 ARRAYSIZE(dataBuffer),
1903 dataBuffer
1904 };
1905 auto status = DecryptMessage(&contextHandle, &message, 0, nullptr);
1906 if (status == SEC_E_OK || status == SEC_I_RENEGOTIATE || status == SEC_I_CONTEXT_EXPIRED) {
1907 // There can still be 0 output even if it succeeds, this is fine
1908 if (dataBuffer[1].cbBuffer > 0) {
1909 // It is always decrypted in-place.
1910 // But [0] is the STREAM_HEADER, [1] is the DATA and [2] is the STREAM_TRAILER.
1911 // The pointers in all of those still point into 'intermediateBuffer'.
1912 buffer.append(static_cast<char *>(dataBuffer[1].pvBuffer),
1913 dataBuffer[1].cbBuffer);
1914 totalRead += dataBuffer[1].cbBuffer;
1915#ifdef QSSLSOCKET_DEBUG
1916 qCDebug(lcTlsBackendSchannel, "Decrypted %lu bytes. New read buffer size: %d",
1917 dataBuffer[1].cbBuffer, buffer.size());
1918#endif
1919 }
1920 if (dataBuffer[3].BufferType == SECBUFFER_EXTRA) {
1921 // https://docs.microsoft.com/en-us/windows/desktop/secauthn/extra-buffers-returned-by-schannel
1922 // dataBuffer[3].cbBuffer indicates the amount of bytes _NOT_ processed,
1923 // the rest need to be stored.
1924 retainExtraData(intermediateBuffer, dataBuffer[3]);
1925 } else {
1926 intermediateBuffer.resize(0);
1927 }
1928 }
1929
1930 if (status == SEC_E_INCOMPLETE_MESSAGE) {
1931 missingData = checkIncompleteData(dataBuffer[0]);
1932#ifdef QSSLSOCKET_DEBUG
1933 qCDebug(lcTlsBackendSchannel, "We didn't have enough data to decrypt anything, will try again!");
1934#endif
1935 // We try again, but if we don't get any more data then we leave
1936 hadIncompleteData = true;
1937 } else if (status == SEC_E_INVALID_HANDLE) {
1938 // I don't think this should happen, if it does we're done...
1939 qCWarning(lcTlsBackendSchannel, "The internal SSPI handle is invalid!");
1940 Q_UNREACHABLE();
1941 } else if (status == SEC_E_INVALID_TOKEN) {
1942 // Supposedly we have an invalid token, it's under-documented what
1943 // this means, so to be safe we disconnect.
1944 shutdown = true;
1946 setErrorAndEmit(d, QAbstractSocket::SslInternalError, schannelErrorToString(status));
1947 break;
1948 } else if (status == SEC_E_MESSAGE_ALTERED) {
1949 // The message has been altered, disconnect now.
1950 shutdown = true; // skips sending the shutdown alert
1952 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1953 schannelErrorToString(status));
1954 break;
1955 } else if (status == SEC_E_OUT_OF_SEQUENCE) {
1956 // @todo: I don't know if this one is actually "fatal"..
1957 // This path might never be hit as it seems this is for connection-oriented connections,
1958 // while SEC_E_MESSAGE_ALTERED is for stream-oriented ones (what we use).
1959 shutdown = true; // skips sending the shutdown alert
1961 setErrorAndEmit(d, QAbstractSocket::SslInternalError,
1962 schannelErrorToString(status));
1963 break;
1964 } else if (status == SEC_E_DECRYPT_FAILURE) {
1965 // It's not documented as a possible return value for DecryptMessage,
1966 // but we see that this may happen - supposed to be a bug in Schannel (with TLS 1.3?)
1967 shutdown = true; // skips sending the shutdown alert
1969 setErrorAndEmit(d, QAbstractSocket::SslInternalError, schannelErrorToString(status));
1970 break;
1971 } else if (status == SEC_I_CONTEXT_EXPIRED) {
1972 // 'remote' has initiated a shutdown
1974 break;
1975 } else if (status == SEC_I_RENEGOTIATE) {
1976 // 'remote' wants to renegotiate
1977#ifdef QSSLSOCKET_DEBUG
1978 qCDebug(lcTlsBackendSchannel, "The peer wants to renegotiate.");
1979#endif
1980 schannelState = SchannelState::Renegotiate;
1981 renegotiating = true;
1982
1983 // We need to call 'continueHandshake' or else there's no guarantee it ever gets called
1985 break;
1986 }
1987 }
1988
1989 if (totalRead) {
1990 if (bool *readyReadEmittedPointer = d->readyReadPointer())
1991 *readyReadEmittedPointer = true;
1992 emit q->readyRead();
1993 emit q->channelReadyRead(0);
1994 }
1995}
1996
1997void TlsCryptographSchannel::sendShutdown()
1998{
1999 Q_ASSERT(d);
2000
2001 const bool isClient = d->tlsMode() == QSslSocket::SslClientMode;
2002 DWORD shutdownToken = SCHANNEL_SHUTDOWN;
2003 SecBuffer buffer = createSecBuffer(&shutdownToken, sizeof(DWORD), SECBUFFER_TOKEN);
2004 SecBufferDesc token{
2005 SECBUFFER_VERSION,
2006 1,
2007 &buffer
2008 };
2009 auto status = ApplyControlToken(&contextHandle, &token);
2010
2011 if (status != SEC_E_OK) {
2012#ifdef QSSLSOCKET_DEBUG
2013 qCDebug(lcTlsBackendSchannel)
2014 << "Failed to apply shutdown control token:" << schannelErrorToString(status);
2015#endif
2016 return;
2017 }
2018
2019 SecBuffer outBuffers[3];
2020 outBuffers[0] = createSecBuffer(nullptr, 0, SECBUFFER_TOKEN);
2021 outBuffers[1] = createSecBuffer(nullptr, 0, SECBUFFER_ALERT);
2022 outBuffers[2] = createSecBuffer(nullptr, 0, SECBUFFER_EMPTY);
2023 auto freeBuffers = qScopeGuard([&outBuffers]() {
2024 for (auto i = 0ull; i < ARRAYSIZE(outBuffers); i++) {
2025 if (outBuffers[i].pvBuffer)
2026 FreeContextBuffer(outBuffers[i].pvBuffer);
2027 }
2028 });
2029 SecBufferDesc outputBufferDesc{
2030 SECBUFFER_VERSION,
2031 ARRAYSIZE(outBuffers),
2032 outBuffers
2033 };
2034
2035 ULONG contextReq = getContextRequirements();
2036 TimeStamp expiry;
2037 if (isClient) {
2038 status = InitializeSecurityContext(&credentialHandle, // phCredential
2039 &contextHandle, // phContext
2040 const_reinterpret_cast<SEC_WCHAR *>(targetName().utf16()), // pszTargetName
2041 contextReq, // fContextReq
2042 0, // Reserved1
2043 0, // TargetDataRep (unused)
2044 nullptr, // pInput
2045 0, // Reserved2
2046 nullptr, // phNewContext (we already have one)
2047 &outputBufferDesc, // pOutput
2048 &contextAttributes, // pfContextAttr
2049 &expiry // ptsExpiry
2050 );
2051 } else {
2052 status = AcceptSecurityContext(
2053 &credentialHandle, // phCredential
2054 &contextHandle, // phContext
2055 nullptr, // pInput
2056 contextReq, // fContextReq
2057 0, // TargetDataRep (unused)
2058 nullptr, // phNewContext
2059 &outputBufferDesc, // pOutput
2060 &contextAttributes, // pfContextAttr,
2061 &expiry // ptsTimeStamp
2062 );
2063 }
2064 if (status == SEC_E_OK || status == SEC_I_CONTEXT_EXPIRED) {
2065 if (!sendToken(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer, false)) {
2066 // We failed to send the shutdown message, but it's not that important since we're
2067 // shutting down anyway.
2068 return;
2069 }
2070 } else {
2071#ifdef QSSLSOCKET_DEBUG
2072 qCDebug(lcTlsBackendSchannel)
2073 << "Failed to initialize shutdown:" << schannelErrorToString(status);
2074#endif
2075 }
2076}
2077
2079{
2080 Q_ASSERT(q);
2081 Q_ASSERT(d);
2082 auto *plainSocket = d->plainTcpSocket();
2083 Q_ASSERT(plainSocket);
2084
2085 if (SecIsValidHandle(&contextHandle)) {
2086 if (!shutdown) {
2087 shutdown = true;
2088 if (plainSocket->state() != QAbstractSocket::UnconnectedState && q->isEncrypted()) {
2089 sendShutdown();
2090 transmit();
2091 }
2092 }
2093 }
2094 plainSocket->disconnectFromHost();
2095}
2096
2098{
2099 Q_ASSERT(d);
2100 auto *plainSocket = d->plainTcpSocket();
2101 Q_ASSERT(plainSocket);
2102 d->setEncrypted(false);
2103
2104 shutdown = true;
2105 if (plainSocket->bytesAvailable() > 0 || hasUndecryptedData()) {
2106 // Read as much as possible because this is likely our last chance
2107 qint64 tempMax = d->maxReadBufferSize();
2108 d->setMaxReadBufferSize(0); // Unlimited
2109 transmit();
2110 d->setMaxReadBufferSize(tempMax);
2111 // Since there were bytes still available we don't want to deallocate
2112 // our context yet. It will happen later, when the socket is re-used or
2113 // destroyed.
2114 } else {
2115 deallocateContext();
2116 freeCredentialsHandle();
2117 }
2118}
2119
2121{
2122 Q_ASSERT(q);
2123
2124 if (!q->isEncrypted())
2125 return {};
2126
2127 const auto sessionProtocol = toQtSslProtocol(connectionInfo.dwProtocol);
2128
2129 const auto ciphers = ciphersByName(QStringView(cipherInfo.szCipherSuite));
2130 for (const auto& cipher : ciphers) {
2131 if (cipher.protocol() == sessionProtocol)
2132 return cipher;
2133 }
2134
2135 return {};
2136}
2137
2139{
2140 if (!q->isEncrypted())
2141 return QSsl::SslProtocol::UnknownProtocol;
2142 return toQtSslProtocol(connectionInfo.dwProtocol);
2143}
2144
2146{
2147 Q_ASSERT(q);
2148 Q_ASSERT(d);
2149 auto *plainSocket = d->plainTcpSocket();
2150 Q_ASSERT(plainSocket);
2151
2152 const bool isServer = d->tlsMode() == QSslSocket::SslServerMode;
2153 switch (schannelState) {
2154 case SchannelState::InitializeHandshake:
2155 if (!SecIsValidHandle(&credentialHandle) && !acquireCredentialsHandle()) {
2157 return;
2158 }
2159 if (!SecIsValidHandle(&credentialHandle)) // Needed to support tst_QSslSocket::setEmptyKey
2160 return;
2161 if (!SecIsValidHandle(&contextHandle) && !(isServer ? acceptContext() : createContext())) {
2163 return;
2164 }
2165 if (schannelState != SchannelState::PerformHandshake)
2166 break;
2167 Q_FALLTHROUGH();
2168 case SchannelState::PerformHandshake:
2169 if (!performHandshake()) {
2171 return;
2172 }
2173 if (schannelState != SchannelState::VerifyHandshake)
2174 break;
2175 Q_FALLTHROUGH();
2176 case SchannelState::VerifyHandshake:
2177 // if we're in shutdown or renegotiating then we might not need to verify
2178 // (since we already did)
2179 if (!verifyHandshake()) {
2180 shutdown = true; // Skip sending shutdown alert
2181 q->abort(); // We don't want to send buffered data
2183 return;
2184 }
2185 if (schannelState != SchannelState::Done)
2186 break;
2187 Q_FALLTHROUGH();
2188 case SchannelState::Done:
2189 // connectionEncrypted is already true if we come here from a renegotiation
2190 if (!q->isEncrypted()) {
2191 d->setEncrypted(true); // all is done
2192 emit q->encrypted();
2193 }
2194 renegotiating = false;
2195 if (d->isPendingClose()) {
2196 d->setPendingClose(false);
2198 } else {
2199 transmit();
2200 }
2201 break;
2202 case SchannelState::Renegotiate:
2203 if (!renegotiate()) {
2205 return;
2206 } else if (intermediateBuffer.size() || plainSocket->bytesAvailable()) {
2208 }
2209 break;
2210 }
2211}
2212
2214{
2215 return sslErrors;
2216}
2217
2218/*
2219 Copied from qsslsocket_mac.cpp, which was copied from qsslsocket_openssl.cpp
2220*/
2221bool TlsCryptographSchannel::checkSslErrors()
2222{
2223 if (sslErrors.isEmpty())
2224 return true;
2225
2226 Q_ASSERT(q);
2227 Q_ASSERT(d);
2228 const auto &configuration = q->sslConfiguration();
2229 auto *plainSocket = d->plainTcpSocket();
2230
2231 emit q->sslErrors(sslErrors);
2232
2233 const bool doVerifyPeer = configuration.peerVerifyMode() == QSslSocket::VerifyPeer
2234 || (configuration.peerVerifyMode() == QSslSocket::AutoVerifyPeer
2235 && d->tlsMode() == QSslSocket::SslClientMode);
2236 const bool doEmitSslError = !d->verifyErrorsHaveBeenIgnored();
2237 // check whether we need to emit an SSL handshake error
2238 if (doVerifyPeer && doEmitSslError) {
2239 if (q->pauseMode() & QAbstractSocket::PauseOnSslErrors) {
2240 QSslSocketPrivate::pauseSocketNotifiers(q);
2241 d->setPaused(true);
2242 } else {
2243 setErrorAndEmit(d, QAbstractSocket::SslHandshakeFailedError,
2244 sslErrors.constFirst().errorString());
2245 plainSocket->disconnectFromHost();
2246 }
2247 return false;
2248 }
2249
2250 return true;
2251}
2252
2253static void attachPrivateKeyToCertificate(const QSslCertificate &certificate,
2254 const QSslKey &privateKey)
2255{
2256 QAsn1Element elem = _q_PKCS12_key(privateKey);
2257 QByteArray buffer;
2258 QDataStream stream(&buffer, QDataStream::WriteOnly);
2259 elem.write(stream);
2260 NCRYPT_PROV_HANDLE provider = 0;
2261 SECURITY_STATUS status = NCryptOpenStorageProvider(&provider, MS_KEY_STORAGE_PROVIDER, 0);
2262 if (status != SEC_E_OK) {
2263 qCWarning(lcTlsBackendSchannel())
2264 << "Failed to open ncrypt storage provider:" << schannelErrorToString(status);
2265 return;
2266 }
2267 const auto freeProvider = qScopeGuard([provider]() { NCryptFreeObject(provider); });
2268
2269 const QString certName = certificate.subjectInfo(QSslCertificate::CommonName).front();
2270 QSpan<const QChar> nameSpan(certName);
2271 NCryptBuffer nbuffer{ ULONG(nameSpan.size_bytes() + sizeof(char16_t)),
2272 NCRYPTBUFFER_PKCS_KEY_NAME,
2273 const_reinterpret_cast<void *>(nameSpan.data()) };
2274 NCryptBufferDesc bufferDesc{ NCRYPTBUFFER_VERSION, 1, &nbuffer };
2275 NCRYPT_KEY_HANDLE ncryptKey = 0;
2276 status = NCryptImportKey(provider, 0, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, &bufferDesc, &ncryptKey,
2277 PBYTE(buffer.data()), buffer.size(), 0);
2278 if (status != SEC_E_OK) {
2279 qCWarning(lcTlsBackendSchannel())
2280 << "Failed to import private key:" << schannelErrorToString(status);
2281 return;
2282 }
2283 const auto freeKey = qScopeGuard([ncryptKey]() { NCryptFreeObject(ncryptKey); });
2284
2285 CERT_CONTEXT *context = PCERT_CONTEXT(certificate.handle());
2286 Q_ASSERT(context);
2287
2288 CRYPT_DATA_BLOB keyBlob = { sizeof(ncryptKey), PBYTE(&ncryptKey) };
2289 BOOL ok =
2290 CertSetCertificateContextProperty(context, CERT_NCRYPT_KEY_HANDLE_PROP_ID, 0, &keyBlob);
2291 if (!ok) {
2292 auto error = GetLastError();
2293 if (lcTlsBackendSchannel().isWarningEnabled())
2294 qErrnoWarning(int(error), "Failed to set ncrypt handle property.");
2295 return;
2296 }
2297
2298 CRYPT_KEY_PROV_INFO provInfo{
2299 const_reinterpret_cast<LPWSTR>(certName.constData()),
2300 const_cast<LPWSTR>(MS_KEY_STORAGE_PROVIDER),
2301 0,
2302 CERT_SET_KEY_PROV_HANDLE_PROP_ID | CERT_SET_KEY_CONTEXT_PROP_ID,
2303 0,
2304 nullptr,
2305 0,
2306 };
2307 ok = CertSetCertificateContextProperty(context, CERT_KEY_PROV_INFO_PROP_ID,
2308 CERT_SET_PROPERTY_INHIBIT_PERSIST_FLAG, &provInfo);
2309 if (!ok) {
2310 auto error = GetLastError();
2311 if (lcTlsBackendSchannel().isWarningEnabled())
2312 qErrnoWarning(int(error), "Failed to set key provider info property.");
2313 return;
2314 }
2315}
2316
2317void TlsCryptographSchannel::initializeCertificateStores()
2318{
2319 //// helper function which turns a chain into a certificate store
2320 Q_ASSERT(d);
2321 Q_ASSERT(q);
2322 const auto &configuration = q->sslConfiguration();
2323
2324 auto createStoreFromCertificateChain = [](const QList<QSslCertificate> certChain, const QSslKey &privateKey) {
2325 const wchar_t *passphrase = L"";
2326 // Need to embed the private key in the certificate
2327 QByteArray pkcs12 = _q_makePkcs12(certChain,
2328 privateKey,
2329 QString::fromWCharArray(passphrase, 0));
2330 CRYPT_DATA_BLOB pfxBlob;
2331 pfxBlob.cbData = DWORD(pkcs12.length());
2332 pfxBlob.pbData = reinterpret_cast<unsigned char *>(pkcs12.data());
2333 // ALWAYS_CNG to import using "Cryptography API: Next Generation (CNG)"
2334 // NO_PERSIST_KEY to request not persisting anything imported to disk
2335 constexpr DWORD flags = PKCS12_ALWAYS_CNG_KSP | PKCS12_NO_PERSIST_KEY;
2336 return QHCertStorePointer(PFXImportCertStore(&pfxBlob, passphrase, flags));
2337 };
2338
2339 if (!configuration.localCertificateChain().isEmpty()) {
2340 if (configuration.privateKey().isNull()) {
2341 setErrorAndEmit(d, QAbstractSocket::SslInvalidUserDataError,
2342 QSslSocket::tr("Cannot provide a certificate with no key"));
2343 return;
2344 }
2345 if (localCertificateStore == nullptr) {
2346 localCertificateStore =
2347 createStoreFromCertificateChain(configuration.localCertificateChain(), {});
2348 if (localCertificateStore) {
2349 const CERT_CONTEXT *certificateContext = CertFindCertificateInStore(
2350 localCertificateStore.get(), X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0,
2351 CERT_FIND_ANY, nullptr, nullptr);
2352 if (certificateContext) {
2353 auto *backend = QTlsBackend::backend<X509CertificateSchannel>(
2354 configuration.localCertificate());
2355 backend->certificateContext.reset(
2356 CertDuplicateCertificateContext(certificateContext));
2357
2358 DWORD keySpec = 0;
2359 BOOL mustFree = FALSE;
2360 NCRYPT_KEY_HANDLE testKey = 0;
2361 BOOL ok = CryptAcquireCertificatePrivateKey(
2362 certificateContext, CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG, nullptr,
2363 &testKey, &keySpec, &mustFree);
2364 if (mustFree)
2365 NCryptFreeObject(testKey);
2366 if (!ok) {
2367 attachPrivateKeyToCertificate(configuration.localCertificate(),
2368 configuration.privateKey());
2369 }
2370 }
2371 } else {
2372 qCWarning(lcTlsBackendSchannel, "Failed to load certificate chain!");
2373 }
2374 }
2375 }
2376
2377 if (!configuration.caCertificates().isEmpty() && !caCertificateStore) {
2378 caCertificateStore = createStoreFromCertificateChain(configuration.caCertificates(),
2379 {}); // No private key for the CA certs
2380 }
2381}
2382
2383bool TlsCryptographSchannel::verifyCertContext(CERT_CONTEXT *certContext)
2384{
2385 Q_ASSERT(certContext);
2386 Q_ASSERT(q);
2387 Q_ASSERT(d);
2388
2389 const bool isClient = d->tlsMode() == QSslSocket::SslClientMode;
2390
2391 // Create a collection of stores so we can pass in multiple stores as additional locations to
2392 // search for the certificate chain
2393 auto tempCertCollection = QHCertStorePointer(CertOpenStore(CERT_STORE_PROV_COLLECTION,
2394 X509_ASN_ENCODING,
2395 0,
2396 CERT_STORE_CREATE_NEW_FLAG,
2397 nullptr));
2398 if (!tempCertCollection) {
2399#ifdef QSSLSOCKET_DEBUG
2400 qCWarning(lcTlsBackendSchannel, "Failed to create certificate store collection!");
2401#endif
2402 return false;
2403 }
2404
2405 if (rootCertOnDemandLoadingAllowed()) {
2406 // @future(maybe): following the OpenSSL backend these certificates should be added into
2407 // the Ca list, not just included during verification.
2408 // That being said, it's not trivial to add the root certificates (if and only if they
2409 // came from the system root store). And I don't see this mentioned in our documentation.
2410 auto rootStore = QHCertStorePointer(
2411 CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0,
2412 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER, L"ROOT"));
2413
2414 if (!rootStore) {
2415#ifdef QSSLSOCKET_DEBUG
2416 qCWarning(lcTlsBackendSchannel, "Failed to open the system root CA certificate store!");
2417#endif
2418 return false;
2419 } else if (!CertAddStoreToCollection(tempCertCollection.get(), rootStore.get(), 0, 1)) {
2420#ifdef QSSLSOCKET_DEBUG
2421 qCWarning(lcTlsBackendSchannel,
2422 "Failed to add the system root CA certificate store to the certificate store "
2423 "collection!");
2424#endif
2425 return false;
2426 }
2427 }
2428 if (caCertificateStore) {
2429 if (!CertAddStoreToCollection(tempCertCollection.get(), caCertificateStore.get(), 0, 1)) {
2430#ifdef QSSLSOCKET_DEBUG
2431 qCWarning(lcTlsBackendSchannel,
2432 "Failed to add the user's CA certificate store to the certificate store "
2433 "collection!");
2434#endif
2435 return false;
2436 }
2437 }
2438
2439 if (!CertAddStoreToCollection(tempCertCollection.get(), certContext->hCertStore, 0, 0)) {
2440#ifdef QSSLSOCKET_DEBUG
2441 qCWarning(lcTlsBackendSchannel,
2442 "Failed to add certificate's origin store to the certificate store collection!");
2443#endif
2444 return false;
2445 }
2446
2447 CERT_CHAIN_PARA parameters;
2448 ZeroMemory(&parameters, sizeof(parameters));
2449 parameters.cbSize = sizeof(CERT_CHAIN_PARA);
2450 parameters.RequestedUsage.dwType = USAGE_MATCH_TYPE_AND;
2451 parameters.RequestedUsage.Usage.cUsageIdentifier = 1;
2452 LPSTR oid = LPSTR(isClient ? szOID_PKIX_KP_SERVER_AUTH
2453 : szOID_PKIX_KP_CLIENT_AUTH);
2454 parameters.RequestedUsage.Usage.rgpszUsageIdentifier = &oid;
2455
2456 QTlsBackend::clearPeerCertificates(d);
2457 const CERT_CHAIN_CONTEXT *chainContext = nullptr;
2458 auto freeCertChain = qScopeGuard([&chainContext]() {
2459 if (chainContext)
2460 CertFreeCertificateChain(chainContext);
2461 });
2462 BOOL status = CertGetCertificateChain(nullptr, // hChainEngine, default
2463 certContext, // pCertContext
2464 nullptr, // pTime, 'now'
2465 tempCertCollection.get(), // hAdditionalStore, additional cert store
2466 &parameters, // pChainPara
2467 CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT, // dwFlags
2468 nullptr, // reserved
2469 &chainContext // ppChainContext
2470 );
2471 if (status == FALSE || !chainContext || chainContext->cChain == 0) {
2472 QSslError error(QSslError::UnableToVerifyFirstCertificate);
2473 sslErrors += error;
2474 emit q->peerVerifyError(error);
2475 return q->state() == QAbstractSocket::ConnectedState;
2476 }
2477
2478 // Helper-function to get a QSslCertificate given a CERT_CHAIN_ELEMENT
2479 static auto getCertificateFromChainElement = [](CERT_CHAIN_ELEMENT *element) {
2480 if (!element)
2481 return QSslCertificate();
2482
2483 const CERT_CONTEXT *certContext = element->pCertContext;
2484 return QTlsPrivate::X509CertificateSchannel::QSslCertificate_from_CERT_CONTEXT(certContext);
2485 };
2486
2487 // Pick a chain to use as the certificate chain, if multiple are available:
2488 // According to https://docs.microsoft.com/en-gb/windows/desktop/api/wincrypt/ns-wincrypt-_cert_chain_context
2489 // this seems to be the best way to get a trusted chain.
2490 CERT_SIMPLE_CHAIN *chain = chainContext->rgpChain[chainContext->cChain - 1];
2491
2492 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_PARTIAL_CHAIN) {
2493 auto error = QSslError(QSslError::SslError::UnableToGetIssuerCertificate,
2494 getCertificateFromChainElement(chain->rgpElement[chain->cElement - 1]));
2495 sslErrors += error;
2496 emit q->peerVerifyError(error);
2497 if (q->state() != QAbstractSocket::ConnectedState)
2498 return false;
2499 }
2500 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_INVALID_BASIC_CONSTRAINTS) {
2501 // @Note: This is actually one of two errors:
2502 // "either the certificate cannot be used to issue other certificates, or the chain path length has been exceeded."
2503 // But here we are checking the chain's status, so we assume the "issuing" error cannot occur here.
2504 auto error = QSslError(QSslError::PathLengthExceeded);
2505 sslErrors += error;
2506 emit q->peerVerifyError(error);
2507 if (q->state() != QAbstractSocket::ConnectedState)
2508 return false;
2509 }
2510 static const DWORD leftoverCertChainErrorMask = CERT_TRUST_IS_CYCLIC | CERT_TRUST_INVALID_EXTENSION
2511 | CERT_TRUST_INVALID_POLICY_CONSTRAINTS | CERT_TRUST_INVALID_NAME_CONSTRAINTS
2512 | CERT_TRUST_CTL_IS_NOT_TIME_VALID | CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID
2513 | CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE;
2514 if (chain->TrustStatus.dwErrorStatus & leftoverCertChainErrorMask) {
2515 auto error = QSslError(QSslError::SslError::UnspecifiedError);
2516 sslErrors += error;
2517 emit q->peerVerifyError(error);
2518 if (q->state() != QAbstractSocket::ConnectedState)
2519 return false;
2520 }
2521
2522 DWORD verifyDepth = chain->cElement;
2523 if (q->peerVerifyDepth() > 0 && DWORD(q->peerVerifyDepth()) < verifyDepth)
2524 verifyDepth = DWORD(q->peerVerifyDepth());
2525
2526 const auto &caCertificates = q->sslConfiguration().caCertificates();
2527
2528 if (!rootCertOnDemandLoadingAllowed()
2529 && !(chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_PARTIAL_CHAIN)
2530 && (q->peerVerifyMode() == QSslSocket::VerifyPeer
2531 || (isClient && q->peerVerifyMode() == QSslSocket::AutoVerifyPeer))) {
2532 // When verifying a peer Windows "helpfully" builds a chain that
2533 // may include roots from the system store. But we don't want that if
2534 // the user has set their own CA certificates.
2535 // Since Windows claims this is not a partial chain the root is included
2536 // and we have to check that it is one of our configured CAs.
2537 CERT_CHAIN_ELEMENT *element = chain->rgpElement[chain->cElement - 1];
2538 QSslCertificate certificate = getCertificateFromChainElement(element);
2539 if (!caCertificates.contains(certificate)) {
2540 auto error = QSslError(QSslError::CertificateUntrusted, certificate);
2541 sslErrors += error;
2542 emit q->peerVerifyError(error);
2543 if (q->state() != QAbstractSocket::ConnectedState)
2544 return false;
2545 }
2546 }
2547
2548 QList<QSslCertificate> peerCertificateChain;
2549 for (DWORD i = 0; i < verifyDepth; i++) {
2550 CERT_CHAIN_ELEMENT *element = chain->rgpElement[i];
2551 QSslCertificate certificate = getCertificateFromChainElement(element);
2552 if (certificate.isNull()) {
2553 const auto &previousCert = !peerCertificateChain.isEmpty() ? peerCertificateChain.last()
2554 : QSslCertificate();
2555 auto error = QSslError(QSslError::SslError::UnableToGetIssuerCertificate, previousCert);
2556 sslErrors += error;
2557 emit q->peerVerifyError(error);
2558 if (previousCert.isNull() || q->state() != QAbstractSocket::ConnectedState)
2559 return false;
2560 }
2561 const QList<QSslCertificateExtension> extensions = certificate.extensions();
2562
2563#ifdef QSSLSOCKET_DEBUG
2564 qCDebug(lcTlsBackendSchannel) << "issuer:" << certificate.issuerDisplayName()
2565 << "\nsubject:" << certificate.subjectDisplayName()
2566 << "\nQSslCertificate info:" << certificate
2567 << "\nextended error info:" << element->pwszExtendedErrorInfo
2568 << "\nerror status:" << element->TrustStatus.dwErrorStatus;
2569#endif
2570
2571 peerCertificateChain.append(certificate);
2572 QTlsBackend::storePeerCertificateChain(d, peerCertificateChain);
2573
2574 if (certificate.isBlacklisted()) {
2575 const auto error = QSslError(QSslError::CertificateBlacklisted, certificate);
2576 sslErrors += error;
2577 emit q->peerVerifyError(error);
2578 if (q->state() != QAbstractSocket::ConnectedState)
2579 return false;
2580 }
2581
2582 LONG result = CertVerifyTimeValidity(nullptr /*== now */, element->pCertContext->pCertInfo);
2583 if (result != 0) {
2584 auto error = QSslError(result == -1 ? QSslError::CertificateNotYetValid
2585 : QSslError::CertificateExpired,
2586 certificate);
2587 sslErrors += error;
2588 emit q->peerVerifyError(error);
2589 if (q->state() != QAbstractSocket::ConnectedState)
2590 return false;
2591 }
2592
2593 //// Errors
2594 if (element->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID) {
2595 // handled right above
2596 Q_ASSERT(!sslErrors.isEmpty());
2597 }
2598 if (element->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED) {
2599 auto error = QSslError(QSslError::CertificateRevoked, certificate);
2600 sslErrors += error;
2601 emit q->peerVerifyError(error);
2602 if (q->state() != QAbstractSocket::ConnectedState)
2603 return false;
2604 }
2605 if (element->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_SIGNATURE_VALID) {
2606 auto error = QSslError(QSslError::CertificateSignatureFailed, certificate);
2607 sslErrors += error;
2608 emit q->peerVerifyError(error);
2609 if (q->state() != QAbstractSocket::ConnectedState)
2610 return false;
2611 }
2612
2613 // While netscape shouldn't be relevant now it defined an extension which is
2614 // still in use. Schannel does not check this automatically, so we do it here.
2615 // It is used to differentiate between client and server certificates.
2616 if (netscapeWrongCertType(extensions, isClient, i == 0))
2617 element->TrustStatus.dwErrorStatus |= CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
2618
2619 if (element->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_VALID_FOR_USAGE) {
2620 auto error = QSslError(QSslError::InvalidPurpose, certificate);
2621 sslErrors += error;
2622 emit q->peerVerifyError(error);
2623 if (q->state() != QAbstractSocket::ConnectedState)
2624 return false;
2625 }
2626 if (element->TrustStatus.dwErrorStatus & CERT_TRUST_IS_UNTRUSTED_ROOT) {
2627 // Override this error if we have the certificate inside our trusted CAs list.
2628 const bool isTrustedRoot = caCertificates.contains(certificate);
2629 if (!isTrustedRoot) {
2630 auto error = QSslError(QSslError::CertificateUntrusted, certificate);
2631 sslErrors += error;
2632 emit q->peerVerifyError(error);
2633 if (q->state() != QAbstractSocket::ConnectedState)
2634 return false;
2635 }
2636 }
2637 static const DWORD certRevocationCheckUnavailableError = CERT_TRUST_IS_OFFLINE_REVOCATION
2638 | CERT_TRUST_REVOCATION_STATUS_UNKNOWN;
2639 if (element->TrustStatus.dwErrorStatus & certRevocationCheckUnavailableError) {
2640 // @future(maybe): Do something with this
2641 }
2642
2643 // Dumping ground of errors that don't fit our specific errors
2644 static const DWORD leftoverCertErrorMask = CERT_TRUST_IS_CYCLIC
2645 | CERT_TRUST_INVALID_EXTENSION | CERT_TRUST_INVALID_NAME_CONSTRAINTS
2646 | CERT_TRUST_INVALID_POLICY_CONSTRAINTS
2647 | CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT
2648 | CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT
2649 | CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT
2650 | CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT
2651 | CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
2652 if (element->TrustStatus.dwErrorStatus & leftoverCertErrorMask) {
2653 auto error = QSslError(QSslError::UnspecifiedError, certificate);
2654 sslErrors += error;
2655 emit q->peerVerifyError(error);
2656 if (q->state() != QAbstractSocket::ConnectedState)
2657 return false;
2658 }
2659 if (element->TrustStatus.dwErrorStatus & CERT_TRUST_INVALID_BASIC_CONSTRAINTS) {
2660 auto it = std::find_if(extensions.cbegin(), extensions.cend(),
2661 [](const QSslCertificateExtension &extension) {
2662 return extension.name() == "basicConstraints"_L1;
2663 });
2664 if (it != extensions.cend()) {
2665 // @Note: This is actually one of two errors:
2666 // "either the certificate cannot be used to issue other certificates,
2667 // or the chain path length has been exceeded."
2668 QVariantMap basicConstraints = it->value().toMap();
2669 QSslError error;
2670 if (i > 0 && !basicConstraints.value("ca"_L1, false).toBool())
2671 error = QSslError(QSslError::InvalidPurpose, certificate);
2672 else
2673 error = QSslError(QSslError::PathLengthExceeded, certificate);
2674 sslErrors += error;
2675 emit q->peerVerifyError(error);
2676 if (q->state() != QAbstractSocket::ConnectedState)
2677 return false;
2678 }
2679 }
2680 if (element->TrustStatus.dwErrorStatus & CERT_TRUST_IS_EXPLICIT_DISTRUST) {
2681 auto error = QSslError(QSslError::CertificateBlacklisted, certificate);
2682 sslErrors += error;
2683 emit q->peerVerifyError(error);
2684 if (q->state() != QAbstractSocket::ConnectedState)
2685 return false;
2686 }
2687
2688 if (element->TrustStatus.dwInfoStatus & CERT_TRUST_IS_SELF_SIGNED) {
2689 // If it's self-signed *and* a CA then we can assume it's a root CA certificate
2690 // and we can ignore the "self-signed" note:
2691 // We check the basicConstraints certificate extension when possible, but this didn't
2692 // exist for version 1, so we can only guess in that case
2693 const bool isRootCertificateAuthority = isCertificateAuthority(extensions)
2694 || certificate.version() == "1";
2695
2696 // Root certificate tends to be signed by themselves, so ignore self-signed status.
2697 if (!isRootCertificateAuthority) {
2698 auto error = QSslError(QSslError::SelfSignedCertificate, certificate);
2699 sslErrors += error;
2700 emit q->peerVerifyError(error);
2701 if (q->state() != QAbstractSocket::ConnectedState)
2702 return false;
2703 }
2704 }
2705 }
2706
2707 if (!peerCertificateChain.isEmpty())
2708 QTlsBackend::storePeerCertificate(d, peerCertificateChain.constFirst());
2709
2710 const auto &configuration = q->sslConfiguration(); // Probably, updated by QTlsBackend::storePeerCertificate etc.
2711 // @Note: Somewhat copied from qsslsocket_mac.cpp
2712 const bool doVerifyPeer = q->peerVerifyMode() == QSslSocket::VerifyPeer
2713 || (q->peerVerifyMode() == QSslSocket::AutoVerifyPeer
2714 && d->tlsMode() == QSslSocket::SslClientMode);
2715 // Check the peer certificate itself. First try the subject's common name
2716 // (CN) as a wildcard, then try all alternate subject name DNS entries the
2717 // same way.
2718 if (!configuration.peerCertificate().isNull()) {
2719 // but only if we're a client connecting to a server
2720 // if we're the server, don't check CN
2721 if (d->tlsMode() == QSslSocket::SslClientMode) {
2722 const auto verificationPeerName = d->verificationName();
2723 const QString peerName(verificationPeerName.isEmpty() ? q->peerName() : verificationPeerName);
2724 if (!isMatchingHostname(configuration.peerCertificate(), peerName)) {
2725 // No matches in common names or alternate names.
2726 const QSslError error(QSslError::HostNameMismatch, configuration.peerCertificate());
2727 sslErrors += error;
2728 emit q->peerVerifyError(error);
2729 if (q->state() != QAbstractSocket::ConnectedState)
2730 return false;
2731 }
2732 }
2733 } else if (doVerifyPeer) {
2734 // No peer certificate presented. Report as error if the socket
2735 // expected one.
2736 const QSslError error(QSslError::NoPeerCertificate);
2737 sslErrors += error;
2738 emit q->peerVerifyError(error);
2739 if (q->state() != QAbstractSocket::ConnectedState)
2740 return false;
2741 }
2742
2743 return true;
2744}
2745
2746bool TlsCryptographSchannel::rootCertOnDemandLoadingAllowed()
2747{
2748 Q_ASSERT(d);
2749 return d->isRootsOnDemandAllowed() && QSslSocketPrivate::rootCertOnDemandLoadingSupported();
2750}
2751
2752} // namespace QTlsPrivate
2753
2754QT_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)
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