QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
gpgidgeneration.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 "gpgidgeneration.h"
9#include "qtpasslogging.h"
10#include <QCoreApplication>
11#include <QCryptographicHash>
12#include <QDir>
13#include <QFile>
14#include <QFileInfo>
15#include <QJsonDocument>
16#include <QJsonObject>
17#include <QLockFile>
18#include <QMap>
19#include <QMutex>
20#include <QMutexLocker>
21#include <QSaveFile>
22#include <QSettings>
23#include <QStringDecoder>
24#include <QUuid>
25#include <algorithm>
26#include <utility>
27
29 QByteArrayLiteral("# QtPass-GpgId-Generation: ");
30const QByteArray GpgIdGeneration::kFolderPrefix =
31 QByteArrayLiteral("# QtPass-GpgId-Folder: ");
32const QByteArray GpgIdGeneration::kStorePrefix =
33 QByteArrayLiteral("# QtPass-GpgId-Store: ");
34const qint64 GpgIdGeneration::kMaxGeneration = 999999999999999999LL;
35
36namespace {
37constexpr int kMaxDigits = 18;
38constexpr QByteArrayView kOurComment("# QtPass-GpgId-");
39
40// Not a QObject: messages live under the class name. lupdate gets that context
41// from the class's own methods, but drops strings in the free functions and
42// structs here, so those spell it out with QCoreApplication::translate().
43auto tr(const char *text) -> QString {
44 return QCoreApplication::translate("GpgIdGeneration", text);
45}
46
50QMutex &recordLock() {
51 static QMutex mutex;
52 return mutex;
53}
54
56constexpr int kRecordLockTimeoutMs = 3000;
57
60struct Entry {
61 qint64 generation = 0;
62 QString digest;
63};
64using Entries = QMap<QString, Entry>;
67using Stores = QMap<QString, QString>;
68
70struct Record {
71 Entries lists;
72 Stores stores;
73};
74
76auto isStoreId(const QByteArray &id) -> bool {
77 return id.size() == 32 && std::all_of(id.cbegin(), id.cend(), [](char c) {
78 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
79 });
80}
81
82constexpr QLatin1StringView kRecordName("QtPass-gpgid-generations.json");
86constexpr QLatin1StringView kStoresName("QtPass-gpgid-stores.json");
87constexpr int kRecordFormat = 1;
88
93auto recordPath() -> QString {
94 const QSettings probe(QSettings::IniFormat, QSettings::UserScope,
95 QCoreApplication::organizationName().isEmpty()
96 ? QStringLiteral("IJHack")
97 : QCoreApplication::organizationName(),
98 QStringLiteral("QtPass-gpgid-generations"));
99 return QFileInfo(probe.fileName()).absolutePath() + QLatin1Char('/') +
100 kRecordName;
101}
102
104auto storesPath() -> QString {
105 return QFileInfo(recordPath()).absolutePath() + QLatin1Char('/') +
106 kStoresName;
107}
108
112auto recordEntry(const QJsonValue &value) -> std::optional<Entry> {
113 if (!value.isObject()) {
114 return std::nullopt;
115 }
116 const QJsonObject item = value.toObject();
117 const QString generation = item.value(QLatin1String("generation")).toString();
118 if (generation.isEmpty() || generation.size() > kMaxDigits) {
119 return std::nullopt;
120 }
121 for (const QChar c : generation) {
122 if (c < QLatin1Char('0') || c > QLatin1Char('9')) {
123 return std::nullopt;
124 }
125 }
126 Entry entry;
127 entry.generation = generation.toLongLong();
128 entry.digest = item.value(QLatin1String("sha256")).toString();
129 return entry;
130}
131
134auto recordObject(const QByteArray &bytes, const QString &name)
135 -> std::optional<QJsonObject> {
136 QJsonParseError parse{};
137 const QJsonDocument doc = QJsonDocument::fromJson(bytes, &parse);
138 if (parse.error != QJsonParseError::NoError || !doc.isObject()) {
139 return std::nullopt;
140 }
141 const QJsonObject root = doc.object();
142 const QJsonValue inner = root.value(name);
143 if (root.value(QLatin1String("format")).toInt() != kRecordFormat ||
144 !inner.isObject()) {
145 return std::nullopt;
146 }
147 return inner.toObject();
148}
149
152auto parseRecord(const QByteArray &bytes) -> std::optional<Entries> {
153 const std::optional<QJsonObject> byKey =
154 recordObject(bytes, QStringLiteral("lists"));
155 if (!byKey) {
156 return std::nullopt;
157 }
158 Entries entries;
159 for (auto it = byKey->constBegin(); it != byKey->constEnd(); ++it) {
160 const std::optional<Entry> entry = recordEntry(it.value());
161 if (!entry) {
162 return std::nullopt;
163 }
164 entries.insert(it.key(), *entry);
165 }
166 return entries;
167}
168
171auto parseStores(const QByteArray &bytes) -> std::optional<Stores> {
172 const std::optional<QJsonObject> byKey =
173 recordObject(bytes, QStringLiteral("stores"));
174 if (!byKey) {
175 return std::nullopt;
176 }
177 Stores stores;
178 for (auto it = byKey->constBegin(); it != byKey->constEnd(); ++it) {
179 const QString id =
180 it.value().toObject().value(QLatin1String("id")).toString();
181 if (!it.value().isObject() || !isStoreId(id.toLatin1())) {
182 return std::nullopt;
183 }
184 stores.insert(it.key(), id);
185 }
186 return stores;
187}
188
192template <typename T, typename Parse>
193auto loadFile(const QString &path, Parse parse, QString *error)
194 -> std::optional<T> {
195 if (!QFileInfo::exists(path)) {
196 return T{};
197 }
198 QFile file(path);
199 if (!file.open(QIODevice::ReadOnly)) {
200 if (error)
201 *error = QCoreApplication::translate(
202 "GpgIdGeneration",
203 "The generation record of the recipient lists, %1, cannot "
204 "be accessed.")
205 .arg(path);
206 return std::nullopt;
207 }
208 std::optional<T> value = parse(file.readAll());
209 if (!value && error) {
210 *error = QCoreApplication::translate(
211 "GpgIdGeneration",
212 "The generation record of the recipient lists, %1, is not "
213 "readable. Signed recipient lists are not accepted until "
214 "it is repaired or removed (which forgets what was accepted "
215 "before).")
216 .arg(path);
217 }
218 return value;
219}
220
224auto saveFile(const QString &path, const QString &name,
225 const QJsonObject &inner, QString *error) -> bool {
226 QJsonObject root;
227 root.insert(QLatin1String("format"), kRecordFormat);
228 root.insert(name, inner);
229 QSaveFile file(path);
230 if (!file.open(QIODevice::WriteOnly)) {
231 if (error)
232 *error = QCoreApplication::translate(
233 "GpgIdGeneration",
234 "The generation record of the recipient lists, %1, cannot "
235 "be written.")
236 .arg(path);
237 return false;
238 }
239 file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
240 const QByteArray bytes = QJsonDocument(root).toJson(QJsonDocument::Indented);
241 if (file.write(bytes) != bytes.size() || !file.commit()) {
242 qCWarning(lcQtPass) << "Could not write the .gpg-id generation record"
243 << path << file.errorString();
244 if (error)
245 *error = QCoreApplication::translate(
246 "GpgIdGeneration",
247 "The generation record of the recipient lists, %1, cannot "
248 "be written.")
249 .arg(path);
250 return false;
251 }
252 return true;
253}
254
255auto saveRecord(const QString &path, const Entries &entries, QString *error)
256 -> bool {
257 QJsonObject lists;
258 for (auto it = entries.constBegin(); it != entries.constEnd(); ++it) {
259 QJsonObject item;
260 item.insert(QLatin1String("generation"),
261 QString::number(it.value().generation));
262 if (!it.value().digest.isEmpty()) {
263 item.insert(QLatin1String("sha256"), it.value().digest);
264 }
265 lists.insert(it.key(), item);
266 }
267 return saveFile(path, QStringLiteral("lists"), lists, error);
268}
269
270auto saveStores(const QString &path, const Stores &stores, QString *error)
271 -> bool {
272 QJsonObject byKey;
273 for (auto it = stores.constBegin(); it != stores.constEnd(); ++it) {
274 QJsonObject item;
275 item.insert(QLatin1String("id"), it.value());
276 byKey.insert(it.key(), item);
277 }
278 return saveFile(path, QStringLiteral("stores"), byKey, error);
279}
280
285struct Transaction {
286 QMutexLocker<QMutex> mutex{&recordLock()};
287 QString path{recordPath()};
288 // The record's folder may not exist before its first write; the lock file
289 // needs it now.
290 bool haveFolder{QDir().mkpath(QFileInfo(path).absolutePath())};
291 QLockFile lock{path + QStringLiteral(".lock")};
292 bool locked{haveFolder && lock.tryLock(kRecordLockTimeoutMs)};
293 QString problem;
294 QString storesFile{storesPath()};
295 std::optional<Record> entries;
296
297 Transaction() {
298 if (!locked) {
299 problem = QCoreApplication::translate(
300 "GpgIdGeneration",
301 "The generation record of the recipient lists, %1, could "
302 "not be locked: another QtPass may be using it, or its "
303 "folder cannot be written.")
304 .arg(path);
305 return;
306 }
307 std::optional<Entries> lists =
308 loadFile<Entries>(path, parseRecord, &problem);
309 if (!lists) {
310 return;
311 }
312 std::optional<Stores> stores =
313 loadFile<Stores>(storesFile, parseStores, &problem);
314 if (!stores) {
315 return;
316 }
317 entries = Record{std::move(*lists), std::move(*stores)};
318 }
319
320 [[nodiscard]] auto ok(QString *error) const -> bool {
321 if (entries) {
322 return true;
323 }
324 if (error)
325 *error = problem;
326 return false;
327 }
328
331 [[nodiscard]] auto record() -> Record & {
332 // NOLINTNEXTLINE(bugprone-unchecked-optional-access): ok() checked it.
333 return *entries;
334 }
336 [[nodiscard]] auto record() const -> const Record & {
337 // NOLINTNEXTLINE(bugprone-unchecked-optional-access): ok() checked it.
338 return *entries;
339 }
340
342 [[nodiscard]] auto known(const QString &key) const -> bool {
343 return record().lists.contains(key);
344 }
345
347 [[nodiscard]] auto generation(const QString &key) const -> qint64 {
348 return record().lists.value(key).generation;
349 }
350
353 [[nodiscard]] auto store(const QString &key) const -> std::optional<QString> {
354 const auto it = record().stores.constFind(key);
355 if (it == record().stores.constEnd()) {
356 return std::nullopt;
357 }
358 return it.value();
359 }
360
362 auto pinStore(const QString &key, const QString &id, QString *error) -> bool {
363 Stores updated = record().stores;
364 updated.insert(key, id);
365 if (!saveStores(storesFile, updated, error)) {
366 return false;
367 }
368 record().stores = std::move(updated);
369 return true;
370 }
371
374 [[nodiscard]] auto digest(const QString &key) const
375 -> std::optional<QString> {
376 QString value = record().lists.value(key).digest;
377 if (value.isEmpty()) {
378 return std::nullopt;
379 }
380 return value;
381 }
382
385 auto remember(const QString &key, qint64 generation, const QString &digest,
386 QString *error) -> bool {
387 Entries updated = record().lists;
388 updated[key] = Entry{generation, digest};
389 if (!saveRecord(path, updated, error)) {
390 return false;
391 }
392 record().lists = std::move(updated);
393 return true;
394 }
395
398 [[nodiscard]] auto accepted(const QString &key, qint64 generation,
399 const QString &digest) const -> bool {
400 return this->generation(key) == generation && this->digest(key) == digest;
401 }
402
405 auto noteOnce(const QString &key, QString *error) -> bool {
406 return known(key) || remember(key, 0, QString(), error);
407 }
408
411 auto pinOnFirstSight(const QString &key, const std::optional<QString> &id,
412 QString *error) -> bool {
413 if (store(key) || !id) {
414 return true;
415 }
416 return pinStore(key, *id, error);
417 }
418};
419
423auto hasControl(const QByteArray &value) -> bool {
424 return std::any_of(value.cbegin(), value.cend(), [](const char c) {
425 const auto u = static_cast<unsigned char>(c);
426 return u < 0x20 || u == 0x7f;
427 });
428}
429
432auto relativeFolder(const QString &path, const QString &root)
433 -> std::optional<QString> {
434 QString folder = QFileInfo(path).absoluteDir().canonicalPath();
435 if (folder.isEmpty()) {
436 folder = QFileInfo(path).absolutePath();
437 }
438 QString store = QFileInfo(root).canonicalFilePath();
439 if (store.isEmpty()) {
440 store = QDir::cleanPath(QFileInfo(root).absoluteFilePath());
441 }
442 folder = QDir::fromNativeSeparators(QDir::cleanPath(folder));
443 store = QDir::fromNativeSeparators(QDir::cleanPath(store));
444#ifdef Q_OS_WIN
445 folder = folder.toLower();
446 store = store.toLower();
447#endif
448 if (folder == store) {
449 return QStringLiteral(".");
450 }
451 const QString prefix = store.endsWith(QLatin1Char('/'))
452 ? std::move(store)
453 : store + QLatin1Char('/');
454 if (!folder.startsWith(prefix)) {
455 return std::nullopt;
456 }
457 folder = folder.mid(prefix.size());
458 // The folder line is one line: a name with a line break in it would end
459 // it, and what follows would be read as a recipient of the signed list.
460 // Any other control character parse() refuses: the list written would be
461 // one that cannot be read back.
462 if (hasControl(folder.toUtf8())) {
463 return std::nullopt;
464 }
465 return folder;
466}
467} // namespace
468
469namespace {
470
473auto generationDigits(const QByteArray &digits) -> std::optional<qint64> {
474 if (digits.isEmpty() || digits.size() > kMaxDigits) {
475 return std::nullopt;
476 }
477 for (const char c : digits) {
478 if (c < '0' || c > '9') {
479 return std::nullopt;
480 }
481 }
482 return digits.toLongLong();
483}
484
488auto takeHeaderLine(const QByteArray &line, std::optional<qint64> &generation,
489 std::optional<QString> &folder,
490 std::optional<QString> &store) -> QString {
491 if (line.startsWith(GpgIdGeneration::kStorePrefix)) {
492 if (store) {
493 //: The store ID line is the line of a signed recipient list (.gpg-id)
494 //: that names the password store by its ID. "Store" is the password
495 //: store, not a shop.
496 return QCoreApplication::translate(
497 "GpgIdGeneration", "The list carries more than one store ID line.");
498 }
499 const QByteArray value = line.mid(GpgIdGeneration::kStorePrefix.size());
500 if (isStoreId(value)) {
501 store = QString::fromLatin1(value);
502 return {};
503 }
504 //: The store ID line is the line of a signed recipient list (.gpg-id)
505 //: that names the password store by its ID. "Store" is the password
506 //: store, not a shop.
507 return QCoreApplication::translate("GpgIdGeneration",
508 "The store ID line is malformed: %1")
509 .arg(QString::fromUtf8(line));
510 }
511 if (line.startsWith(GpgIdGeneration::kGenerationPrefix)) {
512 if (generation) {
513 return QCoreApplication::translate(
514 "GpgIdGeneration", "The list carries more than one generation line.");
515 }
516 generation =
517 generationDigits(line.mid(GpgIdGeneration::kGenerationPrefix.size()));
518 if (generation) {
519 return {};
520 }
521 return QCoreApplication::translate("GpgIdGeneration",
522 "The generation line is malformed: %1")
523 .arg(QString::fromUtf8(line));
524 }
525 if (line.startsWith(GpgIdGeneration::kFolderPrefix)) {
526 if (folder) {
527 return QCoreApplication::translate(
528 "GpgIdGeneration", "The list carries more than one folder line.");
529 }
530 const QByteArray value = line.mid(GpgIdGeneration::kFolderPrefix.size());
531 // A control character (a second \r of "\r\r\n", a tab, a NUL) is not
532 // part of a folder name QtPass writes, and would not survive being
533 // written back: header() ends the line, parse() strips one \r.
534 // The name is the bytes signed, nothing else: QString::fromUtf8() drops
535 // a leading byte order mark and turns bytes that are not UTF-8 into
536 // U+FFFD, so a list signed for "\uFEFFfinance" or "fin\xFF" would read
537 // as bound to finance/ or to a folder really named "fin\uFFFD".
538 QStringDecoder utf8(QStringDecoder::Utf8,
539 QStringDecoder::Flag::Stateless |
540 QStringDecoder::Flag::ConvertInitialBom);
541 const QString name = utf8(value);
542 if (!value.isEmpty() && !hasControl(value) && name.toUtf8() == value) {
543 folder = name;
544 return {};
545 }
546 return QCoreApplication::translate("GpgIdGeneration",
547 "The folder line is malformed: %1")
548 .arg(QString::fromUtf8(line));
549 }
550 return QCoreApplication::translate("GpgIdGeneration",
551 "The header line is malformed: %1")
552 .arg(QString::fromUtf8(line));
553}
554
555} // namespace
556
557auto GpgIdGeneration::parse(const QByteArray &contents, QString *error)
558 -> std::optional<Header> {
559 std::optional<qint64> generation;
560 std::optional<QString> folder;
561 std::optional<QString> store;
562 for (const QByteArray &rawLine : contents.split('\n')) {
563 QByteArray line = rawLine;
564 if (line.endsWith('\r')) {
565 line.chop(1);
566 }
567 // Only a line under our name is ours; any other comment is somebody
568 // else's. But a near miss under the same name is suspicious, not
569 // ignorable.
570 if (!line.startsWith(kOurComment)) {
571 continue;
572 }
573 const QString complaint = takeHeaderLine(line, generation, folder, store);
574 if (complaint.isEmpty()) {
575 continue;
576 }
577 if (error)
578 *error = complaint;
579 return std::nullopt;
580 }
581 if (generation && !folder) {
582 if (error)
583 *error = tr("The list carries a generation line but no folder line.");
584 return std::nullopt;
585 }
586 // QtPass writes the store line only with the other two.
587 if (store && !generation) {
588 if (error)
589 //: The store ID line names the password store by its ID; see the
590 //: other store ID line messages.
591 *error = tr("The list carries a store ID line but no generation line.");
592 return std::nullopt;
593 }
595 header.generation = generation.value_or(0);
596 header.folder = std::move(folder);
597 header.store = std::move(store);
598 return header;
599}
600
601auto GpgIdGeneration::header(qint64 generation, const QString &folder,
602 const QString &store) -> QByteArray {
603 QByteArray lines = kGenerationPrefix + QByteArray::number(generation) + '\n' +
604 kFolderPrefix + folder.toUtf8() + '\n';
605 if (!store.isEmpty()) {
606 lines += kStorePrefix + store.toLatin1() + '\n';
607 }
608 return lines;
609}
610
611auto GpgIdGeneration::withHeader(qint64 generation, const QString &folder,
612 const QByteArray &recipients,
613 const QString &store) -> QByteArray {
614 return header(generation, folder, store) + recipients;
615}
616
617auto GpgIdGeneration::folderOf(const QString &gpgIdFile,
618 const QString &storeRoot)
619 -> std::optional<QString> {
620 return relativeFolder(gpgIdFile, storeRoot);
621}
622
623auto GpgIdGeneration::key(const QString &gpgIdFile) -> QString {
624 const QFileInfo info(gpgIdFile);
625 // canonicalFilePath() is empty for a file that does not exist (a new
626 // profile's list, or one whose folder was removed with it): canonicalise
627 // the nearest folder that does exist and append the rest, so that the
628 // key is the one the list had while it was there.
629 QString canonical = info.canonicalFilePath();
630 if (canonical.isEmpty()) {
631 QString existing = QDir::cleanPath(info.absolutePath());
632 QString rest = info.fileName();
633 while (!QFileInfo(existing).isDir()) {
634 const QFileInfo up(existing);
635 const QString parent = QDir::cleanPath(up.absolutePath());
636 if (parent == existing) {
637 break;
638 }
639 rest = up.fileName() + QLatin1Char('/') + rest;
640 existing = parent;
641 }
642 QString dir = QDir(existing).canonicalPath();
643 if (dir.isEmpty()) {
644 dir = std::move(existing);
645 }
646 canonical = QDir::cleanPath(dir + QLatin1Char('/') + rest);
647 }
648 canonical = QDir::fromNativeSeparators(canonical);
649#ifdef Q_OS_WIN
650 canonical = canonical.toLower();
651#endif
652 return QString::fromLatin1(
653 QCryptographicHash::hash(canonical.toUtf8(), QCryptographicHash::Sha256)
654 .toHex());
655}
656
657auto GpgIdGeneration::recordFile() -> QString { return recordPath(); }
658
659auto GpgIdGeneration::storeRecordFile() -> QString { return storesPath(); }
660
661auto GpgIdGeneration::digest(const QByteArray &contents) -> QString {
662 return QString::fromLatin1(
663 QCryptographicHash::hash(contents, QCryptographicHash::Sha256).toHex());
664}
665
666auto GpgIdGeneration::remembered(const QString &gpgIdFile, QString *error)
667 -> std::optional<qint64> {
668 Transaction t;
669 if (!t.ok(error)) {
670 return std::nullopt;
671 }
672 return t.generation(key(gpgIdFile));
673}
674
675auto GpgIdGeneration::seen(const QString &gpgIdFile, QString *error)
676 -> std::optional<bool> {
677 Transaction t;
678 if (!t.ok(error)) {
679 return std::nullopt;
680 }
681 return t.known(key(gpgIdFile));
682}
683
684auto GpgIdGeneration::boundToItsFolder(const QString &gpgIdFile,
685 const Header &header,
686 const QString &storeRoot, QString *error)
687 -> bool {
688 if (!header.folder) {
689 return true;
690 }
691 const std::optional<QString> here = folderOf(gpgIdFile, storeRoot);
692 if (here && *here == *header.folder) {
693 return true;
694 }
695 if (error)
696 *error =
697 tr("The signed recipient list %1 was written for the folder "
698 "\"%2\" of the store, not for \"%3\", and is not used. It "
699 "may have been copied here by someone else; if the folder "
700 "was moved or renamed instead, a holder of the signing key "
701 "opens Users on it and saves the recipients, which binds "
702 "the list to where it is now.")
703 .arg(gpgIdFile, *header.folder, here.value_or(QStringLiteral("?")));
704 return false;
705}
706
707auto GpgIdGeneration::wayThrough(qint64 last, const QString &recordPath,
708 const QString &saving) -> QString {
709 if (last >= kMaxGeneration) {
710 return tr("Generation %1 is the highest there is, so no newer list "
711 "can be written here: removing %2 forgets what this device "
712 "accepted before, after which a holder of the signing key "
713 "gets through by opening Users and %3.")
714 .arg(last)
715 .arg(recordPath, saving);
716 }
717 return tr("A holder of the signing key gets through by opening Users "
718 "and %1, which writes generation %2. Removing %3 forgets what "
719 "this device accepted before.")
720 .arg(saving)
721 .arg(last + 1)
722 .arg(recordPath);
723}
724
725auto GpgIdGeneration::staleList(const QString &gpgIdFile, const Header &header,
726 qint64 last, const QString &recordPath,
727 QString *error) -> Verdict {
728 if (!header.folder) {
729 // Below what was accepted here and with no folder line to say it was
730 // written here at all: an authentic headerless pair from any folder's
731 // history would pass as this folder's rollback otherwise.
732 if (error)
733 *error =
734 tr("The signed recipient list %1 carries no generation line, "
735 "while generation %2 was accepted here before. pass writes no "
736 "generation line (also through QtPass's pass backend), nor did "
737 "QtPass before 2.0; without one the list may also have been "
738 "written for another folder of the store and copied here. %3")
739 .arg(gpgIdFile)
740 .arg(last)
741 .arg(
742 wayThrough(last, recordPath,
743 tr("selecting the recipients afresh and saving")));
744 return Verdict::Unbound;
745 }
746 if (error)
747 *error =
748 tr("The signed recipient list %1 is generation %2, older than "
749 "generation %3, the last one QtPass accepted here. It may have "
750 "been put back by someone else. %4")
751 .arg(gpgIdFile)
752 .arg(header.generation)
753 .arg(last)
754 .arg(wayThrough(last, recordPath,
755 tr("saving the recipients: the preselected "
756 "recipients there are this list's, so remove "
757 "anyone who should no longer have access "
758 "first")));
759 return Verdict::Rollback;
760}
761
762auto GpgIdGeneration::accept(const QString &gpgIdFile,
763 const QByteArray &contents,
764 const QString &storeRoot, QString *error)
765 -> Verdict {
766 QString why;
767 const std::optional<Header> header = parse(contents, &why);
768 if (!header) {
769 if (error)
770 *error = tr("The signed recipient list %1 is not one to trust: %2")
771 .arg(gpgIdFile, why);
772 return Verdict::Malformed;
773 }
774 // A pair is only valid where it was written for: copied into another
775 // folder it is a rollback in disguise (that folder's first list).
776 if (!boundToItsFolder(gpgIdFile, *header, storeRoot, error)) {
778 }
779 return acceptAgainstRecord(gpgIdFile, *header, contents, storeRoot, error);
780}
781
782auto GpgIdGeneration::acceptAgainstRecord(const QString &gpgIdFile,
783 const Header &header,
784 const QByteArray &contents,
785 const QString &storeRoot,
786 QString *error) -> Verdict {
787 Transaction t;
788 if (!t.ok(error)) {
790 }
791 const QString k = key(gpgIdFile);
792 const qint64 last = t.generation(k);
793 const qint64 generation = header.generation;
794 const QString bytes = digest(contents);
795 // Before anything that could preselect the list's recipients (a rollback
796 // is recovered through the Users dialog): a list of another store is no
797 // history of this one.
798 const QString storeKey = key(storeRoot);
799 const std::optional<QString> pinned = t.store(storeKey);
800 if (pinned &&
801 !ofThisStore(gpgIdFile, header, *pinned, t.accepted(k, generation, bytes),
802 t.storesFile, error)) {
803 return Verdict::WrongStore;
804 }
805 if (generation < last) {
806 return staleList(gpgIdFile, header, last, t.path, error);
807 }
808 if (generation == 0) {
809 // pass writes headerless lists on every change, so differing bytes here
810 // are normal, not a conflict. Generation 0 has no freshness to keep
811 // (SECURITY.md). Still noted, once, so that a removal of the list is
812 // told apart from a folder that never had one (Pass::skippedGpgId()).
813 if (!t.noteOnce(k, error)) {
815 }
816 // First sight of the store's id, on a list that is otherwise accepted.
817 return t.pinOnFirstSight(storeKey, header.store, error)
820 }
821 if (generation == last) {
822 // Same generation, different bytes: two devices both made 19 from 18
823 // (Git's conflict), or a swap. A record without a digest (an unrecorded
824 // reservation) takes these bytes as the ones.
825 const std::optional<QString> known = t.digest(k);
826 if (known) {
827 if (*known != bytes) {
828 return conflictingList(gpgIdFile, generation, last, t.path, error);
829 }
830 return t.pinOnFirstSight(storeKey, header.store, error)
833 }
834 }
835 // The pin first: a generation recorded with the pin's write failing would
836 // leave the store unpinned for the next list, another store's included.
837 if (!t.pinOnFirstSight(storeKey, header.store, error) ||
838 !t.remember(k, generation, bytes, error)) {
840 }
841 return Verdict::Accepted;
842}
843
844auto GpgIdGeneration::conflictingList(const QString &gpgIdFile,
845 qint64 generation, qint64 last,
846 const QString &recordPath, QString *error)
847 -> Verdict {
848 if (error)
849 *error = tr("The signed recipient list %1 is generation %2, the same "
850 "generation as a different list this device accepted "
851 "before. Either two devices saved recipients at the same "
852 "time (Git will have shown the conflict), or an authentic "
853 "list of that generation was swapped in. %3")
854 .arg(gpgIdFile)
855 .arg(generation)
856 .arg(wayThrough(last, recordPath,
857 tr("checking the recipients and saving")));
858 return Verdict::Conflict;
859}
860
861auto GpgIdGeneration::ofThisStore(const QString &gpgIdFile,
862 const Header &header, const QString &pinned,
863 bool alreadyAccepted,
864 const QString &recordPath, QString *error)
865 -> bool {
866 if (header.store) {
867 if (*header.store == pinned) {
868 return true;
869 }
870 if (error)
871 *error =
872 tr("The signed recipient list %1 was written for another password "
873 "store (store ID %2; this device knows this store as %3) and is "
874 "not used. It may have been copied here from a store signed "
875 "with the same key. If this store was set up again instead, "
876 "removing %4 forgets the store IDs this device knows.")
877 .arg(gpgIdFile, *header.store, pinned, recordPath);
878 return false;
879 }
880 // No store line: a list without a generation (pass) has none to carry,
881 // and one this device accepted before it had a store id still is what it
882 // was. Anything new must say which store it is for.
883 if (header.generation == 0 || alreadyAccepted) {
884 return true;
885 }
886 if (error)
887 *error =
888 //: The store ID line is the line of a signed recipient list that
889 //: names the password store by its ID (%2 here).
890 tr("The signed recipient list %1 carries no store ID line, while this "
891 "device knows this store by its ID %2: it may have been written "
892 "for another store and copied here, or by an older QtPass. A "
893 "holder of the signing key gets through by opening Users, "
894 "selecting the recipients afresh and saving, which writes the "
895 "store ID line.")
896 .arg(gpgIdFile, pinned);
897 return false;
898}
899
900auto GpgIdGeneration::storeIdFor(const QString &storeRoot,
901 const std::optional<QString> &onDisk,
902 QString *error) -> std::optional<QString> {
903 Transaction t;
904 if (!t.ok(error)) {
905 return std::nullopt;
906 }
907 const QString storeKey = key(storeRoot);
908 if (const std::optional<QString> pinned = t.store(storeKey)) {
909 return pinned;
910 }
911 // Joining a store that has an id already: take it over, rather than
912 // giving the store a second one every other device would refuse.
913 QString id = onDisk && isStoreId(onDisk->toLatin1())
914 ? *onDisk
915 : QUuid::createUuid().toString(QUuid::Id128).toLower();
916 if (!t.pinStore(storeKey, id, error)) {
917 return std::nullopt;
918 }
919 return id;
920}
921
922auto GpgIdGeneration::reserveNext(const QString &gpgIdFile,
923 std::optional<qint64> verifiedOnDisk,
924 QString *error) -> std::optional<qint64> {
925 Transaction t;
926 if (!t.ok(error)) {
927 return std::nullopt;
928 }
929 const QString k = key(gpgIdFile);
930 const qint64 last = t.generation(k);
931 const qint64 base = qMax(last, verifiedOnDisk.value_or(0));
932 if (base >= kMaxGeneration) {
933 if (error)
934 *error = tr("The recipient list %1 has reached generation %2, the "
935 "highest there is; the list cannot be written.")
936 .arg(gpgIdFile)
937 .arg(base);
938 return std::nullopt;
939 }
940 const qint64 generation = base + 1;
941 // No digest until the bytes are written: the previous generation's must
942 // not pass for this one's.
943 if (!t.remember(k, generation, QString(), error)) {
944 return std::nullopt;
945 }
946 return generation;
947}
948
949auto GpgIdGeneration::recordWritten(const QString &gpgIdFile,
950 const QByteArray &contents, QString *error)
951 -> bool {
952 const std::optional<Header> header = parse(contents, error);
953 if (!header) {
954 return false;
955 }
956 Transaction t;
957 if (!t.ok(error)) {
958 return false;
959 }
960 const QString k = key(gpgIdFile);
961 const qint64 last = t.generation(k);
962 if (header->generation != last) {
963 // Not the generation reserved last: something else moved the record in
964 // between; whatever is there is not overwritten with these bytes.
965 if (error)
966 *error = tr("The generation record of the recipient lists, %1, has "
967 "moved on to generation %2 while generation %3 was being "
968 "written.")
969 .arg(t.path)
970 .arg(last)
971 .arg(header->generation);
972 return false;
973 }
974 return t.remember(k, last, digest(contents), error);
975}
static auto accept(const QString &gpgIdFile, const QByteArray &contents, const QString &storeRoot, QString *error=nullptr) -> Verdict
Decide about a verified list: its folder against where it sits, its generation against the remembered...
static auto ofThisStore(const QString &gpgIdFile, const Header &header, const QString &pinned, bool alreadyAccepted, const QString &recordPath, QString *error) -> bool
Whether header fits the store this device knows by pinned: its store line names that id,...
static auto digest(const QByteArray &contents) -> QString
The digest of a list as the record keeps it: SHA-256 of the exact bytes, hexadecimal,...
static auto header(qint64 generation, const QString &folder, const QString &store={}) -> QByteArray
The header lines for a list.
static auto storeRecordFile() -> QString
The file the store IDs are kept in, next to recordFile() and under its lock, so a QtPass from before ...
static auto folderOf(const QString &gpgIdFile, const QString &storeRoot) -> std::optional< QString >
The store-relative folder of gpgIdFile, as written in and compared against the folder line: ....
static auto reserveNext(const QString &gpgIdFile, std::optional< qint64 > verifiedOnDisk, QString *error=nullptr) -> std::optional< qint64 >
Reserve the generation to write next for gpgIdFile: one above both what this device remembers and ver...
static auto boundToItsFolder(const QString &gpgIdFile, const Header &header, const QString &storeRoot, QString *error) -> bool
Whether header's folder line, if it has one, names the folder the list sits in: a pair copied elsewhe...
static auto acceptAgainstRecord(const QString &gpgIdFile, const Header &header, const QByteArray &contents, const QString &storeRoot, QString *error) -> Verdict
The second half of accept(), for a list whose header parsed and fits its folder: check it against wha...
static auto recordWritten(const QString &gpgIdFile, const QByteArray &contents, QString *error=nullptr) -> bool
Record the bytes just written for gpgIdFile, so that this device recognises its own list afterwards a...
static auto key(const QString &gpgIdFile) -> QString
The settings key for a .gpg-id: a hash of its canonical path, so path spelling (case,...
static auto seen(const QString &gpgIdFile, QString *error=nullptr) -> std::optional< bool >
Whether this device accepted or wrote a list at gpgIdFile before, of any generation: a headerless lis...
Verdict
The outcome of accept(). Only Accepted means the list may be used; the others say why not,...
@ Malformed
A header line malformed or duplicated.
@ Accepted
Folder, generation and record all agree; remembered.
@ RecordUnavailable
The record could not be read or written.
@ Rollback
Authentic and bound to this folder, but older than a generation this device accepted.
@ WrongFolder
Written for another folder of the store.
@ WrongStore
Written for another store (its store line names another id than this device knows the store by),...
@ Unbound
Older than a generation this device accepted and without a folder line: authentic,...
@ Conflict
The generation this device accepted last, but not the bytes: two devices saved at once (Git shows tha...
static auto remembered(const QString &gpgIdFile, QString *error=nullptr) -> std::optional< qint64 >
The highest generation this device has accepted or written for the .gpg-id at gpgIdFile....
static auto staleList(const QString &gpgIdFile, const Header &header, qint64 last, const QString &recordPath, QString *error) -> Verdict
The refusal for a list older than the one accepted here: a rollback, or an unbound list that could be...
static const QByteArray kStorePrefix
static const QByteArray kFolderPrefix
static const qint64 kMaxGeneration
static auto conflictingList(const QString &gpgIdFile, qint64 generation, qint64 last, const QString &recordPath, QString *error) -> Verdict
The refusal for a list of the generation accepted here whose bytes differ: two devices saved at once,...
static auto withHeader(qint64 generation, const QString &folder, const QByteArray &recipients, const QString &store={}) -> QByteArray
A complete list: the header in front of the recipients.
static auto recordFile() -> QString
The file the accepted generations are recorded in, so a refusal can name it: removing it forgets what...
static const QByteArray kGenerationPrefix
static auto parse(const QByteArray &contents, QString *error=nullptr) -> std::optional< Header >
The header a .gpg-id's bytes declare.
static auto storeIdFor(const QString &storeRoot, const std::optional< QString > &onDisk, QString *error=nullptr) -> std::optional< QString >
The store id to write into a list of storeRoot: the one this device knows the store by; else onDisk,...
static auto wayThrough(qint64 last, const QString &recordPath, const QString &saving) -> QString
How a holder of the signing key gets through a refusal, in words: saving the recipients writes the ne...
Rollback detection for signed .gpg-id files: the generation counter and the record of what was last s...
The "qtpass" logging category.
What a list's header says.
std::optional< QString > folder
Nothing when the list carries no folder line.
qint64 generation
0 when the list carries no generation line.
std::optional< QString > store
Nothing when the list carries no store line.