10#include <QCoreApplication>
11#include <QCryptographicHash>
15#include <QJsonDocument>
20#include <QMutexLocker>
23#include <QStringDecoder>
29 QByteArrayLiteral(
"# QtPass-GpgId-Generation: ");
31 QByteArrayLiteral(
"# QtPass-GpgId-Folder: ");
33 QByteArrayLiteral(
"# QtPass-GpgId-Store: ");
37constexpr int kMaxDigits = 18;
38constexpr QByteArrayView kOurComment(
"# QtPass-GpgId-");
43auto tr(
const char *text) -> QString {
44 return QCoreApplication::translate(
"GpgIdGeneration", text);
56constexpr int kRecordLockTimeoutMs = 3000;
61 qint64 generation = 0;
64using Entries = QMap<QString, Entry>;
67using Stores = QMap<QString, QString>;
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');
82constexpr QLatin1StringView kRecordName(
"QtPass-gpgid-generations.json");
86constexpr QLatin1StringView kStoresName(
"QtPass-gpgid-stores.json");
87constexpr int kRecordFormat = 1;
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(
'/') +
104auto storesPath() -> QString {
105 return QFileInfo(recordPath()).absolutePath() + QLatin1Char(
'/') +
112auto recordEntry(
const QJsonValue &value) -> std::optional<Entry> {
113 if (!value.isObject()) {
116 const QJsonObject item = value.toObject();
117 const QString generation = item.value(QLatin1String(
"generation")).toString();
118 if (generation.isEmpty() || generation.size() > kMaxDigits) {
121 for (
const QChar c : generation) {
122 if (c < QLatin1Char(
'0') || c > QLatin1Char(
'9')) {
127 entry.generation = generation.toLongLong();
128 entry.digest = item.value(QLatin1String(
"sha256")).toString();
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()) {
141 const QJsonObject root = doc.object();
142 const QJsonValue inner = root.value(name);
143 if (root.value(QLatin1String(
"format")).toInt() != kRecordFormat ||
147 return inner.toObject();
152auto parseRecord(
const QByteArray &bytes) -> std::optional<Entries> {
153 const std::optional<QJsonObject> byKey =
154 recordObject(bytes, QStringLiteral(
"lists"));
159 for (
auto it = byKey->constBegin(); it != byKey->constEnd(); ++it) {
160 const std::optional<Entry> entry = recordEntry(it.value());
164 entries.insert(it.key(), *entry);
171auto parseStores(
const QByteArray &bytes) -> std::optional<Stores> {
172 const std::optional<QJsonObject> byKey =
173 recordObject(bytes, QStringLiteral(
"stores"));
178 for (
auto it = byKey->constBegin(); it != byKey->constEnd(); ++it) {
180 it.value().toObject().value(QLatin1String(
"id")).toString();
181 if (!it.value().isObject() || !isStoreId(
id.toLatin1())) {
184 stores.insert(it.key(),
id);
192template <
typename T,
typename Parse>
193auto loadFile(
const QString &path, Parse parse, QString *error)
194 -> std::optional<T> {
195 if (!QFileInfo::exists(path)) {
199 if (!file.open(QIODevice::ReadOnly)) {
201 *error = QCoreApplication::translate(
203 "The generation record of the recipient lists, %1, cannot "
208 std::optional<T> value = parse(file.readAll());
209 if (!value && error) {
210 *error = QCoreApplication::translate(
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 "
224auto saveFile(
const QString &path,
const QString &name,
225 const QJsonObject &inner, QString *error) ->
bool {
227 root.insert(QLatin1String(
"format"), kRecordFormat);
228 root.insert(name, inner);
229 QSaveFile file(path);
230 if (!file.open(QIODevice::WriteOnly)) {
232 *error = QCoreApplication::translate(
234 "The generation record of the recipient lists, %1, cannot "
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();
245 *error = QCoreApplication::translate(
247 "The generation record of the recipient lists, %1, cannot "
255auto saveRecord(
const QString &path,
const Entries &entries, QString *error)
258 for (
auto it = entries.constBegin(); it != entries.constEnd(); ++it) {
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);
265 lists.insert(it.key(), item);
267 return saveFile(path, QStringLiteral(
"lists"), lists, error);
270auto saveStores(
const QString &path,
const Stores &stores, QString *error)
273 for (
auto it = stores.constBegin(); it != stores.constEnd(); ++it) {
275 item.insert(QLatin1String(
"id"), it.value());
276 byKey.insert(it.key(), item);
278 return saveFile(path, QStringLiteral(
"stores"), byKey, error);
286 QMutexLocker<QMutex> mutex{&recordLock()};
287 QString path{recordPath()};
290 bool haveFolder{QDir().mkpath(QFileInfo(path).absolutePath())};
291 QLockFile lock{path + QStringLiteral(
".lock")};
292 bool locked{haveFolder && lock.tryLock(kRecordLockTimeoutMs)};
294 QString storesFile{storesPath()};
295 std::optional<Record> entries;
299 problem = QCoreApplication::translate(
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.")
307 std::optional<Entries> lists =
308 loadFile<Entries>(path, parseRecord, &problem);
312 std::optional<Stores> stores =
313 loadFile<Stores>(storesFile, parseStores, &problem);
317 entries = Record{std::move(*lists), std::move(*stores)};
320 [[nodiscard]]
auto ok(QString *error)
const ->
bool {
331 [[nodiscard]]
auto record() -> Record & {
336 [[nodiscard]]
auto record() const -> const Record & {
342 [[nodiscard]]
auto known(
const QString &key)
const ->
bool {
343 return record().lists.contains(key);
347 [[nodiscard]]
auto generation(
const QString &key)
const -> qint64 {
348 return record().lists.value(key).generation;
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()) {
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)) {
368 record().stores = std::move(updated);
374 [[nodiscard]]
auto digest(
const QString &key)
const
375 -> std::optional<QString> {
376 QString value = record().lists.value(key).digest;
377 if (value.isEmpty()) {
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)) {
392 record().lists = std::move(updated);
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;
405 auto noteOnce(
const QString &key, QString *error) ->
bool {
406 return known(key) || remember(key, 0, QString(), error);
411 auto pinOnFirstSight(
const QString &key,
const std::optional<QString> &
id,
412 QString *error) ->
bool {
413 if (store(key) || !
id) {
416 return pinStore(key, *
id, error);
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;
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();
438 QString store = QFileInfo(root).canonicalFilePath();
439 if (store.isEmpty()) {
440 store = QDir::cleanPath(QFileInfo(root).absoluteFilePath());
442 folder = QDir::fromNativeSeparators(QDir::cleanPath(folder));
443 store = QDir::fromNativeSeparators(QDir::cleanPath(store));
445 folder = folder.toLower();
446 store = store.toLower();
448 if (folder == store) {
449 return QStringLiteral(
".");
451 const QString prefix = store.endsWith(QLatin1Char(
'/'))
453 : store + QLatin1Char(
'/');
454 if (!folder.startsWith(prefix)) {
457 folder = folder.mid(prefix.size());
462 if (hasControl(folder.toUtf8())) {
473auto generationDigits(
const QByteArray &digits) -> std::optional<qint64> {
474 if (digits.isEmpty() || digits.size() > kMaxDigits) {
477 for (
const char c : digits) {
478 if (c <
'0' || c >
'9') {
482 return digits.toLongLong();
488auto takeHeaderLine(
const QByteArray &line, std::optional<qint64> &generation,
489 std::optional<QString> &folder,
490 std::optional<QString> &store) -> QString {
496 return QCoreApplication::translate(
497 "GpgIdGeneration",
"The list carries more than one store ID line.");
500 if (isStoreId(value)) {
501 store = QString::fromLatin1(value);
507 return QCoreApplication::translate(
"GpgIdGeneration",
508 "The store ID line is malformed: %1")
509 .arg(QString::fromUtf8(line));
513 return QCoreApplication::translate(
514 "GpgIdGeneration",
"The list carries more than one generation line.");
521 return QCoreApplication::translate(
"GpgIdGeneration",
522 "The generation line is malformed: %1")
523 .arg(QString::fromUtf8(line));
527 return QCoreApplication::translate(
528 "GpgIdGeneration",
"The list carries more than one folder line.");
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) {
546 return QCoreApplication::translate(
"GpgIdGeneration",
547 "The folder line is malformed: %1")
548 .arg(QString::fromUtf8(line));
550 return QCoreApplication::translate(
"GpgIdGeneration",
551 "The header line is malformed: %1")
552 .arg(QString::fromUtf8(line));
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')) {
570 if (!line.startsWith(kOurComment)) {
573 const QString complaint = takeHeaderLine(line, generation, folder, store);
574 if (complaint.isEmpty()) {
581 if (generation && !folder) {
583 *error = tr(
"The list carries a generation line but no folder line.");
587 if (store && !generation) {
591 *error = tr(
"The list carries a store ID line but no generation line.");
602 const QString &store) -> QByteArray {
605 if (!store.isEmpty()) {
612 const QByteArray &recipients,
613 const QString &store) -> QByteArray {
614 return header(generation, folder, store) + recipients;
618 const QString &storeRoot)
619 -> std::optional<QString> {
620 return relativeFolder(gpgIdFile, storeRoot);
624 const QFileInfo info(gpgIdFile);
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) {
639 rest = up.fileName() + QLatin1Char(
'/') + rest;
642 QString dir = QDir(existing).canonicalPath();
644 dir = std::move(existing);
646 canonical = QDir::cleanPath(dir + QLatin1Char(
'/') + rest);
648 canonical = QDir::fromNativeSeparators(canonical);
650 canonical = canonical.toLower();
652 return QString::fromLatin1(
653 QCryptographicHash::hash(canonical.toUtf8(), QCryptographicHash::Sha256)
662 return QString::fromLatin1(
663 QCryptographicHash::hash(contents, QCryptographicHash::Sha256).toHex());
667 -> std::optional<qint64> {
672 return t.generation(
key(gpgIdFile));
676 -> std::optional<bool> {
681 return t.known(
key(gpgIdFile));
686 const QString &storeRoot, QString *error)
691 const std::optional<QString> here =
folderOf(gpgIdFile, storeRoot);
692 if (here && *here == *
header.folder) {
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(
"?")));
708 const QString &saving) -> QString {
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.")
715 .arg(recordPath, saving);
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.")
726 qint64 last,
const QString &recordPath,
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")
743 tr(
"selecting the recipients afresh and saving")));
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")
755 tr(
"saving the recipients: the preselected "
756 "recipients there are this list's, so remove "
757 "anyone who should no longer have access "
763 const QByteArray &contents,
764 const QString &storeRoot, QString *error)
767 const std::optional<Header>
header =
parse(contents, &why);
770 *error = tr(
"The signed recipient list %1 is not one to trust: %2")
771 .arg(gpgIdFile, why);
784 const QByteArray &contents,
785 const QString &storeRoot,
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);
798 const QString storeKey =
key(storeRoot);
799 const std::optional<QString> pinned = t.store(storeKey);
802 t.storesFile, error)) {
805 if (generation < last) {
808 if (generation == 0) {
813 if (!t.noteOnce(k, error)) {
817 return t.pinOnFirstSight(storeKey,
header.store, error)
821 if (generation == last) {
825 const std::optional<QString> known = t.digest(k);
827 if (*known != bytes) {
830 return t.pinOnFirstSight(storeKey,
header.store, error)
837 if (!t.pinOnFirstSight(storeKey,
header.store, error) ||
838 !t.remember(k, generation, bytes, error)) {
845 qint64 generation, qint64 last,
846 const QString &recordPath, QString *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")
857 tr(
"checking the recipients and saving")));
863 bool alreadyAccepted,
864 const QString &recordPath, QString *error)
867 if (*
header.store == pinned) {
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);
883 if (
header.generation == 0 || alreadyAccepted) {
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 "
896 .arg(gpgIdFile, pinned);
901 const std::optional<QString> &onDisk,
902 QString *error) -> std::optional<QString> {
907 const QString storeKey =
key(storeRoot);
908 if (
const std::optional<QString> pinned = t.store(storeKey)) {
913 QString
id = onDisk && isStoreId(onDisk->toLatin1())
915 : QUuid::createUuid().toString(QUuid::Id128).toLower();
916 if (!t.pinStore(storeKey,
id, error)) {
923 std::optional<qint64> verifiedOnDisk,
924 QString *error) -> std::optional<qint64> {
929 const QString k =
key(gpgIdFile);
930 const qint64 last = t.generation(k);
931 const qint64 base = qMax(last, verifiedOnDisk.value_or(0));
934 *error = tr(
"The recipient list %1 has reached generation %2, the "
935 "highest there is; the list cannot be written.")
940 const qint64 generation = base + 1;
943 if (!t.remember(k, generation, QString(), error)) {
950 const QByteArray &contents, QString *error)
952 const std::optional<Header>
header =
parse(contents, error);
960 const QString k =
key(gpgIdFile);
961 const qint64 last = t.generation(k);
962 if (
header->generation != last) {
966 *error = tr(
"The generation record of the recipient lists, %1, has "
967 "moved on to generation %2 while generation %3 was being "
974 return t.remember(k, last,
digest(contents), error);
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.