QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
rnpcrypto.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
8#include "rnpcrypto.h"
9#include "util.h"
10
11#include <QDir>
12#include <QFileInfo>
13#include <QJsonArray>
14#include <QJsonDocument>
15#include <QJsonObject>
16#include <QRegularExpression>
17#include <QTimeZone>
18#include <algorithm>
19#include <cstring>
20#include <limits>
21#include <memory>
22#include <optional>
23#include <rnp/rnp.h>
24#include <rnp/rnp_err.h>
25#include <utility>
26
27namespace {
28
30auto rnpError(const QString &what, rnp_result_t result) -> QString {
31 return QStringLiteral("%1: %2").arg(
32 what, QString::fromUtf8(rnp_result_to_string(result)));
33}
34
35auto rnpError(const char *what, rnp_result_t result) -> QString {
36 return rnpError(QString::fromUtf8(what), result);
37}
38
39void setError(QString *error, const QString &message) {
40 if (error != nullptr) {
41 *error = message;
42 }
43}
44
45struct InputDeleter {
46 void operator()(rnp_input_st *input) const { rnp_input_destroy(input); }
47};
48struct OutputDeleter {
49 void operator()(rnp_output_st *output) const { rnp_output_destroy(output); }
50};
51struct KeyDeleter {
52 void operator()(rnp_key_handle_st *key) const { rnp_key_handle_destroy(key); }
53};
54using Input = std::unique_ptr<rnp_input_st, InputDeleter>;
55using Output = std::unique_ptr<rnp_output_st, OutputDeleter>;
56using Key = std::unique_ptr<rnp_key_handle_st, KeyDeleter>;
57
59auto memoryInput(const QByteArray &data, QString *error, const char *what)
60 -> Input {
61 rnp_input_t input = nullptr;
62 const rnp_result_t result = rnp_input_from_memory(
63 &input, reinterpret_cast<const uint8_t *>(data.constData()),
64 static_cast<size_t>(data.size()), false);
65 if (result != RNP_SUCCESS) {
66 setError(error, rnpError(what, result));
67 return nullptr;
68 }
69 return Input(input);
70}
71
74auto memoryOutput(QString *error, const char *what, qint64 maxBytes = 0)
75 -> Output {
76 rnp_output_t output = nullptr;
77 const rnp_result_t result =
78 rnp_output_to_memory(&output, static_cast<size_t>(maxBytes));
79 if (result != RNP_SUCCESS) {
80 setError(error, rnpError(what, result));
81 return nullptr;
82 }
83 return Output(output);
84}
85
87auto outputBytes(rnp_output_t output) -> std::optional<QByteArray> {
88 uint8_t *buf = nullptr;
89 size_t len = 0;
90 if (rnp_output_memory_get_buf(output, &buf, &len, false) != RNP_SUCCESS) {
91 return std::nullopt;
92 }
93 return QByteArray(reinterpret_cast<const char *>(buf),
94 static_cast<qsizetype>(len));
95}
96
98auto isValidKey(rnp_key_handle_t key) -> bool {
99 bool valid = false;
100 return rnp_key_is_valid(key, &valid) == RNP_SUCCESS && valid;
101}
102
103auto allowsEncryption(rnp_key_handle_t key) -> bool {
104 bool allowed = false;
105 return rnp_key_allows_usage(key, "encrypt", &allowed) == RNP_SUCCESS &&
106 allowed;
107}
108
115auto canEncryptTo(rnp_key_handle_t key) -> bool {
116 if (!isValidKey(key)) {
117 return false;
118 }
119 if (allowsEncryption(key)) {
120 return true;
121 }
122 size_t subkeys = 0;
123 rnp_key_get_subkey_count(key, &subkeys);
124 for (size_t i = 0; i < subkeys; ++i) {
125 rnp_key_handle_t handle = nullptr;
126 if (rnp_key_get_subkey_at(key, i, &handle) != RNP_SUCCESS ||
127 handle == nullptr) {
128 continue;
129 }
130 const Key subkey(handle);
131 if (isValidKey(handle) && allowsEncryption(handle)) {
132 return true;
133 }
134 }
135 return false;
136}
137
144auto secretIsHere(rnp_key_handle_t key) -> bool {
145 bool secret = false;
146 if (rnp_key_have_secret(key, &secret) != RNP_SUCCESS || !secret) {
147 return false;
148 }
149 char *type = nullptr;
150 if (rnp_key_get_protection_type(key, &type) != RNP_SUCCESS ||
151 type == nullptr) {
152 return false;
153 }
154 const QString protection = QString::fromLatin1(type);
155 rnp_buffer_destroy(type);
156 return protection != QLatin1String("GPG-None") &&
157 protection != QLatin1String("GPG-Smartcard") &&
158 protection != QLatin1String("Unknown");
159}
160
161auto isProtected(rnp_key_handle_t key) -> bool {
162 bool locked = false;
163 return rnp_key_is_protected(key, &locked) == RNP_SUCCESS && locked;
164}
165
172template <typename Visit>
173auto forEachSecretPart(rnp_key_handle_t key, Visit visit) -> int {
174 int visited = 0;
175 if (secretIsHere(key)) {
176 ++visited;
177 if (!visit(key)) {
178 return visited;
179 }
180 }
181 size_t subkeys = 0;
182 rnp_key_get_subkey_count(key, &subkeys);
183 for (size_t i = 0; i < subkeys; ++i) {
184 rnp_key_handle_t handle = nullptr;
185 if (rnp_key_get_subkey_at(key, i, &handle) != RNP_SUCCESS ||
186 handle == nullptr) {
187 continue;
188 }
189 const Key subkey(handle);
190 if (secretIsHere(handle)) {
191 ++visited;
192 if (!visit(handle)) {
193 return visited;
194 }
195 }
196 }
197 return visited;
198}
199
205auto signingKeyOf(rnp_key_handle_t key) -> Key {
206 if (!isValidKey(key)) {
207 return nullptr;
208 }
209 rnp_key_handle_t handle = nullptr;
210 if (rnp_key_get_default_key(key, "sign", 0, &handle) != RNP_SUCCESS ||
211 handle == nullptr) {
212 return nullptr;
213 }
214 Key signer(handle);
215 if (!isValidKey(handle) || !secretIsHere(handle)) {
216 return nullptr;
217 }
218 return signer;
219}
220
222enum class Usage { Encrypt, Sign };
223
224auto usableFor(rnp_key_handle_t primary, Usage usage) -> bool {
225 return usage == Usage::Encrypt ? canEncryptTo(primary)
226 : signingKeyOf(primary) != nullptr;
227}
228
230auto primaryFingerprint(rnp_key_handle_t key) -> QString {
231 bool primary = false;
232 rnp_key_is_primary(key, &primary);
233 char *fpr = nullptr;
234 if ((primary ? rnp_key_get_fprint(key, &fpr)
235 : rnp_key_get_primary_fprint(key, &fpr)) != RNP_SUCCESS) {
236 return {};
237 }
238 QString result = QString::fromLatin1(fpr);
239 rnp_buffer_destroy(fpr);
240 return result;
241}
242
249auto liveUserIds(rnp_key_handle_t key) -> QStringList {
250 QStringList live;
251 size_t uids = 0;
252 rnp_key_get_uid_count(key, &uids);
253 for (size_t i = 0; i < uids; ++i) {
254 rnp_uid_handle_t handle = nullptr;
255 if (rnp_key_get_uid_handle_at(key, i, &handle) != RNP_SUCCESS ||
256 handle == nullptr) {
257 continue;
258 }
259 // Both: in RNP 0.17 a revoked user ID can still be "valid".
260 bool valid = false;
261 bool revoked = true;
262 const bool known = rnp_uid_is_valid(handle, &valid) == RNP_SUCCESS &&
263 rnp_uid_is_revoked(handle, &revoked) == RNP_SUCCESS;
264 rnp_uid_handle_destroy(handle);
265 char *uid = nullptr;
266 if (!known || !valid || revoked ||
267 rnp_key_get_uid_at(key, i, &uid) != RNP_SUCCESS) {
268 continue;
269 }
270 live << QString::fromUtf8(uid);
271 rnp_buffer_destroy(uid);
272 }
273 return live;
274}
275
277template <typename Hit>
278auto anyUserIdMatches(rnp_key_handle_t key, Hit hit) -> bool {
279 const QStringList uids = liveUserIds(key);
280 return std::any_of(uids.cbegin(), uids.cend(), hit);
281}
282
284auto mailboxOf(const QString &uid) -> QString {
285 const qsizetype open = uid.lastIndexOf(QLatin1Char('<'));
286 const qsizetype close = uid.lastIndexOf(QLatin1Char('>'));
287 return open >= 0 && close > open ? uid.mid(open + 1, close - open - 1)
288 : uid.trimmed();
289}
290
296template <typename Match>
297auto matchingPrimaries(rnp_ffi_t ffi, Usage usage, Match match) -> QStringList {
298 QStringList primaries;
299 rnp_identifier_iterator_t it = nullptr;
300 if (rnp_identifier_iterator_create(ffi, &it, "fingerprint") != RNP_SUCCESS) {
301 return primaries;
302 }
303 const char *fpr = nullptr;
304 while (rnp_identifier_iterator_next(it, &fpr) == RNP_SUCCESS &&
305 fpr != nullptr) {
306 rnp_key_handle_t handle = nullptr;
307 if (rnp_locate_key(ffi, "fingerprint", fpr, &handle) != RNP_SUCCESS ||
308 handle == nullptr) {
309 continue;
310 }
311 const Key key(handle);
312 if (!match(handle)) {
313 continue;
314 }
315 const QString primary = primaryFingerprint(handle);
316 rnp_key_handle_t primaryHandle = nullptr;
317 if (primary.isEmpty() || primaries.contains(primary) ||
318 rnp_locate_key(ffi, "fingerprint", primary.toLatin1().constData(),
319 &primaryHandle) != RNP_SUCCESS ||
320 primaryHandle == nullptr) {
321 continue;
322 }
323 const Key primaryKey(primaryHandle);
324 if (usableFor(primaryHandle, usage)) {
325 primaries << primary;
326 }
327 }
328 rnp_identifier_iterator_destroy(it);
329 return primaries;
330}
331
344auto locateExactKey(rnp_ffi_t ffi, const char *type, const QString &lookup,
345 const QString &recipient, QString *why, Usage usage)
346 -> Key {
347 rnp_key_handle_t handle = nullptr;
348 rnp_locate_key(ffi, type, lookup.toUpper().toLatin1().constData(), &handle);
349 if (handle == nullptr) {
350 setError(why,
351 (usage == Usage::Encrypt ? QStringLiteral("No public key for %1")
352 : QStringLiteral("No secret key for %1"))
353 .arg(recipient));
354 return nullptr;
355 }
356 Key key(handle);
357 // Named exactly, so no other key is tried; say why it cannot be used
358 // rather than leaving RNP's generic error for later.
359 const QString primary = primaryFingerprint(handle);
360 rnp_key_handle_t primaryHandle = nullptr;
361 rnp_locate_key(ffi, "fingerprint", primary.toLatin1().constData(),
362 &primaryHandle);
363 const Key primaryKey(primaryHandle);
364 if (primaryHandle == nullptr || !usableFor(primaryHandle, usage)) {
365 setError(why,
366 (usage == Usage::Encrypt
367 ? QStringLiteral("The key %1 cannot be encrypted to: it "
368 "is expired or revoked, or has no valid "
369 "encryption subkey")
370 : QStringLiteral("The key %1 cannot sign: it is expired "
371 "or revoked, has no valid signing key, "
372 "or its secret key is not here"))
373 .arg(recipient));
374 return nullptr;
375 }
376 return key;
377}
378
391auto primariesNamedBy(rnp_ffi_t ffi, const QString &id, const QString &keyId,
392 bool isHexId, Usage usage) -> QStringList {
393 if (isHexId && keyId.size() == 8) {
394 // A short key ID: the last eight digits of a key's (or subkey's) ID.
395 const QString shortId = keyId.toUpper();
396 return matchingPrimaries(ffi, usage, [&shortId](rnp_key_handle_t key) {
397 char *keyId = nullptr;
398 if (rnp_key_get_keyid(key, &keyId) != RNP_SUCCESS) {
399 return false;
400 }
401 const bool hit = QString::fromLatin1(keyId).endsWith(shortId);
402 rnp_buffer_destroy(keyId);
403 return hit;
404 });
405 }
406 static const QRegularExpression address(
407 QStringLiteral(R"(^(?:<[^\s<>@]+@[^\s<>@]+>|[^\s<>@]+@[^\s<>@]+)$)"));
408 if (address.match(id).hasMatch()) {
409 // An e-mail address (a .gpg-id often lists just that) names the key
410 // whose user ID has that address, compared without regard to case, not
411 // every user ID that contains it: as part of a name, alice@example.org
412 // would also find malice@example.org. Stricter than gpg -r, which
413 // searches for a substring.
414 QString mailbox = id;
415 mailbox.remove(QLatin1Char('<')).remove(QLatin1Char('>'));
416 return matchingPrimaries(ffi, usage, [&mailbox](rnp_key_handle_t key) {
417 return anyUserIdMatches(key, [&mailbox](const QString &uid) {
418 return mailboxOf(uid).compare(mailbox, Qt::CaseInsensitive) == 0;
419 });
420 });
421 }
422 // The whole user ID first, then part of one (gpg -r takes both). Both
423 // through matchingPrimaries, so an expired key is skipped and two keys
424 // with the same user ID (after a key rotation, say) are an error, not a
425 // pick.
426 QStringList primaries =
427 matchingPrimaries(ffi, usage, [&id](rnp_key_handle_t key) {
428 return anyUserIdMatches(
429 key, [&id](const QString &uid) { return uid == id; });
430 });
431 if (primaries.isEmpty()) {
432 primaries = matchingPrimaries(ffi, usage, [&id](rnp_key_handle_t key) {
433 return anyUserIdMatches(key, [&id](const QString &uid) {
434 return uid.contains(id, Qt::CaseInsensitive);
435 });
436 });
437 }
438 return primaries;
439}
440
448auto locateKey(rnp_ffi_t ffi, const QString &recipient, QString *why,
449 Usage usage = Usage::Encrypt) -> Key {
450 const QString id = recipient.trimmed();
451 if (id.isEmpty()) {
452 setError(why, QStringLiteral("Empty recipient"));
453 return nullptr;
454 }
455 // A key ID or fingerprint: hex digits after an optional 0x, which marks
456 // one only when hex follows (gpg reads "0xAlice" as a user ID, and so
457 // does this). Blanks (spaces or tabs) between groups are allowed in a
458 // fingerprint only, as gpg allows them: "dead beef" is a user ID.
459 static const QRegularExpression blanks(QStringLiteral("\\s+"));
460 static const QRegularExpression hex(QStringLiteral("^[0-9A-Fa-f]+$"));
461 const auto withoutPrefix = [](const QString &text) {
462 return text.startsWith(QLatin1String("0x"), Qt::CaseInsensitive) &&
463 hex.match(text.mid(2)).hasMatch()
464 ? text.mid(2)
465 : text;
466 };
467 QString fingerprint = id;
468 fingerprint.remove(blanks);
469 fingerprint = withoutPrefix(fingerprint);
470 const QString keyId = withoutPrefix(id);
471 if (keyId.compare(QLatin1String("0x"), Qt::CaseInsensitive) == 0) {
472 setError(why, QStringLiteral("Empty recipient"));
473 return nullptr;
474 }
475 const bool isHexId = hex.match(keyId).hasMatch();
476 const char *type = nullptr;
477 QString lookup;
478 // 40 digits for a v4 key, 64 for v5 and v6 (RFC 9580).
479 if (hex.match(fingerprint).hasMatch() &&
480 (fingerprint.size() == 40 || fingerprint.size() == 64)) {
481 type = "fingerprint";
482 lookup = std::move(fingerprint);
483 } else if (isHexId && keyId.size() == 16) {
484 type = "keyid";
485 lookup = keyId;
486 }
487 if (type != nullptr) {
488 return locateExactKey(ffi, type, lookup, recipient, why, usage);
489 }
490
491 const QStringList primaries =
492 primariesNamedBy(ffi, id, keyId, isHexId, usage);
493 if (primaries.size() > 1) {
494 setError(why,
495 QStringLiteral("%1 matches more than one key").arg(recipient));
496 return nullptr;
497 }
498 if (primaries.isEmpty()) {
499 setError(why, (usage == Usage::Encrypt
500 ? QStringLiteral("No usable public key for %1")
501 : QStringLiteral("No usable secret key for %1"))
502 .arg(recipient));
503 return nullptr;
504 }
505 rnp_key_handle_t key = nullptr;
506 rnp_locate_key(ffi, "fingerprint", primaries.first().toLatin1().constData(),
507 &key);
508 return Key(key);
509}
510
511// The signature is RNP's rnp_password_cb.
512auto passwordCallback(rnp_ffi_t /*ffi*/, void *appCtx, rnp_key_handle_t key,
513 const char * /*pgpContext*/,
514 char buf[], // NOLINT(modernize-avoid-c-arrays)
515 size_t bufLen) -> bool {
516 const auto *provider =
517 static_cast<const RnpCrypto::PassphraseProvider *>(appCtx);
518 if (provider == nullptr || !*provider || bufLen == 0) {
519 return false;
520 }
521 QString keyId;
522 char *rawId = nullptr;
523 if (rnp_key_get_keyid(key, &rawId) == RNP_SUCCESS) {
524 keyId = QString::fromLatin1(rawId);
525 rnp_buffer_destroy(rawId);
526 }
527 QByteArray passphrase = (*provider)(keyId).toUtf8();
528 if (passphrase.isEmpty() ||
529 static_cast<size_t>(passphrase.size()) >= bufLen) {
530 passphrase.fill('\0');
531 return false;
532 }
533 std::memcpy(buf, passphrase.constData(),
534 static_cast<size_t>(passphrase.size()));
535 buf[passphrase.size()] = '\0';
536 passphrase.fill('\0');
537 return true;
538}
539
540} // namespace
541
543 rnp_ffi_t ffi = nullptr;
544 if (rnp_ffi_create(&ffi, "GPG", "GPG") == RNP_SUCCESS) {
545 m_ffi = ffi;
546 rnp_ffi_set_pass_provider(m_ffi, passwordCallback, &m_passphrase);
547 }
548}
549
551 if (m_ffi != nullptr) {
552 rnp_ffi_destroy(m_ffi);
553 }
554}
555
556auto RnpCrypto::isValid() const -> bool { return m_ffi != nullptr; }
557
559 // RNP reads 0 as "no limit", and a negative value would wrap to a huge
560 // size_t: either would switch the guard off without a word. RNP 0.17 and
561 // 0.18 also keep the limit in 32 bits, so 4 GiB would become 0 (no limit)
562 // and 4 GiB + 5 become 5: anything wider is capped to what fits.
563 if (bytes > 0) {
565 std::min<qint64>(bytes, std::numeric_limits<quint32>::max());
566 }
567}
568
570 m_passphrase = std::move(provider);
571}
572
573auto RnpCrypto::importKeys(const QByteArray &keyData, QString *error)
574 -> QStringList {
575 if (m_ffi == nullptr) {
576 setError(error, QStringLiteral("RNP is not available"));
577 return {};
578 }
579 Input input = memoryInput(keyData, error, "Cannot read the key data");
580 if (!input) {
581 return {};
582 }
583 char *json = nullptr;
584 const rnp_result_t result = rnp_import_keys(
585 m_ffi, input.get(), RNP_LOAD_SAVE_PUBLIC_KEYS | RNP_LOAD_SAVE_SECRET_KEYS,
586 &json);
587 if (result != RNP_SUCCESS) {
588 setError(error, rnpError("Cannot import the keys", result));
589 return {};
590 }
591 QJsonParseError parseError{};
592 const QJsonDocument doc = QJsonDocument::fromJson(json, &parseError);
593 rnp_buffer_destroy(json);
594 const QJsonValue keysValue = doc.object().value(QStringLiteral("keys"));
595 if (parseError.error != QJsonParseError::NoError || !keysValue.isArray()) {
596 // The keys may well be in the keyring; only which ones is unknown.
597 setError(error, QStringLiteral("Cannot read RNP's import report: %1")
598 .arg(parseError.error != QJsonParseError::NoError
599 ? parseError.errorString()
600 : QStringLiteral("no key list")));
601 return {};
602 }
603 QStringList primaries;
604 const QJsonArray keys = keysValue.toArray();
605 for (const auto &entry : keys) {
606 const QString fpr =
607 entry.toObject().value(QStringLiteral("fingerprint")).toString();
608 rnp_key_handle_t key = nullptr;
609 if (rnp_locate_key(m_ffi, "fingerprint", fpr.toLatin1().constData(),
610 &key) != RNP_SUCCESS ||
611 key == nullptr) {
612 continue;
613 }
614 bool primary = false;
615 rnp_key_is_primary(key, &primary);
616 rnp_key_handle_destroy(key);
617 if (primary && !primaries.contains(fpr)) {
618 primaries << fpr;
619 }
620 }
621 return primaries;
622}
623
624auto RnpCrypto::encrypt(const QByteArray &plaintext,
625 const QStringList &recipients, QString *error)
626 -> QByteArray {
627 if (m_ffi == nullptr) {
628 setError(error, QStringLiteral("RNP is not available"));
629 return {};
630 }
631 if (recipients.isEmpty()) {
632 setError(error, QStringLiteral("No recipients"));
633 return {};
634 }
635 Input input = memoryInput(plaintext, error, "Cannot read the entry");
636 Output output = memoryOutput(error, "Cannot encrypt");
637 if (!input || !output) {
638 return {};
639 }
640 rnp_op_encrypt_t op = nullptr;
641 rnp_result_t result =
642 rnp_op_encrypt_create(&op, m_ffi, input.get(), output.get());
643 if (result != RNP_SUCCESS) {
644 setError(error, rnpError("Cannot encrypt", result));
645 return {};
646 }
647 const std::unique_ptr<rnp_op_encrypt_st, rnp_result_t (*)(rnp_op_encrypt_t)>
648 guard(op, rnp_op_encrypt_destroy);
649 for (const QString &recipient : recipients) {
650 QString why;
651 const Key key = locateKey(m_ffi, recipient, &why);
652 if (!key) {
653 setError(error, why);
654 return {};
655 }
656 result = rnp_op_encrypt_add_recipient(op, key.get());
657 if (result != RNP_SUCCESS) {
658 setError(error,
659 rnpError(QStringLiteral("Cannot encrypt to %1").arg(recipient),
660 result));
661 return {};
662 }
663 }
664 rnp_op_encrypt_set_armor(op, false);
665 result = rnp_op_encrypt_execute(op);
666 if (result != RNP_SUCCESS) {
667 setError(error, rnpError("Cannot encrypt", result));
668 return {};
669 }
670 std::optional<QByteArray> cipher = outputBytes(output.get());
671 if (!cipher) {
672 setError(error, QStringLiteral("Cannot encrypt: no output from RNP"));
673 return {};
674 }
675 return *cipher;
676}
677
678auto RnpCrypto::decrypt(const QByteArray &ciphertext, QString *error, bool *ok)
679 -> QByteArray {
680 if (ok != nullptr) {
681 *ok = false;
682 }
683 if (m_ffi == nullptr) {
684 setError(error, QStringLiteral("RNP is not available"));
685 return {};
686 }
687 Input input = memoryInput(ciphertext, error, "Cannot read the entry");
688 Output output = memoryOutput(error, "Cannot decrypt", m_maxPlaintext);
689 if (!input || !output) {
690 return {};
691 }
692 // Through a verify operation rather than rnp_decrypt(): only that reports
693 // how the message was protected, and rnp_decrypt() returns success for
694 // CFB without MDC, the kind EFAIL abuses.
695 rnp_op_verify_t op = nullptr;
696 rnp_result_t result =
697 rnp_op_verify_create(&op, m_ffi, input.get(), output.get());
698 if (result != RNP_SUCCESS) {
699 setError(error, rnpError("Cannot decrypt", result));
700 return {};
701 }
702 const std::unique_ptr<rnp_op_verify_st, rnp_result_t (*)(rnp_op_verify_t)>
703 guard(op, rnp_op_verify_destroy);
704 // A signature by a key not in this keyring does not make an entry
705 // unreadable; pass does not check signatures on entries either.
706 rnp_op_verify_set_flags(op, RNP_VERIFY_IGNORE_SIGS_ON_DECRYPT);
707 result = rnp_op_verify_execute(op);
708 if (result != RNP_SUCCESS) {
709 setError(error, rnpError("Cannot decrypt", result));
710 return {};
711 }
712 char *mode = nullptr;
713 bool protectedOk = false;
714 if (rnp_op_verify_get_protection_info(op, &mode, nullptr, &protectedOk) !=
715 RNP_SUCCESS ||
716 !protectedOk) {
717 setError(error,
718 QStringLiteral("Refusing a message without integrity "
719 "protection (%1)")
720 .arg(QString::fromLatin1(mode != nullptr ? mode : "unknown")));
721 rnp_buffer_destroy(mode);
722 return {};
723 }
724 rnp_buffer_destroy(mode);
725 std::optional<QByteArray> plain = outputBytes(output.get());
726 if (!plain) {
727 setError(error, QStringLiteral("Cannot decrypt: no output from RNP"));
728 return {};
729 }
730 if (ok != nullptr) {
731 *ok = true;
732 }
733 return *plain;
734}
735
736namespace {
737
739auto fingerprintOf(rnp_key_handle_t key) -> QString {
740 char *fpr = nullptr;
741 if (rnp_key_get_fprint(key, &fpr) != RNP_SUCCESS) {
742 return {};
743 }
744 QString result = QString::fromLatin1(fpr);
745 rnp_buffer_destroy(fpr);
746 return result;
747}
748
749auto isRevoked(rnp_key_handle_t key) -> bool {
750 bool revoked = false;
751 return rnp_key_is_revoked(key, &revoked) == RNP_SUCCESS && revoked;
752}
753
760auto firstSecretOfUnknownProtection(rnp_ffi_t ffi) -> std::optional<QString> {
761 QString found;
762 rnp_identifier_iterator_t it = nullptr;
763 if (rnp_identifier_iterator_create(ffi, &it, "fingerprint") != RNP_SUCCESS) {
764 return std::nullopt;
765 }
766 bool failed = false;
767 const char *fpr = nullptr;
768 while (found.isEmpty() && !failed) {
769 if (rnp_identifier_iterator_next(it, &fpr) != RNP_SUCCESS) {
770 failed = true;
771 break;
772 }
773 if (fpr == nullptr) {
774 break; // the end
775 }
776 rnp_key_handle_t handle = nullptr;
777 if (rnp_locate_key(ffi, "fingerprint", fpr, &handle) != RNP_SUCCESS ||
778 handle == nullptr) {
779 failed = true;
780 break;
781 }
782 const Key key(handle);
783 bool secret = false;
784 if (rnp_key_have_secret(handle, &secret) != RNP_SUCCESS) {
785 failed = true;
786 break;
787 }
788 if (!secret) {
789 continue;
790 }
791 char *type = nullptr;
792 if (rnp_key_get_protection_type(handle, &type) != RNP_SUCCESS ||
793 type == nullptr) {
794 failed = true;
795 break;
796 }
797 if (QString::fromLatin1(type) == QLatin1String("Unknown")) {
798 found = QString::fromLatin1(fpr);
799 }
800 rnp_buffer_destroy(type);
801 }
802 rnp_identifier_iterator_destroy(it);
803 if (failed) {
804 return std::nullopt;
805 }
806 return found;
807}
808
810auto primaryOf(rnp_ffi_t ffi, rnp_key_handle_t key) -> Key {
811 const QString primary = primaryFingerprint(key);
812 rnp_key_handle_t handle = nullptr;
813 if (primary.isEmpty() ||
814 rnp_locate_key(ffi, "fingerprint", primary.toLatin1().constData(),
815 &handle) != RNP_SUCCESS) {
816 return nullptr;
817 }
818 return Key(handle);
819}
820
827auto keyInfoOf(rnp_key_handle_t handle) -> RnpCrypto::KeyInfo {
829 info.fingerprint = fingerprintOf(handle);
830 char *keyId = nullptr;
831 if (rnp_key_get_keyid(handle, &keyId) == RNP_SUCCESS) {
832 info.keyId = QString::fromLatin1(keyId);
833 rnp_buffer_destroy(keyId);
834 }
835 info.userIds = liveUserIds(handle);
836 uint32_t created = 0;
837 if (rnp_key_get_creation(handle, &created) == RNP_SUCCESS) {
838 info.created = QDateTime::fromSecsSinceEpoch(created, QTimeZone::UTC);
839 }
840 uint32_t lifetime = 0;
841 if (rnp_key_get_expiration(handle, &lifetime) == RNP_SUCCESS &&
842 lifetime > 0) {
843 info.expires = info.created.addSecs(lifetime);
844 }
845 info.revoked = isRevoked(handle);
846 bool expired = false;
847 info.expired = rnp_key_is_expired(handle, &expired) == RNP_SUCCESS && expired;
848 // A secret part may be a subkey's only (gpg --export-secret-subkeys).
849 info.hasSecret = forEachSecretPart(handle, [&info](rnp_key_handle_t part) {
850 info.secretProtected =
851 info.secretProtected && isProtected(part);
852 return true;
853 }) > 0;
854 info.canEncrypt = canEncryptTo(handle);
855 info.canSign = signingKeyOf(handle) != nullptr;
856 return info;
857}
858
859} // namespace
860
861auto RnpCrypto::listKeys(bool secretOnly) const -> QList<KeyInfo> {
862 QList<KeyInfo> keys;
863 if (m_ffi == nullptr) {
864 return keys;
865 }
866 rnp_identifier_iterator_t it = nullptr;
867 if (rnp_identifier_iterator_create(m_ffi, &it, "fingerprint") !=
868 RNP_SUCCESS) {
869 return keys;
870 }
871 const char *fpr = nullptr;
872 while (rnp_identifier_iterator_next(it, &fpr) == RNP_SUCCESS &&
873 fpr != nullptr) {
874 rnp_key_handle_t handle = nullptr;
875 if (rnp_locate_key(m_ffi, "fingerprint", fpr, &handle) != RNP_SUCCESS ||
876 handle == nullptr) {
877 continue;
878 }
879 const Key key(handle);
880 bool primary = false;
881 if (rnp_key_is_primary(handle, &primary) != RNP_SUCCESS || !primary) {
882 continue;
883 }
884 const KeyInfo info = keyInfoOf(handle);
885 if (!secretOnly || info.hasSecret) {
886 keys << info;
887 }
888 }
889 rnp_identifier_iterator_destroy(it);
890 return keys;
891}
892
893auto RnpCrypto::sign(const QByteArray &data, const QString &signer,
894 QString *error) -> QByteArray {
895 if (m_ffi == nullptr) {
896 setError(error, QStringLiteral("RNP is not available"));
897 return {};
898 }
899 // As gpg --local-user: exactly the key named, never another one that
900 // happens to have a secret key here.
901 QString why;
902 const Key named = locateKey(m_ffi, signer, &why, Usage::Sign);
903 if (!named) {
904 setError(error, why);
905 return {};
906 }
907 const Key primary = primaryOf(m_ffi, named.get());
908 const Key signing = primary ? signingKeyOf(primary.get()) : nullptr;
909 if (!signing) {
910 setError(error, QStringLiteral("The key %1 cannot sign").arg(signer));
911 return {};
912 }
913 Input input = memoryInput(data, error, "Cannot read the data to sign");
914 Output output = memoryOutput(error, "Cannot sign");
915 if (!input || !output) {
916 return {};
917 }
918 rnp_op_sign_t op = nullptr;
919 rnp_result_t result =
920 rnp_op_sign_detached_create(&op, m_ffi, input.get(), output.get());
921 if (result != RNP_SUCCESS) {
922 setError(error, rnpError("Cannot sign", result));
923 return {};
924 }
925 const std::unique_ptr<rnp_op_sign_st, rnp_result_t (*)(rnp_op_sign_t)> guard(
926 op, rnp_op_sign_destroy);
927 rnp_op_sign_set_armor(op, false);
928 result = rnp_op_sign_add_signature(op, signing.get(), nullptr);
929 if (result == RNP_SUCCESS) {
930 // Unlocks the secret key through the passphrase provider.
931 result = rnp_op_sign_execute(op);
932 }
933 if (result != RNP_SUCCESS) {
934 setError(error, rnpError("Cannot sign", result));
935 return {};
936 }
937 std::optional<QByteArray> signature = outputBytes(output.get());
938 if (!signature || signature->isEmpty()) {
939 setError(error, QStringLiteral("Cannot sign: no output from RNP"));
940 return {};
941 }
942 return *signature;
943}
944
945auto RnpCrypto::verify(const QByteArray &data, const QByteArray &signature,
946 QString *error) -> QStringList {
947 if (m_ffi == nullptr) {
948 setError(error, QStringLiteral("RNP is not available"));
949 return {};
950 }
951 Input input = memoryInput(data, error, "Cannot read the signed data");
952 Input sigInput = memoryInput(signature, error, "Cannot read the signature");
953 if (!input || !sigInput) {
954 return {};
955 }
956 rnp_op_verify_t op = nullptr;
957 rnp_result_t result =
958 rnp_op_verify_detached_create(&op, m_ffi, input.get(), sigInput.get());
959 if (result != RNP_SUCCESS) {
960 setError(error, rnpError("Cannot verify", result));
961 return {};
962 }
963 const std::unique_ptr<rnp_op_verify_st, rnp_result_t (*)(rnp_op_verify_t)>
964 guard(op, rnp_op_verify_destroy);
965 // Fails when no signature verifies; each one's own status says why.
966 result = rnp_op_verify_execute(op);
967 size_t count = 0;
968 rnp_op_verify_get_signature_count(op, &count);
969 for (size_t i = 0; i < count; ++i) {
970 rnp_op_verify_signature_t sig = nullptr;
971 if (rnp_op_verify_get_signature_at(op, i, &sig) != RNP_SUCCESS ||
972 rnp_op_verify_signature_get_status(sig) != RNP_SUCCESS) {
973 continue;
974 }
975 rnp_key_handle_t handle = nullptr;
976 if (rnp_op_verify_signature_get_key(sig, &handle) != RNP_SUCCESS ||
977 handle == nullptr) {
978 continue;
979 }
980 const Key key(handle);
981 const Key primary = primaryOf(m_ffi, handle);
982 // The first good signature decides, as the first VALIDSIG does in
983 // GpgIdSigner: by a revoked key (a leaked one, say) it counts for
984 // nothing. RNP 0.17 and 0.18 already give such a signature a failed
985 // status; checked here too, so that holds whatever RNP decides.
986 if (isRevoked(handle) || !primary || isRevoked(primary.get())) {
987 setError(error, QStringLiteral("The signature is by a revoked key (%1)")
988 .arg(primaryFingerprint(handle)));
989 return {};
990 }
991 return {fingerprintOf(handle), fingerprintOf(primary.get())};
992 }
993 setError(error, result != RNP_SUCCESS ? rnpError("No valid signature", result)
994 : QStringLiteral("No valid signature"));
995 return {};
996}
997
998auto RnpCrypto::protectKey(const QString &fingerprint,
999 const QString &passphrase, QString *error) -> bool {
1000 if (m_ffi == nullptr) {
1001 setError(error, QStringLiteral("RNP is not available"));
1002 return false;
1003 }
1004 if (passphrase.isEmpty()) {
1005 setError(error, QStringLiteral("An empty passphrase protects nothing"));
1006 return false;
1007 }
1008 rnp_key_handle_t handle = nullptr;
1009 rnp_locate_key(m_ffi, "fingerprint",
1010 fingerprint.toUpper().toLatin1().constData(), &handle);
1011 const Key key(handle);
1012 // Every part that is still unprotected gets the passphrase; the ones that
1013 // are protected keep theirs. So a key left half protected (an imported
1014 // one, or a run that failed part-way) can be finished, rather than only
1015 // saved with consent, unprotected parts and all.
1016 int unprotected = 0;
1017 const int parts =
1018 handle == nullptr
1019 ? 0
1020 : forEachSecretPart(handle, [&unprotected](rnp_key_handle_t part) {
1021 unprotected += isProtected(part) ? 0 : 1;
1022 return true;
1023 });
1024 if (parts == 0) {
1025 setError(error, QStringLiteral("No secret key for %1").arg(fingerprint));
1026 return false;
1027 }
1028 if (unprotected == 0) {
1029 setError(error,
1030 QStringLiteral("The secret key %1 is protected already; its "
1031 "passphrase is not changed here")
1032 .arg(fingerprint));
1033 return false;
1034 }
1035 QByteArray secret = passphrase.toUtf8();
1036 bool ok = true;
1037 forEachSecretPart(handle, [&](rnp_key_handle_t part) {
1038 if (isProtected(part)) {
1039 return true;
1040 }
1041 // RNP's defaults: AES-256 and a SHA-256 S2K with its iteration count.
1042 const rnp_result_t result =
1043 rnp_key_protect(part, secret.constData(), nullptr, nullptr, nullptr, 0);
1044 if (result != RNP_SUCCESS) {
1045 setError(
1046 error,
1047 rnpError(QStringLiteral("Cannot protect %1").arg(fingerprintOf(part)),
1048 result));
1049 ok = false;
1050 }
1051 return ok;
1052 });
1053 secret.fill('\0');
1054 return ok;
1055}
1056
1057auto RnpCrypto::everySecretIsProtected(QString *error) const -> bool {
1058 for (const KeyInfo &key : listKeys(true)) {
1059 if (!key.secretProtected) {
1060 setError(error, QStringLiteral("The secret key %1 is not protected "
1061 "by a passphrase")
1062 .arg(key.fingerprint));
1063 return false;
1064 }
1065 }
1066 // A secret part whose protection RNP cannot name is not counted as
1067 // here (secretIsHere()), yet it would be written: what is in it is not
1068 // known, so it is refused like an unprotected one.
1069 const std::optional<QString> unknown = firstSecretOfUnknownProtection(m_ffi);
1070 if (!unknown) {
1071 setError(error, QStringLiteral("Cannot tell how every secret key is "
1072 "protected; nothing is written"));
1073 return false;
1074 }
1075 if (!unknown->isEmpty()) {
1076 setError(error, QStringLiteral("The secret key %1 has a protection RNP "
1077 "cannot name")
1078 .arg(*unknown));
1079 return false;
1080 }
1081 return true;
1082}
1083
1084auto RnpCrypto::saveKeyring(const QString &dir, bool allowUnprotected,
1085 QString *error) const -> bool {
1086 if (m_ffi == nullptr) {
1087 setError(error, QStringLiteral("RNP is not available"));
1088 return false;
1089 }
1090 // QtPass's own folder, not wherever a link would lead: cleaned first, so
1091 // "dir/" or "dir/." is not judged by its target, and a junction counts.
1092 if (Util::isLinkedFolder(dir)) {
1093 setError(error,
1094 QStringLiteral("%1 is a link, not a keyring folder").arg(dir));
1095 return false;
1096 }
1097 // Checked before anything is written: a secret key goes to disk only
1098 // protected by its own passphrase, unless the user said otherwise.
1099 if (!allowUnprotected && !everySecretIsProtected(error)) {
1100 return false;
1101 }
1102 // One file with public and secret keys, replaced whole: two files could
1103 // not be swapped together, and a save failing between them would leave a
1104 // new public ring next to an old secret one, which the next load would
1105 // combine (a secret key removed since back in). RNP refuses to save an
1106 // empty set; an empty file says the same.
1107 std::optional<QByteArray> ring = QByteArray();
1108 if (!listKeys().isEmpty()) {
1109 Output output = memoryOutput(error, "Cannot save the keyring");
1110 if (!output) {
1111 return false;
1112 }
1113 const rnp_result_t result =
1114 rnp_save_keys(m_ffi, "GPG", output.get(),
1115 RNP_LOAD_SAVE_PUBLIC_KEYS | RNP_LOAD_SAVE_SECRET_KEYS);
1116 if (result != RNP_SUCCESS) {
1117 setError(error, rnpError("Cannot save the keyring", result));
1118 return false;
1119 }
1120 ring = outputBytes(output.get());
1121 if (!ring) {
1122 setError(error, QStringLiteral("Cannot save the keyring: no output"));
1123 return false;
1124 }
1125 }
1126 // What loadKeyring() would not read back is not written.
1127 if (ring->size() > kMaxKeyringBytes) {
1128 setError(error, QStringLiteral("The keyring is larger than %1 bytes")
1129 .arg(kMaxKeyringBytes));
1130 return false;
1131 }
1132 // QtPass's own folder, owner-only whatever the umask, also when it
1133 // existed already.
1134 if (!QDir().mkpath(dir) ||
1135 !QFile::setPermissions(dir, QFile::ReadOwner | QFile::WriteOwner |
1136 QFile::ExeOwner)) {
1137 setError(error, QStringLiteral("Cannot create %1").arg(dir));
1138 return false;
1139 }
1140 // Staged and replaced whole (owner-only), as an entry is written: a
1141 // reader sees the old keyring or the new one, never a mix.
1142 QString why;
1144 QDir(dir).filePath(QStringLiteral("keyring.gpg")), *ring, true,
1145 &why)) {
1146 setError(error, QStringLiteral("Cannot write the keyring: %1").arg(why));
1147 return false;
1148 }
1149 return true;
1150}
1151
1152auto RnpCrypto::loadKeyring(const QString &dir, QString *error) -> bool {
1153 if (m_ffi == nullptr) {
1154 setError(error, QStringLiteral("RNP is not available"));
1155 return false;
1156 }
1157 // As saveKeyring(): the folder itself is not read through a link either.
1158 if (Util::isLinkedFolder(dir)) {
1159 setError(error,
1160 QStringLiteral("%1 is a link, not a keyring folder").arg(dir));
1161 return false;
1162 }
1163 const QString path = QDir(dir).filePath(QStringLiteral("keyring.gpg"));
1164 const QFileInfo info(path);
1165 if (!info.exists() && !info.isSymLink()) {
1166 return true; // no keyring yet
1167 }
1168 const std::optional<QByteArray> bytes =
1170 if (!bytes) {
1171 setError(error, QStringLiteral("Cannot read %1 as a keyring (a regular "
1172 "file of at most %2 bytes)")
1173 .arg(path)
1174 .arg(kMaxKeyringBytes));
1175 return false;
1176 }
1177 if (bytes->isEmpty()) {
1178 return true; // saved without keys
1179 }
1180 Input input = memoryInput(*bytes, error, "Cannot read the keyring");
1181 if (!input) {
1182 return false;
1183 }
1184 const rnp_result_t result =
1185 rnp_load_keys(m_ffi, "GPG", input.get(),
1186 RNP_LOAD_SAVE_PUBLIC_KEYS | RNP_LOAD_SAVE_SECRET_KEYS);
1187 if (result != RNP_SUCCESS) {
1188 setError(error,
1189 rnpError(QStringLiteral("Cannot load %1").arg(path), result));
1190 return false;
1191 }
1192 return true;
1193}
static constexpr qint64 kMaxKeyringBytes
Most bytes of a keyring file: saveKeyring() writes no larger one, loadKeyring() reads no larger one.
Definition rnpcrypto.h:104
auto sign(const QByteArray &data, const QString &signer, QString *error=nullptr) -> QByteArray
Makes a detached signature over data, as gpg –detach-sign –local-user signer does (for ....
void setPassphraseProvider(PassphraseProvider provider)
Sets how secret-key passphrases are obtained.
std::function< QString(const QString &keyId)> PassphraseProvider
Asks for the passphrase of a secret key.
Definition rnpcrypto.h:86
RnpCrypto()
Creates an empty keyring.
auto importKeys(const QByteArray &keyData, QString *error=nullptr) -> QStringList
Imports public and secret keys from armored or binary key data.
qint64 m_maxPlaintext
Largest plaintext decrypt() returns, in bytes.
Definition rnpcrypto.h:307
auto verify(const QByteArray &data, const QByteArray &signature, QString *error=nullptr) -> QStringList
Checks a detached signature over data, as QtPass reads gpg's VALIDSIG.
void setMaxPlaintextBytes(qint64 bytes)
Sets the most bytes of plaintext decrypt() may produce.
~RnpCrypto()
Frees the keyring and everything RNP holds for it.
rnp_ffi_st * m_ffi
RNP's handle holding this object's keyring; null when RNP could not be initialised,...
Definition rnpcrypto.h:300
auto protectKey(const QString &fingerprint, const QString &passphrase, QString *error=nullptr) -> bool
Protects the secret parts of a key with passphrase.
auto decrypt(const QByteArray &ciphertext, QString *error=nullptr, bool *ok=nullptr) -> QByteArray
Decrypts an OpenPGP message with any secret key in the keyring.
auto listKeys(bool secretOnly=false) const -> QList< KeyInfo >
The primary keys in the keyring.
auto isValid() const -> bool
Whether the RNP context could be created at all.
auto loadKeyring(const QString &dir, QString *error=nullptr) -> bool
Adds the keyring in dir (as saveKeyring() wrote it) to this one. Secret keys stay protected until an ...
auto encrypt(const QByteArray &plaintext, const QStringList &recipients, QString *error=nullptr) -> QByteArray
Encrypts plaintext to every recipient, as one message.
PassphraseProvider m_passphrase
Asked for the passphrase of a locked secret key during decryption; set with setPassphraseProvider(),...
Definition rnpcrypto.h:305
auto saveKeyring(const QString &dir, bool allowUnprotected=false, QString *error=nullptr) const -> bool
Writes the keyring to dir: keyring.gpg, public and secret keys in one file (OpenPGP keys,...
auto everySecretIsProtected(QString *error) const -> bool
Whether saveKeyring() may write the secret keys without the user's consent: each is protected by a pa...
static auto writeFileReplacing(const QString &path, const QByteArray &bytes, bool replace, QString *error=nullptr) -> bool
Write bytes as the file path through stageFileReplacing().
Definition util.cpp:1911
static auto readRegularFile(const QString &path, qint64 maxBytes) -> std::optional< QByteArray >
Read path whole, as the regular file it is (openRegularFile()), when it holds at most maxBytes.
Definition util.cpp:1555
static auto isLinkedFolder(const QString &path) -> bool
Whether path names a symbolic link or NTFS junction, with or without a trailing separator (which woul...
Definition util.cpp:1213
RnpCrypto, in-process OpenPGP encryption and decryption through the RNP library.
One primary key in the keyring, as the Users dialog lists keys.
Definition rnpcrypto.h:46
QStringList userIds
Its user IDs that are still its own (valid, not revoked), in the keyring's order.
Definition rnpcrypto.h:55
QDateTime expires
When it expires; invalid when it does not.
Definition rnpcrypto.h:59
bool canSign
Whether it can sign now, with a secret key that is here.
Definition rnpcrypto.h:77
bool canEncrypt
Whether a message can be encrypted to it now.
Definition rnpcrypto.h:75
bool secretProtected
Whether every secret part of it that is here is protected by a passphrase; true when none is here.
Definition rnpcrypto.h:73
bool expired
Whether it has expired.
Definition rnpcrypto.h:63
QString fingerprint
The primary key's fingerprint, upper-case hex.
Definition rnpcrypto.h:48
QString keyId
The primary key's 16-hex-digit key ID.
Definition rnpcrypto.h:50
QDateTime created
When it was created.
Definition rnpcrypto.h:57
bool hasSecret
Whether a secret part of it (primary or subkey) is here to use: a GnuPG stub (a key left at home,...
Definition rnpcrypto.h:68
bool revoked
Whether it has been revoked.
Definition rnpcrypto.h:61
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...