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