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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
|
/*
* Copyright (C) 2017 Sami Vänttinen <sami.vanttinen@protonmail.com>
* Copyright (C) 2017 KeePassXC Team <team@keepassxc.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "BrowserAction.h"
#include "BrowserSettings.h"
#include "NativeMessagingBase.h"
#include "config-keepassx.h"
#include "sodium.h"
#include "sodium/crypto_box.h"
#include "sodium/randombytes.h"
#include <QJsonDocument>
#include <QJsonParseError>
BrowserAction::BrowserAction(BrowserService& browserService)
: m_mutex(QMutex::Recursive)
, m_browserService(browserService)
, m_associated(false)
{
}
QJsonObject BrowserAction::readResponse(const QJsonObject& json)
{
if (json.isEmpty()) {
return QJsonObject();
}
bool triggerUnlock = false;
const QString trigger = json.value("triggerUnlock").toString();
if (!trigger.isEmpty() && trigger.compare("true", Qt::CaseSensitive) == 0) {
triggerUnlock = true;
}
const QString action = json.value("action").toString();
if (action.isEmpty()) {
return QJsonObject();
}
QMutexLocker locker(&m_mutex);
if (action.compare("change-public-keys", Qt::CaseSensitive) != 0 && !m_browserService.isDatabaseOpened()) {
if (m_clientPublicKey.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_CLIENT_PUBLIC_KEY_NOT_RECEIVED);
} else if (!m_browserService.openDatabase(triggerUnlock)) {
return getErrorReply(action, ERROR_KEEPASS_DATABASE_NOT_OPENED);
}
}
return handleAction(json);
}
// Private functions
///////////////////////
QJsonObject BrowserAction::handleAction(const QJsonObject& json)
{
QString action = json.value("action").toString();
if (action.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_INCORRECT_ACTION);
}
if (action.compare("change-public-keys", Qt::CaseSensitive) == 0) {
return handleChangePublicKeys(json, action);
} else if (action.compare("get-databasehash", Qt::CaseSensitive) == 0) {
return handleGetDatabaseHash(json, action);
} else if (action.compare("associate", Qt::CaseSensitive) == 0) {
return handleAssociate(json, action);
} else if (action.compare("test-associate", Qt::CaseSensitive) == 0) {
return handleTestAssociate(json, action);
} else if (action.compare("get-logins", Qt::CaseSensitive) == 0) {
return handleGetLogins(json, action);
} else if (action.compare("generate-password", Qt::CaseSensitive) == 0) {
return handleGeneratePassword(json, action);
} else if (action.compare("set-login", Qt::CaseSensitive) == 0) {
return handleSetLogin(json, action);
} else if (action.compare("lock-database", Qt::CaseSensitive) == 0) {
return handleLockDatabase(json, action);
}
// Action was not recognized
return getErrorReply(action, ERROR_KEEPASS_INCORRECT_ACTION);
}
QJsonObject BrowserAction::handleChangePublicKeys(const QJsonObject& json, const QString& action)
{
QMutexLocker locker(&m_mutex);
const QString nonce = json.value("nonce").toString();
const QString clientPublicKey = json.value("publicKey").toString();
if (clientPublicKey.isEmpty() || nonce.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_CLIENT_PUBLIC_KEY_NOT_RECEIVED);
}
m_associated = false;
unsigned char pk[crypto_box_PUBLICKEYBYTES];
unsigned char sk[crypto_box_SECRETKEYBYTES];
crypto_box_keypair(pk, sk);
const QString publicKey = getBase64FromKey(pk, crypto_box_PUBLICKEYBYTES);
const QString secretKey = getBase64FromKey(sk, crypto_box_SECRETKEYBYTES);
m_clientPublicKey = clientPublicKey;
m_publicKey = publicKey;
m_secretKey = secretKey;
QJsonObject response = buildMessage(incrementNonce(nonce));
response["action"] = action;
response["publicKey"] = publicKey;
return response;
}
QJsonObject BrowserAction::handleGetDatabaseHash(const QJsonObject& json, const QString& action)
{
const QString hash = getDatabaseHash();
const QString nonce = json.value("nonce").toString();
const QString encrypted = json.value("message").toString();
const QJsonObject decrypted = decryptMessage(encrypted, nonce, action);
if (decrypted.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_CANNOT_DECRYPT_MESSAGE);
}
if (hash.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_DATABASE_HASH_NOT_RECEIVED);
}
QString command = decrypted.value("action").toString();
if (!command.isEmpty() && command.compare("get-databasehash", Qt::CaseSensitive) == 0) {
const QString newNonce = incrementNonce(nonce);
QJsonObject message = buildMessage(newNonce);
message["hash"] = hash;
return buildResponse(action, message, newNonce);
}
return getErrorReply(action, ERROR_KEEPASS_CANNOT_DECRYPT_MESSAGE);
}
QJsonObject BrowserAction::handleAssociate(const QJsonObject& json, const QString& action)
{
const QString hash = getDatabaseHash();
const QString nonce = json.value("nonce").toString();
const QString encrypted = json.value("message").toString();
const QJsonObject decrypted = decryptMessage(encrypted, nonce, action);
if (decrypted.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_CANNOT_DECRYPT_MESSAGE);
}
const QString key = decrypted.value("key").toString();
if (key.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_ASSOCIATION_FAILED);
}
QMutexLocker locker(&m_mutex);
if (key.compare(m_clientPublicKey, Qt::CaseSensitive) == 0) {
// Check for identification key. If it's not found, ensure backwards compatibility and use the current public key
const QString idKey = decrypted.value("idKey").toString();
const QString id = m_browserService.storeKey((idKey.isEmpty() ? key: idKey));
if (id.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_ACTION_CANCELLED_OR_DENIED);
}
m_associated = true;
const QString newNonce = incrementNonce(nonce);
QJsonObject message = buildMessage(newNonce);
message["hash"] = hash;
message["id"] = id;
return buildResponse(action, message, newNonce);
}
return getErrorReply(action, ERROR_KEEPASS_ASSOCIATION_FAILED);
}
QJsonObject BrowserAction::handleTestAssociate(const QJsonObject& json, const QString& action)
{
const QString hash = getDatabaseHash();
const QString nonce = json.value("nonce").toString();
const QString encrypted = json.value("message").toString();
const QJsonObject decrypted = decryptMessage(encrypted, nonce, action);
if (decrypted.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_CANNOT_DECRYPT_MESSAGE);
}
const QString responseKey = decrypted.value("key").toString();
const QString id = decrypted.value("id").toString();
if (responseKey.isEmpty() || id.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_DATABASE_NOT_OPENED);
}
QMutexLocker locker(&m_mutex);
const QString key = m_browserService.getKey(id);
if (key.isEmpty() || key.compare(responseKey, Qt::CaseSensitive) != 0) {
return getErrorReply(action, ERROR_KEEPASS_ASSOCIATION_FAILED);
}
m_associated = true;
const QString newNonce = incrementNonce(nonce);
QJsonObject message = buildMessage(newNonce);
message["hash"] = hash;
message["id"] = id;
return buildResponse(action, message, newNonce);
}
QJsonObject BrowserAction::handleGetLogins(const QJsonObject& json, const QString& action)
{
const QString hash = getDatabaseHash();
const QString nonce = json.value("nonce").toString();
const QString encrypted = json.value("message").toString();
QMutexLocker locker(&m_mutex);
if (!m_associated) {
return getErrorReply(action, ERROR_KEEPASS_ASSOCIATION_FAILED);
}
const QJsonObject decrypted = decryptMessage(encrypted, nonce, action);
if (decrypted.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_CANNOT_DECRYPT_MESSAGE);
}
const QString url = decrypted.value("url").toString();
if (url.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_NO_URL_PROVIDED);
}
const QJsonArray keys = decrypted.value("keys").toArray();
StringPairList keyList;
for (const QJsonValue val : keys) {
const QJsonObject keyObject = val.toObject();
keyList.push_back(qMakePair(keyObject.value("id").toString(), keyObject.value("key").toString()));
}
const QString id = decrypted.value("id").toString();
const QString submit = decrypted.value("submitUrl").toString();
const QJsonArray users = m_browserService.findMatchingEntries(id, url, submit, "", keyList);
if (users.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_NO_LOGINS_FOUND);
}
const QString newNonce = incrementNonce(nonce);
QJsonObject message = buildMessage(newNonce);
message["count"] = users.count();
message["entries"] = users;
message["hash"] = hash;
message["id"] = id;
return buildResponse(action, message, newNonce);
}
QJsonObject BrowserAction::handleGeneratePassword(const QJsonObject& json, const QString& action)
{
const QString nonce = json.value("nonce").toString();
const QString password = browserSettings()->generatePassword();
if (nonce.isEmpty() || password.isEmpty()) {
return QJsonObject();
}
QJsonArray arr;
QJsonObject passwd;
passwd["login"] = QString::number(password.length() * 8); // bits;
passwd["password"] = password;
arr.append(passwd);
const QString newNonce = incrementNonce(nonce);
QJsonObject message = buildMessage(newNonce);
message["entries"] = arr;
return buildResponse(action, message, newNonce);
}
QJsonObject BrowserAction::handleSetLogin(const QJsonObject& json, const QString& action)
{
const QString hash = getDatabaseHash();
const QString nonce = json.value("nonce").toString();
const QString encrypted = json.value("message").toString();
QMutexLocker locker(&m_mutex);
if (!m_associated) {
return getErrorReply(action, ERROR_KEEPASS_ASSOCIATION_FAILED);
}
const QJsonObject decrypted = decryptMessage(encrypted, nonce, action);
if (decrypted.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_CANNOT_DECRYPT_MESSAGE);
}
const QString url = decrypted.value("url").toString();
if (url.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_NO_URL_PROVIDED);
}
const QString id = decrypted.value("id").toString();
const QString login = decrypted.value("login").toString();
const QString password = decrypted.value("password").toString();
const QString submitUrl = decrypted.value("submitUrl").toString();
const QString uuid = decrypted.value("uuid").toString();
const QString realm;
if (uuid.isEmpty()) {
m_browserService.addEntry(id, login, password, url, submitUrl, realm);
} else {
m_browserService.updateEntry(id, uuid, login, password, url, submitUrl);
}
const QString newNonce = incrementNonce(nonce);
QJsonObject message = buildMessage(newNonce);
message["count"] = QJsonValue::Null;
message["entries"] = QJsonValue::Null;
message["error"] = "";
message["hash"] = hash;
return buildResponse(action, message, newNonce);
}
QJsonObject BrowserAction::handleLockDatabase(const QJsonObject& json, const QString& action)
{
const QString hash = getDatabaseHash();
const QString nonce = json.value("nonce").toString();
const QString encrypted = json.value("message").toString();
const QJsonObject decrypted = decryptMessage(encrypted, nonce, action);
if (decrypted.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_CANNOT_DECRYPT_MESSAGE);
}
if (hash.isEmpty()) {
return getErrorReply(action, ERROR_KEEPASS_DATABASE_HASH_NOT_RECEIVED);
}
QString command = decrypted.value("action").toString();
if (!command.isEmpty() && command.compare("lock-database", Qt::CaseSensitive) == 0) {
QMutexLocker locker(&m_mutex);
m_browserService.lockDatabase();
const QString newNonce = incrementNonce(nonce);
QJsonObject message = buildMessage(newNonce);
return buildResponse(action, message, newNonce);
}
return getErrorReply(action, ERROR_KEEPASS_DATABASE_HASH_NOT_RECEIVED);
}
QJsonObject BrowserAction::getErrorReply(const QString& action, const int errorCode) const
{
QJsonObject response;
response["action"] = action;
response["errorCode"] = QString::number(errorCode);
response["error"] = getErrorMessage(errorCode);
return response;
}
QJsonObject BrowserAction::buildMessage(const QString& nonce) const
{
QJsonObject message;
message["version"] = KEEPASSXC_VERSION;
message["success"] = "true";
message["nonce"] = nonce;
return message;
}
QJsonObject BrowserAction::buildResponse(const QString& action, const QJsonObject& message, const QString& nonce)
{
QJsonObject response;
response["action"] = action;
response["message"] = encryptMessage(message, nonce);
response["nonce"] = nonce;
return response;
}
QString BrowserAction::getErrorMessage(const int errorCode) const
{
switch (errorCode) {
case ERROR_KEEPASS_DATABASE_NOT_OPENED:
return QObject::tr("Database not opened");
case ERROR_KEEPASS_DATABASE_HASH_NOT_RECEIVED:
return QObject::tr("Database hash not available");
case ERROR_KEEPASS_CLIENT_PUBLIC_KEY_NOT_RECEIVED:
return QObject::tr("Client public key not received");
case ERROR_KEEPASS_CANNOT_DECRYPT_MESSAGE:
return QObject::tr("Cannot decrypt message");
case ERROR_KEEPASS_TIMEOUT_OR_NOT_CONNECTED:
return QObject::tr("Timeout or cannot connect to KeePassXC");
case ERROR_KEEPASS_ACTION_CANCELLED_OR_DENIED:
return QObject::tr("Action cancelled or denied");
case ERROR_KEEPASS_CANNOT_ENCRYPT_MESSAGE:
return QObject::tr("Cannot encrypt message or public key not found. Is Native Messaging enabled in KeePassXC?");
case ERROR_KEEPASS_ASSOCIATION_FAILED:
return QObject::tr("KeePassXC association failed, try again");
case ERROR_KEEPASS_KEY_CHANGE_FAILED:
return QObject::tr("Key change was not successful");
case ERROR_KEEPASS_ENCRYPTION_KEY_UNRECOGNIZED:
return QObject::tr("Encryption key is not recognized");
case ERROR_KEEPASS_NO_SAVED_DATABASES_FOUND:
return QObject::tr("No saved databases found");
case ERROR_KEEPASS_INCORRECT_ACTION:
return QObject::tr("Incorrect action");
case ERROR_KEEPASS_EMPTY_MESSAGE_RECEIVED:
return QObject::tr("Empty message received");
case ERROR_KEEPASS_NO_URL_PROVIDED:
return QObject::tr("No URL provided");
case ERROR_KEEPASS_NO_LOGINS_FOUND:
return QObject::tr("No logins found");
default:
return QObject::tr("Unknown error");
}
}
QString BrowserAction::getDatabaseHash()
{
QMutexLocker locker(&m_mutex);
QByteArray hash =
QCryptographicHash::hash(
(m_browserService.getDatabaseRootUuid() + m_browserService.getDatabaseRecycleBinUuid()).toUtf8(),
QCryptographicHash::Sha256)
.toHex();
return QString(hash);
}
QString BrowserAction::encryptMessage(const QJsonObject& message, const QString& nonce)
{
if (message.isEmpty() || nonce.isEmpty()) {
return QString();
}
const QString reply(QJsonDocument(message).toJson());
if (!reply.isEmpty()) {
return encrypt(reply, nonce);
}
return QString();
}
QJsonObject BrowserAction::decryptMessage(const QString& message, const QString& nonce, const QString& action)
{
if (message.isEmpty() || nonce.isEmpty()) {
return QJsonObject();
}
QByteArray ba = decrypt(message, nonce);
if (!ba.isEmpty()) {
return getJsonObject(ba);
}
return getErrorReply(action, ERROR_KEEPASS_CANNOT_DECRYPT_MESSAGE);
}
QString BrowserAction::encrypt(const QString& plaintext, const QString& nonce)
{
QMutexLocker locker(&m_mutex);
const QByteArray ma = plaintext.toUtf8();
const QByteArray na = base64Decode(nonce);
const QByteArray ca = base64Decode(m_clientPublicKey);
const QByteArray sa = base64Decode(m_secretKey);
std::vector<unsigned char> m(ma.cbegin(), ma.cend());
std::vector<unsigned char> n(na.cbegin(), na.cend());
std::vector<unsigned char> ck(ca.cbegin(), ca.cend());
std::vector<unsigned char> sk(sa.cbegin(), sa.cend());
std::vector<unsigned char> e;
e.resize(NATIVE_MSG_MAX_LENGTH);
if (m.empty() || n.empty() || ck.empty() || sk.empty()) {
return QString();
}
if (crypto_box_easy(e.data(), m.data(), m.size(), n.data(), ck.data(), sk.data()) == 0) {
QByteArray res = getQByteArray(e.data(), (crypto_box_MACBYTES + ma.length()));
return res.toBase64();
}
return QString();
}
QByteArray BrowserAction::decrypt(const QString& encrypted, const QString& nonce)
{
QMutexLocker locker(&m_mutex);
const QByteArray ma = base64Decode(encrypted);
const QByteArray na = base64Decode(nonce);
const QByteArray ca = base64Decode(m_clientPublicKey);
const QByteArray sa = base64Decode(m_secretKey);
std::vector<unsigned char> m(ma.cbegin(), ma.cend());
std::vector<unsigned char> n(na.cbegin(), na.cend());
std::vector<unsigned char> ck(ca.cbegin(), ca.cend());
std::vector<unsigned char> sk(sa.cbegin(), sa.cend());
std::vector<unsigned char> d;
d.resize(NATIVE_MSG_MAX_LENGTH);
if (m.empty() || n.empty() || ck.empty() || sk.empty()) {
return QByteArray();
}
if (crypto_box_open_easy(d.data(), m.data(), ma.length(), n.data(), ck.data(), sk.data()) == 0) {
return getQByteArray(d.data(), std::char_traits<char>::length(reinterpret_cast<const char*>(d.data())));
}
return QByteArray();
}
QString BrowserAction::getBase64FromKey(const uchar* array, const uint len)
{
return getQByteArray(array, len).toBase64();
}
QByteArray BrowserAction::getQByteArray(const uchar* array, const uint len) const
{
QByteArray qba;
qba.reserve(len);
for (uint i = 0; i < len; ++i) {
qba.append(static_cast<char>(array[i]));
}
return qba;
}
QJsonObject BrowserAction::getJsonObject(const uchar* pArray, const uint len) const
{
QByteArray arr = getQByteArray(pArray, len);
QJsonParseError err;
QJsonDocument doc(QJsonDocument::fromJson(arr, &err));
return doc.object();
}
QJsonObject BrowserAction::getJsonObject(const QByteArray& ba) const
{
QJsonParseError err;
QJsonDocument doc(QJsonDocument::fromJson(ba, &err));
return doc.object();
}
QByteArray BrowserAction::base64Decode(const QString& str)
{
return QByteArray::fromBase64(str.toUtf8());
}
QString BrowserAction::incrementNonce(const QString& nonce)
{
const QByteArray nonceArray = base64Decode(nonce);
std::vector<unsigned char> n(nonceArray.cbegin(), nonceArray.cend());
sodium_increment(n.data(), n.size());
return getQByteArray(n.data(), n.size()).toBase64();
}
|