summaryrefslogtreecommitdiffstats
path: root/src/plugins/tls/schannel/qx509_schannel.cpp
blob: d9d82dce29f415dfd689ad2f0d5fcccf9e6a8e05 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qtlsbackend_schannel_p.h"
#include "qtlskey_schannel_p.h"
#include "qx509_schannel_p.h"

#include <QtCore/private/qsystemerror_p.h>
#include <QtNetwork/private/qsslcertificate_p.h>

#include <memory>

QT_BEGIN_NAMESPACE

namespace QTlsPrivate {

X509CertificateSchannel::X509CertificateSchannel() = default;

X509CertificateSchannel::~X509CertificateSchannel()
{
    if (certificateContext)
        CertFreeCertificateContext(certificateContext);
}

TlsKey *X509CertificateSchannel::publicKey() const
{
    auto key = std::make_unique<TlsKeySchannel>(QSsl::PublicKey);
    if (publicKeyAlgorithm != QSsl::Opaque)
        key->decodeDer(QSsl::PublicKey, publicKeyAlgorithm, publicKeyDerData, {}, false);

    return key.release();
}

Qt::HANDLE X509CertificateSchannel::handle() const
{
    return Qt::HANDLE(certificateContext);
}

QSslCertificate X509CertificateSchannel::QSslCertificate_from_CERT_CONTEXT(const CERT_CONTEXT *certificateContext)
{
    QByteArray derData = QByteArray((const char *)certificateContext->pbCertEncoded,
                                    certificateContext->cbCertEncoded);
    QSslCertificate certificate(derData, QSsl::Der);
    if (!certificate.isNull()) {
        auto *certBackend = QTlsBackend::backend<X509CertificateSchannel>(certificate);
        Q_ASSERT(certBackend);
        certBackend->certificateContext = CertDuplicateCertificateContext(certificateContext);
    }
    return certificate;
}

bool X509CertificateSchannel::importPkcs12(QIODevice *device, QSslKey *key, QSslCertificate *cert,
                                           QList<QSslCertificate> *caCertificates,
                                           const QByteArray &passPhrase)
{
    // These are required
    Q_ASSERT(device);
    Q_ASSERT(key);
    Q_ASSERT(cert);

    QByteArray pkcs12data = device->readAll();
    if (pkcs12data.size() == 0)
        return false;

    CRYPT_DATA_BLOB dataBlob;
    dataBlob.cbData = pkcs12data.size();
    dataBlob.pbData = reinterpret_cast<BYTE*>(pkcs12data.data());

    const auto password = QString::fromUtf8(passPhrase);

    const DWORD flags = (CRYPT_EXPORTABLE | PKCS12_NO_PERSIST_KEY | PKCS12_PREFER_CNG_KSP);

    auto certStore = QHCertStorePointer(PFXImportCertStore(&dataBlob,
                                                           reinterpret_cast<LPCWSTR>(password.utf16()),
                                                           flags));

    if (!certStore) {
        qCWarning(lcTlsBackendSchannel, "Failed to import PFX data: %s",
                  qPrintable(QSystemError::windowsString()));
        return false;
    }

    // first extract the certificate with the private key
    const auto certContext = QPCCertContextPointer(CertFindCertificateInStore(certStore.get(),
                                                                              X509_ASN_ENCODING |
                                                                              PKCS_7_ASN_ENCODING,
                                                                              0,
                                                                              CERT_FIND_HAS_PRIVATE_KEY,
                                                                              nullptr, nullptr));

    if (!certContext) {
        qCWarning(lcTlsBackendSchannel, "Failed to find certificate in PFX store: %s",
                  qPrintable(QSystemError::windowsString()));
        return false;
    }

    *cert = QSslCertificate_from_CERT_CONTEXT(certContext.get());

    // retrieve the private key for the certificate
    NCRYPT_KEY_HANDLE keyHandle = {};
    DWORD keyHandleSize = sizeof(keyHandle);
    if (!CertGetCertificateContextProperty(certContext.get(), CERT_NCRYPT_KEY_HANDLE_PROP_ID,
                                           &keyHandle, &keyHandleSize)) {
        qCWarning(lcTlsBackendSchannel, "Failed to find private key handle in certificate context: %s",
                  qPrintable(QSystemError::windowsString()));
        return false;
    }

    SECURITY_STATUS securityStatus = ERROR_SUCCESS;

    // we need the 'NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG' to make NCryptExportKey succeed
    DWORD policy = (NCRYPT_ALLOW_EXPORT_FLAG | NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG);
    DWORD policySize = sizeof(policy);

    securityStatus = NCryptSetProperty(keyHandle, NCRYPT_EXPORT_POLICY_PROPERTY,
                                       reinterpret_cast<BYTE*>(&policy), policySize, 0);
    if (securityStatus != ERROR_SUCCESS) {
        qCWarning(lcTlsBackendSchannel, "Failed to update export policy of private key: 0x%x",
                  static_cast<unsigned int>(securityStatus));
        return false;
    }

    DWORD blobSize = {};
    securityStatus = NCryptExportKey(keyHandle, {}, BCRYPT_RSAFULLPRIVATE_BLOB,
                                     nullptr, nullptr, 0, &blobSize, 0);
    if (securityStatus != ERROR_SUCCESS) {
        qCWarning(lcTlsBackendSchannel, "Failed to retrieve private key size: 0x%x",
                  static_cast<unsigned int>(securityStatus));
        return false;
    }

    std::vector<BYTE> blob(blobSize);
    securityStatus = NCryptExportKey(keyHandle, {}, BCRYPT_RSAFULLPRIVATE_BLOB,
                                     nullptr, blob.data(), blobSize, &blobSize, 0);
    if (securityStatus != ERROR_SUCCESS) {
        qCWarning(lcTlsBackendSchannel, "Failed to retrieve private key from certificate: 0x%x",
                  static_cast<unsigned int>(securityStatus));
        return false;
    }

    DWORD privateKeySize = {};

    if (!CryptEncodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, CNG_RSA_PRIVATE_KEY_BLOB,
                           blob.data(), nullptr, &privateKeySize)) {
        qCWarning(lcTlsBackendSchannel, "Failed to encode private key to key info: %s",
                  qPrintable(QSystemError::windowsString()));
        return false;
    }

