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