1 /****************************************************************************
2 **
3 ** Copyright (C) 2018 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 3 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL3 included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 3 requirements
23 ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24 **
25 ** GNU General Public License Usage
26 ** Alternatively, this file may be used under the terms of the GNU
27 ** General Public License version 2.0 or (at your option) the GNU General
28 ** Public license version 3 or any later version approved by the KDE Free
29 ** Qt Foundation. The licenses are as published by the Free Software
30 ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31 ** included in the packaging of this file. Please review the following
32 ** information to ensure the GNU General Public License requirements will
33 ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34 ** https://www.gnu.org/licenses/gpl-3.0.html.
35 **
36 ** $QT_END_LICENSE$
37 **
38 ****************************************************************************/
39 
40 #include "qssl_p.h"
41 #include "qsslkey.h"
42 #include "qsslkey_p.h"
43 #include "qsslcertificate_p.h"
44 
45 #include <QtCore/qbytearray.h>
46 #include <QtCore/qscopeguard.h>
47 
48 QT_BEGIN_NAMESPACE
49 
50 namespace {
getName(QSslKeyPrivate::Cipher cipher)51 const wchar_t *getName(QSslKeyPrivate::Cipher cipher)
52 {
53     switch (cipher) {
54     case QSslKeyPrivate::Cipher::DesCbc:
55         return BCRYPT_DES_ALGORITHM;
56     case QSslKeyPrivate::Cipher::DesEde3Cbc:
57         return BCRYPT_3DES_ALGORITHM;
58     case QSslKeyPrivate::Cipher::Rc2Cbc:
59         return BCRYPT_RC2_ALGORITHM;
60     case QSslKeyPrivate::Cipher::Aes128Cbc:
61     case QSslKeyPrivate::Cipher::Aes192Cbc:
62     case QSslKeyPrivate::Cipher::Aes256Cbc:
63         return BCRYPT_AES_ALGORITHM;
64     }
65     Q_UNREACHABLE();
66 }
67 
getHandle(QSslKeyPrivate::Cipher cipher)68 BCRYPT_ALG_HANDLE getHandle(QSslKeyPrivate::Cipher cipher)
69 {
70     BCRYPT_ALG_HANDLE handle;
71     NTSTATUS status = BCryptOpenAlgorithmProvider(
72             &handle, // phAlgorithm
73             getName(cipher), // pszAlgId
74             nullptr, // pszImplementation
75             0 // dwFlags
76     );
77     if (status < 0) {
78         qCWarning(lcSsl, "Failed to open algorithm handle (%ld)!", status);
79         return nullptr;
80     }
81 
82     return handle;
83 }
84 
generateSymmetricKey(BCRYPT_ALG_HANDLE handle,const QByteArray & key)85 BCRYPT_KEY_HANDLE generateSymmetricKey(BCRYPT_ALG_HANDLE handle,
86                                        const QByteArray &key)
87 {
88     BCRYPT_KEY_HANDLE keyHandle;
89     NTSTATUS status = BCryptGenerateSymmetricKey(
90             handle, // hAlgorithm
91             &keyHandle, // phKey
92             nullptr, // pbKeyObject (can ignore)
93             0, // cbKeyObject (also ignoring)
94             reinterpret_cast<unsigned char *>(const_cast<char *>(key.data())), // pbSecret
95             ULONG(key.length()), // cbSecret
96             0 // dwFlags
97     );
98     if (status < 0) {
99         qCWarning(lcSsl, "Failed to generate symmetric key (%ld)!", status);
100         return nullptr;
101     }
102 
103     status = BCryptSetProperty(
104             keyHandle, // hObject
105             BCRYPT_CHAINING_MODE, // pszProperty
106             reinterpret_cast<UCHAR *>(const_cast<wchar_t *>(BCRYPT_CHAIN_MODE_CBC)), // pbInput
107             ARRAYSIZE(BCRYPT_CHAIN_MODE_CBC), // cbInput
108             0 // dwFlags
109     );
110     if (status < 0) {
111         BCryptDestroyKey(keyHandle);
112         qCWarning(lcSsl, "Failed to change the symmetric key's chaining mode (%ld)!", status);
113         return nullptr;
114     }
115     return keyHandle;
116 }
117 
doCrypt(QSslKeyPrivate::Cipher cipher,const QByteArray & data,const QByteArray & key,const QByteArray & iv,bool encrypt)118 QByteArray doCrypt(QSslKeyPrivate::Cipher cipher, const QByteArray &data, const QByteArray &key,
119                    const QByteArray &iv, bool encrypt)
120 {
121     BCRYPT_ALG_HANDLE handle = getHandle(cipher);
122     if (!handle)
123         return {};
124     auto handleDealloc = qScopeGuard([&handle]() {
125         BCryptCloseAlgorithmProvider(handle, 0);
126     });
127 
128     BCRYPT_KEY_HANDLE keyHandle = generateSymmetricKey(handle, key);
129     if (!keyHandle)
130         return {};
131     auto keyHandleDealloc = qScopeGuard([&keyHandle]() {
132         BCryptDestroyKey(keyHandle);
133     });
134 
135     QByteArray ivCopy = iv; // This gets modified, so we take a copy
136 
137     ULONG sizeNeeded = 0;
138     QVarLengthArray<unsigned char> output;
139     auto cryptFunction = encrypt ? BCryptEncrypt : BCryptDecrypt;
140     for (int i = 0; i < 2; i++) {
141         output.resize(int(sizeNeeded));
142         auto input = reinterpret_cast<unsigned char *>(const_cast<char *>(data.data()));
143         // Need to call it twice because the first iteration lets us know the size needed.
144         NTSTATUS status = cryptFunction(
145                 keyHandle, // hKey
146                 input, // pbInput
147                 ULONG(data.length()), // cbInput
148                 nullptr, // pPaddingInfo
149                 reinterpret_cast<unsigned char *>(ivCopy.data()), // pbIV
150                 ULONG(ivCopy.length()), // cbIV
151                 sizeNeeded ? output.data() : nullptr, // pbOutput
152                 ULONG(output.length()), // cbOutput
153                 &sizeNeeded, // pcbResult
154                 BCRYPT_BLOCK_PADDING // dwFlags
155         );
156         if (status < 0) {
157             qCWarning(lcSsl, "%s failed (%ld)!", encrypt ? "Encrypt" : "Decrypt", status);
158             return {};
159         }
160     }
161 
162     return QByteArray(reinterpret_cast<const char *>(output.constData()), int(sizeNeeded));
163 }
164 } // anonymous namespace
165 
decrypt(Cipher cipher,const QByteArray & data,const QByteArray & key,const QByteArray & iv)166 QByteArray QSslKeyPrivate::decrypt(Cipher cipher, const QByteArray &data, const QByteArray &key,
167                                    const QByteArray &iv)
168 {
169     return doCrypt(cipher, data, key, iv, false);
170 }
171 
encrypt(Cipher cipher,const QByteArray & data,const QByteArray & key,const QByteArray & iv)172 QByteArray QSslKeyPrivate::encrypt(Cipher cipher, const QByteArray &data, const QByteArray &key,
173                                    const QByteArray &iv)
174 {
175     return doCrypt(cipher, data, key, iv, true);
176 }
177 
178 QT_END_NAMESPACE
179