cutelyst 5.0.0
A C++ Web Framework built on top of Qt, using the simple approach of Catalyst (Perl) framework.
credentialpassword.cpp
1/*
2 * SPDX-FileCopyrightText: (C) 2013-2022 Daniel Nicoletti <dantti12@gmail.com>
3 * SPDX-License-Identifier: BSD-3-Clause
4 */
5#include "authenticationrealm.h"
6#include "credentialpassword_p.h"
7
8#include <QFile>
9#include <QLoggingCategory>
10#include <QMessageAuthenticationCode>
11#include <QUuid>
12
13using namespace Cutelyst;
14
15Q_LOGGING_CATEGORY(C_CREDENTIALPASSWORD, "cutelyst.plugin.credentialpassword", QtWarningMsg)
16
19 , d_ptr(new CredentialPasswordPrivate)
20{
21}
22
24{
25 delete d_ptr;
26}
27
30 const ParamsMultiMap &authinfo)
31{
34 AuthenticationUser _user = realm->findUser(c, authinfo);
35 if (!_user.isNull()) {
36 if (d->checkPassword(_user, authinfo)) {
37 user = _user;
38 } else {
39 qCDebug(C_CREDENTIALPASSWORD) << "Password didn't match";
40 }
41 } else {
42 qCDebug(C_CREDENTIALPASSWORD)
43 << "Unable to locate a user matching user info provided in realm";
44 }
45 return user;
46}
47
49{
50 Q_D(const CredentialPassword);
51 return d->passwordField;
52}
53
55{
57 d->passwordField = fieldName;
58}
59
61{
62 Q_D(const CredentialPassword);
63 return d->passwordType;
64}
65
71
73{
74 Q_D(const CredentialPassword);
75 return d->passwordPreSalt;
76}
77
79{
81 d->passwordPreSalt = passwordPreSalt;
82}
83
85{
86 Q_D(const CredentialPassword);
87 return d->passwordPostSalt;
88}
89
91{
93 d->passwordPostSalt = passwordPostSalt;
94}
95
96// To avoid timming attack
97bool slowEquals(const QByteArray &a, const QByteArray &b)
98{
99 int diff = a.size() ^ b.size();
100 for (int i = 0; i < a.size() && i < b.size(); i++) {
101 diff |= a[i] ^ b[i];
102 }
103 return diff == 0;
104}
105
106namespace {
107#define HASH_SECTIONS 4
108#define HASH_ALGORITHM_INDEX 0
109#define HASH_ITERATION_INDEX 1
110#define HASH_SALT_INDEX 2
111#define HASH_PBKDF2_INDEX 3
112} // namespace
113
114bool CredentialPassword::validatePassword(const QByteArray &password, const QByteArray &correctHash)
115{
116 QByteArrayList params = correctHash.split(':');
117 if (params.size() < HASH_SECTIONS) {
118 return false;
119 }
120
121 int method = CredentialPasswordPrivate::cryptoStrToEnum(params.at(HASH_ALGORITHM_INDEX));
122 if (method == -1) {
123 return false;
124 }
125
126 QByteArray pbkdf2Hash = QByteArray::fromBase64(params.at(HASH_PBKDF2_INDEX));
127 return slowEquals(pbkdf2Hash,
128 pbkdf2(static_cast<QCryptographicHash::Algorithm>(method),
129 password,
130 params.at(HASH_SALT_INDEX),
131 params.at(HASH_ITERATION_INDEX).toInt(),
132 pbkdf2Hash.length()));
133}
134
137 int iterations,
138 int saltByteSize,
139 int hashByteSize)
140{
141 QByteArray salt;
142#ifdef Q_OS_LINUX
143 QFile random(QStringLiteral("/dev/urandom"));
144 if (random.open(QIODevice::ReadOnly)) {
145 salt = random.read(saltByteSize).toBase64();
146 } else {
147#endif
149#ifdef Q_OS_LINUX
150 }
151#endif
152
153 const QByteArray methodStr = CredentialPasswordPrivate::cryptoEnumToStr(method);
154 return methodStr + ':' + QByteArray::number(iterations) + ':' + salt + ':' +
155 pbkdf2(method, password, salt, iterations, hashByteSize).toBase64();
156}
157
159{
160 return createPassword(password, QCryptographicHash::Sha512, 10000, 16, 16);
161}
162
163// TODO https://crackstation.net/hashing-security.htm
164// shows a different Algorithm that seems a bit simpler
165// this one does passes the RFC6070 tests
166// https://www.ietf.org/rfc/rfc6070.txt
168 const QByteArray &password,
169 const QByteArray &salt,
170 int rounds,
171 int keyLength)
172{
173 QByteArray key;
174
175 if (rounds <= 0 || keyLength <= 0) {
176 qCCritical(C_CREDENTIALPASSWORD, "PBKDF2 ERROR: Invalid parameters.");
177 return key;
178 }
179
180 if (salt.size() == 0 || salt.size() > std::numeric_limits<int>::max() - 4) {
181 return key;
182 }
183 key.reserve(keyLength);
184
185 int saltSize = salt.size();
186 QByteArray asalt = salt;
187 asalt.resize(saltSize + 4);
188
189 QByteArray d1;
190 QByteArray obuf;
191
192 QMessageAuthenticationCode code(method, password);
193
194 for (int count = 1, remainingBytes = keyLength; remainingBytes > 0; ++count) {
195 asalt[saltSize + 0] = static_cast<char>((count >> 24) & 0xff);
196 asalt[saltSize + 1] = static_cast<char>((count >> 16) & 0xff);
197 asalt[saltSize + 2] = static_cast<char>((count >> 8) & 0xff);
198 asalt[saltSize + 3] = static_cast<char>(count & 0xff);
199
200 code.reset();
201 code.addData(asalt);
202 obuf = d1 = code.result();
203
204 for (int i = 1; i < rounds; ++i) {
205 code.reset();
206 code.addData(d1);
207 d1 = code.result();
208 auto it = obuf.begin();
209 auto d1It = d1.cbegin();
210 while (d1It != d1.cend()) {
211 *it = *it ^ *d1It;
212 ++it;
213 ++d1It;
214 }
215 }
216
217 key.append(obuf);
218 remainingBytes -= obuf.size();
219 }
220
221 key.truncate(keyLength);
222 return key;
223}
224
226 const QByteArray &key,
227 const QByteArray &message)
228{
229 return QMessageAuthenticationCode::hash(key, message, method);
230}
231
232bool CredentialPasswordPrivate::checkPassword(const AuthenticationUser &user,
233 const ParamsMultiMap &authinfo)
234{
235 const QString password = passwordPreSalt + authinfo.value(passwordField) + passwordPostSalt;
236 const QString storedPassword = user.value(passwordField).toString();
237
238 if (Q_LIKELY(passwordType == CredentialPassword::Hashed)) {
239 return CredentialPassword::validatePassword(password.toUtf8(), storedPassword.toUtf8());
240 } else if (passwordType == CredentialPassword::Clear) {
241 return storedPassword == password;
242 } else if (passwordType == CredentialPassword::None) {
243 qCDebug(C_CREDENTIALPASSWORD) << "CredentialPassword is set to ignore password check";
244 return true;
245 }
246
247 return false;
248}
249
250QByteArray CredentialPasswordPrivate::cryptoEnumToStr(QCryptographicHash::Algorithm method)
251{
252 QByteArray hashmethod;
253
254#ifndef QT_CRYPTOGRAPHICHASH_ONLY_SHA1
255 if (method == QCryptographicHash::Md4) {
256 hashmethod = QByteArrayLiteral("Md4");
257 } else if (method == QCryptographicHash::Md5) {
258 hashmethod = QByteArrayLiteral("Md5");
259 }
260#endif
261 if (method == QCryptographicHash::Sha1) {
262 hashmethod = QByteArrayLiteral("Sha1");
263 }
264#ifndef QT_CRYPTOGRAPHICHASH_ONLY_SHA1
265 if (method == QCryptographicHash::Sha224) {
266 hashmethod = QByteArrayLiteral("Sha224");
267 } else if (method == QCryptographicHash::Sha256) {
268 hashmethod = QByteArrayLiteral("Sha256");
269 } else if (method == QCryptographicHash::Sha384) {
270 hashmethod = QByteArrayLiteral("Sha384");
271 } else if (method == QCryptographicHash::Sha512) {
272 hashmethod = QByteArrayLiteral("Sha512");
273 } else if (method == QCryptographicHash::Sha3_224) {
274 hashmethod = QByteArrayLiteral("Sha3_224");
275 } else if (method == QCryptographicHash::Sha3_256) {
276 hashmethod = QByteArrayLiteral("Sha3_256");
277 } else if (method == QCryptographicHash::Sha3_384) {
278 hashmethod = QByteArrayLiteral("Sha3_384");
279 } else if (method == QCryptographicHash::Sha3_512) {
280 hashmethod = QByteArrayLiteral("Sha3_512");
281 }
282#endif
283
284 return hashmethod;
285}
286
287int CredentialPasswordPrivate::cryptoStrToEnum(const QByteArray &hashMethod)
288{
289 QByteArray hashmethod = hashMethod;
290
291 int method = -1;
292#ifndef QT_CRYPTOGRAPHICHASH_ONLY_SHA1
293 if (hashmethod == "Md4") {
295 } else if (hashmethod == "Md5") {
297 }
298#endif
299 if (hashmethod == "Sha1") {
301 }
302#ifndef QT_CRYPTOGRAPHICHASH_ONLY_SHA1
303 if (hashmethod == "Sha224") {
305 } else if (hashmethod == "Sha256") {
307 } else if (hashmethod == "Sha384") {
309 } else if (hashmethod == "Sha512") {
311 } else if (hashmethod == "Sha3_224") {
313 } else if (hashmethod == "Sha3_256") {
315 } else if (hashmethod == "Sha3_384") {
317 } else if (hashmethod == "Sha3_512") {
319 }
320#endif
321
322 return method;
323}
324
325#include "moc_credentialpassword.cpp"
Abstract class to validate authentication credentials like user name and password.
Combines user store and credential validation into a named realm.
virtual AuthenticationUser findUser(Context *c, const ParamsMultiMap &userinfo)
Container for user data retrieved from an AuthenticationStore.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant()) const
The Cutelyst Context.
Definition context.h:42
Use password based authentication to authenticate a user.
void setPasswordType(PasswordType type)
void setPasswordPostSalt(const QString &passwordPostSalt)
AuthenticationUser authenticate(Context *c, AuthenticationRealm *realm, const ParamsMultiMap &authinfo) final
static QByteArray pbkdf2(QCryptographicHash::Algorithm method, const QByteArray &password, const QByteArray &salt, int rounds, int keyLength)
static bool validatePassword(const QByteArray &password, const QByteArray &correctHash)
static QByteArray createPassword(const QByteArray &password, QCryptographicHash::Algorithm method, int iterations, int saltByteSize, int hashByteSize)
void setPasswordField(const QString &fieldName)
static QByteArray hmac(QCryptographicHash::Algorithm method, const QByteArray &key, const QByteArray &message)
void setPasswordPreSalt(const QString &passwordPreSalt)
The Cutelyst namespace holds all public Cutelyst API.
QByteArray & append(QByteArrayView data)
QByteArray::iterator begin()
QByteArray::const_iterator cbegin() const const
QByteArray::const_iterator cend() const const
QByteArray fromBase64(const QByteArray &base64, QByteArray::Base64Options options)
qsizetype length() const const
QByteArray number(double n, char format, int precision)
void reserve(qsizetype size)
void resize(qsizetype newSize, char c)
qsizetype size() const const
QList< QByteArray > split(char sep) const const
QByteArray toBase64(QByteArray::Base64Options options) const const
void truncate(qsizetype pos)
bool open(FILE *fh, QIODeviceBase::OpenMode mode, QFileDevice::FileHandleFlags handleFlags)
QByteArray read(qint64 maxSize)
QList::const_reference at(qsizetype i) const const
qsizetype size() const const
bool addData(QIODevice *device)
QByteArray hash(QByteArrayView message, QByteArrayView key, QCryptographicHash::Algorithm method)
QByteArray result() const const
T value(const Key &key, const T &defaultValue) const const
QByteArray toUtf8() const const
QUuid createUuid()
QByteArray toRfc4122() const const
QString toString() const const