    std::vector<BYTE> privateKeyData(privateKeySize);

    CRYPT_PRIVATE_KEY_INFO privateKeyInfo = {};
    privateKeyInfo.Algorithm.pszObjId = const_cast<PSTR>(szOID_RSA_RSA);
    privateKeyInfo.PrivateKey.cbData = privateKeySize;
    privateKeyInfo.PrivateKey.pbData = privateKeyData.data();

    if (!CryptEncodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                           CNG_RSA_PRIVATE_KEY_BLOB, blob.data(),
                           privateKeyInfo.PrivateKey.pbData, &privateKeyInfo.PrivateKey.cbData)) {
        qCWarning(lcTlsBackendSchannel, "Failed to encode private key to key info: %s",
                  qPrintable(QSystemError::windowsString()));
        return false;
    }


    DWORD derSize = {};

    if (!CryptEncodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, PKCS_PRIVATE_KEY_INFO,
                           &privateKeyInfo, nullptr, &derSize)) {
        qCWarning(lcTlsBackendSchannel, "Failed to encode key info to DER format: %s",
                  qPrintable(QSystemError::windowsString()));

        return false;
    }

    QByteArray derData(derSize, Qt::Uninitialized);

    if (!CryptEncodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, PKCS_PRIVATE_KEY_INFO,
                           &privateKeyInfo, reinterpret_cast<BYTE*>(derData.data()), &derSize)) {
        qCWarning(lcTlsBackendSchannel, "Failed to encode key info to DER format: %s",
                  qPrintable(QSystemError::windowsString()));

        return false;
    }

    *key = QSslKey(derData, QSsl::Rsa, QSsl::Der, QSsl::PrivateKey);
    if (key->isNull()) {
        qCWarning(lcTlsBackendSchannel, "Failed to parse private key from DER format");
        return false;
    }

    // fetch all the remaining certificates as CA certificates
    if (caCertificates) {
        PCCERT_CONTEXT caCertContext = nullptr;
        while ((caCertContext = CertFindCertificateInStore(certStore.get(),
                                                           X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                                                           0, CERT_FIND_ANY, nullptr, caCertContext))) {
            if (CertCompareCertificate(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                                       certContext->pCertInfo, caCertContext->pCertInfo))
                continue; // ignore the certificate with private key

            auto caCertificate = QSslCertificate_from_CERT_CONTEXT(caCertContext);

            caCertificates->append(caCertificate);
        }
    }

    return true;
}

} // namespace QTlsPrivate

QT_END_NAMESPACE