QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
pass.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
10#include "pass.h"
11
12#include "entryrecord.h"
13#include "gpgidgeneration.h"
14#include "gpgidsigner.h"
15#include "gpgkeystate.h"
16#include "pathvalidator.h"
17#include "processinfo.h"
18#include "util.h"
19#include <QCoreApplication>
20#include <QDebug>
21#include <QDir>
22#include <QFile>
23#include <QFileInfo>
24#include <QHash>
25#include <QLocale>
26#include <QProcess>
27#include <QRandomGenerator>
28#include <QRegularExpression>
29#include <QSaveFile>
30#include <QScopeGuard>
31#include <QTemporaryDir>
32#include <QTextStream>
33#include <algorithm>
34#include <array>
35#include <optional>
36#include <utility>
37
38#include "qtpasslogging.h"
39
40using Enums::GIT_INIT;
41using Enums::GIT_PULL;
42using Enums::GIT_PUSH;
50
51namespace {
52auto fallbackCharset(const QString &input, const QString &fallback) -> QString {
53 return input.isEmpty() ? fallback : input;
54}
55
56auto effectiveCharset(const PasswordConfiguration &passConfig) -> QString {
57 int sel = passConfig.selected;
58 if (sel < 0 || sel >= PasswordConfiguration::CHARSETS_COUNT)
60 return fallbackCharset(
61 passConfig.Characters[sel],
62 passConfig.Characters[PasswordConfiguration::ALLCHARS]);
63}
64
71void mergeIntoWslenv(QProcessEnvironment &env, const QStringList &names) {
72 QStringList parts = env.value(QStringLiteral("WSLENV"))
73 .split(QLatin1Char(':'), Qt::SkipEmptyParts);
74 for (const QString &name : names) {
75 if (!parts.contains(name)) {
76 parts.append(name);
77 }
78 }
79 env.insert(QStringLiteral("WSLENV"), parts.join(QLatin1Char(':')));
80}
81} // namespace
82
83Pass::Pass() : env(QProcessEnvironment::systemEnvironment()) {
84 connect(&exec, &Executor::finished, this, &Pass::finished);
85 connect(&exec, &Executor::error, this, &Pass::finished);
86
88 connect(&exec, &Executor::drained, this, [this] {
89 // Idle means the queue is empty and nothing runs, so no insert is in
90 // flight: force the pending count to zero. A report that never arrived
91 // (the "No such transaction" path in ImitatePass::finished(), or any
92 // later change that drops an insert without reporting) would otherwise
93 // leave the count one too high for the rest of the session, and every
94 // later dialog would take its own report for an earlier one and wait for
95 // ever. Idle cannot fall between a dialog's insertsPending() read and its
96 // own report, since that insert keeps the executor busy.
98 m_insertedEntries.clear();
99 emit idle();
100 });
101 // Each queued process starts in the environment as the store is then:
102 // the Git pin is judged at that moment (dequeuing() comes just before the
103 // start, on this thread).
104 connect(&exec, &Executor::dequeuing, this, [this](int, bool completes) {
105 if (completes) {
107 }
108 });
109 // Merge our vars into WSLENV rather than blindly appending a duplicate
110 // entry. WSLENV flags: /p translates the path, /u forwards from Windows
111 // into WSL only; /w would be the other direction, from WSL out, and leaves
112 // pass inside WSL without the value. Everything updateEnv() sets for pass
113 // has to cross, the signing key above all: without it pass does not check
114 // the .gpg-id signature.
115 const QStringList wslenvVars = {
116 QStringLiteral("PASSWORD_STORE_DIR/p"),
117 QStringLiteral("PASSWORD_STORE_SIGNING_KEY/u"),
118 QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH/u"),
119 QStringLiteral("PASSWORD_STORE_CHARACTER_SET/u"),
120 QStringLiteral("PASSWORD_STORE_GPG_OPTS/u"),
121 QStringLiteral("GIT_CEILING_DIRECTORIES/p"),
122 QStringLiteral("GIT_LITERAL_PATHSPECS/u")};
123 mergeIntoWslenv(env, wslenvVars);
124}
125
126void Pass::executeWrapper(PROCESS id, const QString &app,
127 const QStringList &args, bool readStdout,
128 bool readStderr) {
129 executeWrapper(id, app, args, QString(), readStdout, readStderr);
130}
131
132void Pass::executeWrapper(PROCESS id, const QString &app,
133 const QStringList &args, QString input,
134 bool readStdout, bool readStderr) {
135 beforeExecute(id);
136 qCDebug(lcQtPass) << app << loggableArgs(args);
137 exec.execute(id, m_settings.passStore, app, args, std::move(input),
138 readStdout, readStderr);
139}
140
141auto Pass::loggableArgs(const QStringList &args) -> QStringList {
142 // Secrets travel on stdin (Insert's content, KeygenDialog's batch file),
143 // never in argv; this keeps the log honest should that ever change.
144 static const QStringList secretOptions{
145 QStringLiteral("--passphrase"), QStringLiteral("--override-session-key")};
146 QStringList out;
147 bool hide = false;
148 for (const QString &arg : args) {
149 if (hide) {
150 out << QStringLiteral("<redacted>");
151 hide = false;
152 continue;
153 }
154 if (arg.startsWith(QStringLiteral("otpauth://"))) {
155 out << QStringLiteral("<redacted>");
156 continue;
157 }
158 if (arg.startsWith(QStringLiteral("--passphrase=")) ||
159 arg.startsWith(QStringLiteral("--override-session-key="))) {
160 out << arg.left(arg.indexOf(u'=') + 1) + QStringLiteral("<redacted>");
161 continue;
162 }
163 hide = secretOptions.contains(arg);
164 out << arg;
165 }
166 return out;
167}
168
170
171void Pass::init(const AppSettings &settings) {
172 m_settings = settings;
173 // A key exported for pass counts when none is set here: pass checks the
174 // list against it, and so do QtPass's own checks. Dropping it turned every
175 // check off.
178#ifdef __APPLE__
179 // If it exists, prepend gpgtools to PATH
180 if (QFile(QStringLiteral("/usr/local/MacGPG2/bin")).exists())
181 env.insert(QStringLiteral("PATH"),
182 QStringLiteral("/usr/local/MacGPG2/bin:") +
183 env.value(QStringLiteral("PATH")));
184 // Add missing /usr/local/bin (exact component match, no leading colon)
185 const QString currentPath = env.value(QStringLiteral("PATH"));
186 if (!currentPath.split(':', Qt::SkipEmptyParts)
187 .contains(QStringLiteral("/usr/local/bin"))) {
188 env.insert(QStringLiteral("PATH"),
189 currentPath.isEmpty()
190 ? QStringLiteral("/usr/local/bin")
191 : QStringLiteral("/usr/local/bin:") + currentPath);
192 }
193#endif
194
195 // The configured gpgHome wins over GNUPGHOME only when it exists: a stale
196 // one (#1711) fails every gpg call with "No secret key". Clearing the
197 // setting restores the inherited value rather than keeping the old path.
198 const QString inheritedHome = QProcessEnvironment::systemEnvironment().value(
199 QStringLiteral("GNUPGHOME"));
200 const auto useInheritedHome = [this, &inheritedHome]() {
201 if (inheritedHome.isEmpty()) {
202 env.remove(QStringLiteral("GNUPGHOME"));
203 } else {
204 env.insert(QStringLiteral("GNUPGHOME"), inheritedHome);
205 }
206 };
207 if (m_settings.gpgHome.isEmpty()) {
208 useInheritedHome();
209 } else {
210 QDir absHome(m_settings.gpgHome);
211 absHome.makeAbsolute();
212 if (absHome.exists()) {
213 env.insert(QStringLiteral("GNUPGHOME"), absHome.path());
214 } else {
215 if (inheritedHome.isEmpty()) {
216 qCWarning(lcQtPass) << "gpgHome" << absHome.path()
217 << "does not exist; using the default GnuPG home";
218 emit statusMsg(tr("Configured GPG home %1 does not exist, using the "
219 "default keyring")
220 .arg(absHome.path()),
221 5000);
222 } else {
223 qCWarning(lcQtPass)
224 << "gpgHome" << absHome.path() << "does not exist; using GNUPGHOME"
225 << inheritedHome << "from the environment";
226 emit statusMsg(tr("Configured GPG home %1 does not exist, using "
227 "GNUPGHOME %2 from the environment")
228 .arg(absHome.path(), inheritedHome),
229 5000);
230 }
231 useInheritedHome();
232 }
233 }
234 // With signed lists, the entries a store holds when this device first
235 // opens it count as saved here (trust on first use), before anything a
236 // pusher writes can land: not at the edit check, which would record a
237 // renamed folder as saved. Unsigned stores never walk.
238 if (!m_settings.passSigningKey.isEmpty()) {
240 }
241}
242
243auto Pass::generatePassword(unsigned int length, const QString &charset)
244 -> QString {
245 if (length == 0) {
246 emit critical(tr("Invalid password length"),
247 tr("Can't generate password with zero length."));
248 return {};
249 }
250 QString passwd;
251 if (m_settings.usePwgen) {
252 // --secure goes first as it overrides --no-* otherwise
253 QStringList args;
254 args.append("-1");
255 if (!m_settings.lessRandom) {
256 args.append("--secure");
257 }
258 args.append(m_settings.avoidCapitals ? "--no-capitalize" : "--capitalize");
259 args.append(m_settings.avoidNumbers ? "--no-numerals" : "--numerals");
260 if (m_settings.useSymbols) {
261 args.append("--symbols");
262 }
263 args.append(QString::number(length));
264 if (Executor::executeBlocking(m_settings.pwgenExecutable, args, &passwd) ==
265 0) {
266 static const QRegularExpression literalNewLines{"[\\n\\r]"};
267 passwd.remove(literalNewLines);
268 } else {
269 passwd.clear();
270 qCDebug(lcQtPass) << "pwgen fail";
271 // Report it, as the other generation failures do: otherwise Generate
272 // does nothing silently and OK then saves an empty (or, on Edit, the
273 // old) password.
274 emit critical(
275 tr("Password generation failed"),
276 tr("Could not run pwgen (\"%1\"). Check the pwgen program in the "
277 "settings, or turn \"Use pwgen\" off.")
278 .arg(m_settings.pwgenExecutable));
279 }
280 } else {
281 // An empty CUSTOM charset falls back to ALLCHARS, not a weak password
282 // (#780).
283 const QString cs = fallbackCharset(
284 charset, m_settings.passwordConfiguration
286 if (cs.length() > 0) {
287 passwd = generateRandomPassword(cs, length);
288 } else {
289 emit critical(
290 tr("No characters chosen"),
291 tr("Can't generate password, there are no characters to choose from "
292 "set in the configuration!"));
293 }
294 }
295 return passwd;
296}
297
298bool Pass::gpgSupportsEd25519(const QString &gpgExecutable) {
299 const QString exe =
300 gpgExecutable.isEmpty() ? QStringLiteral("gpg") : gpgExecutable;
301 QString out, err;
302 if (Executor::executeBlocking(exe, {"--version"}, &out, &err) != 0) {
303 return false;
304 }
305 static const QRegularExpression versionRegex(
306 QStringLiteral(R"(gpg \‍(GnuPG\) (\d+)\.(\d+))"));
307 QRegularExpressionMatch match = versionRegex.match(out);
308 if (!match.hasMatch()) {
309 return false;
310 }
311 int major = match.captured(1).toInt();
312 int minor = match.captured(2).toInt();
313 return major > 2 || (major == 2 && minor >= 1);
314}
315
316// ed25519 (GnuPG 2.1+) generates much faster than RSA.
317QString Pass::getDefaultKeyTemplate(const QString &gpgExecutable) {
318 if (gpgSupportsEd25519(gpgExecutable)) {
319 return QStringLiteral("%echo Generating a default key\n"
320 "Key-Type: EdDSA\n"
321 "Key-Curve: Ed25519\n"
322 "Subkey-Type: ECDH\n"
323 "Subkey-Curve: Curve25519\n"
324 "Name-Real: \n"
325 "Name-Comment: QtPass\n"
326 "Name-Email: \n"
327 "Expire-Date: 0\n"
328 "%no-protection\n"
329 "%commit\n"
330 "%echo done");
331 }
332 return QStringLiteral("%echo Generating a default key\n"
333 "Key-Type: RSA\n"
334 "Subkey-Type: RSA\n"
335 "Name-Real: \n"
336 "Name-Comment: QtPass\n"
337 "Name-Email: \n"
338 "Expire-Date: 0\n"
339 "%no-protection\n"
340 "%commit\n"
341 "%echo done");
342}
343
344namespace {
345auto resolveWslGpgconfPath(const QString &lastPart) -> QString {
346 qsizetype lastSep = lastPart.lastIndexOf('/');
347 if (lastSep < 0) {
348 lastSep = lastPart.lastIndexOf('\\');
349 }
350 if (lastSep >= 0) {
351 return lastPart.left(lastSep + 1) + "gpgconf";
352 }
353 return QStringLiteral("gpgconf");
354}
355
356QString findGpgconfInGpgDir(const QString &gpgPath) {
357 QFileInfo gpgInfo(gpgPath);
358 if (!gpgInfo.isAbsolute()) {
359 return {};
360 }
361
362 QDir dir(gpgInfo.absolutePath());
363
364#ifdef Q_OS_WIN
365 QFileInfo candidateExe(dir.filePath("gpgconf.exe"));
366 if (candidateExe.isExecutable()) {
367 return candidateExe.filePath();
368 }
369#endif
370
371 QFileInfo candidate(dir.filePath("gpgconf"));
372 if (candidate.isExecutable()) {
373 return candidate.filePath();
374 }
375 return {};
376}
377
378} // namespace
379
380auto Pass::resolveGpgconfCommand(const QString &gpgPath)
382 if (gpgPath.trimmed().isEmpty()) {
383 return {"gpgconf", {}};
384 }
385
386 // WSL: gpgconf next to the configured gpg, same distribution, via --exec
387 // not the shell. An unparsed form (`wsl sh -c ...`, bare `wsl`) falls back
388 // to gpgconf on the Windows PATH.
389 if (const auto wsl = Executor::parseWslCommand(gpgPath)) {
390 if (!QFileInfo(wsl->command).fileName().startsWith("gpg")) {
391 return {"gpgconf", {}};
392 }
393 const auto gpgconf = wsl->with(resolveWslGpgconfPath(wsl->command));
394 return {gpgconf.launcher, gpgconf.argv({})};
395 }
396
397 const QStringList parts = QProcess::splitCommand(gpgPath);
398 if (parts.isEmpty()) {
399 return {"gpgconf", {}};
400 }
401 const QString &first = parts.first();
402 if (QFileInfo(first).fileName().compare("wsl", Qt::CaseInsensitive) == 0 ||
403 QFileInfo(first).fileName().compare("wsl.exe", Qt::CaseInsensitive) ==
404 0) {
405 return {"gpgconf", {}};
406 }
407
408 if (!first.contains('/') && !first.contains('\\')) {
409 return {"gpgconf", {}};
410 }
411
412 QString gpgconfPath = findGpgconfInGpgDir(first);
413 if (!gpgconfPath.isEmpty()) {
414 return {std::move(gpgconfPath), {}};
415 }
416
417 return {"gpgconf", {}};
418}
419
420void Pass::GenerateGPGKeys(QString batch) {
421 const QString gpgPath = m_settings.gpgExecutable;
422 if (gpgPath.isEmpty()) {
423 // The executor would fail an empty executable with a generic process
424 // error; the keygen dialog waits for generateGPGKeysFailed and a reason
425 // it can show. Queued so we do not re-enter KeygenDialog::done(), which
426 // drives key generation synchronously.
427 QMetaObject::invokeMethod(
428 this,
429 [this]() {
430 emit generateGPGKeysFailed(tr("No GPG executable configured"));
431 emit processErrorExit(1, tr("No GPG executable configured"));
432 },
433 Qt::QueuedConnection);
434 return;
435 }
436
437 // A stale gpg-agent holding the key database lock causes "database locked"
438 // timeouts during key generation.
439 ResolvedGpgconfCommand resolvedGpgconf = resolveGpgconfCommand(gpgPath);
440 QStringList killArgs = resolvedGpgconf.arguments;
441 killArgs << "--kill";
442 killArgs << "gpg-agent";
443 // Use same environment as key generation to target correct gpg-agent
444 if (Executor::executeBlocking(env, resolvedGpgconf.program, killArgs) != 0) {
445 qCWarning(lcQtPass) << "Failed to kill gpg-agent";
446 }
447
448 executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
449 std::move(batch), true, true);
450}
451
452namespace {
461auto keyOfLine(const QString &line) -> QString {
462 QString key = line.trimmed();
463 if (key.endsWith(QLatin1Char('!'))) {
464 key.chop(1);
465 }
466 if (key.startsWith(QLatin1String("0x"), Qt::CaseInsensitive)) {
467 key.remove(0, 2);
468 }
469 static const QRegularExpression grouped(
470 QStringLiteral("^[0-9A-Fa-f]{4}(?:\\s+[0-9A-Fa-f]{4})+$"));
471 if (grouped.match(key).hasMatch()) {
472 static const QRegularExpression space(QStringLiteral("\\s"));
473 key.remove(space);
474 if (key.size() != 40 && key.size() != 64) {
475 return {};
476 }
477 }
478 static const QRegularExpression hex(QStringLiteral(
479 "^(?:[0-9A-Fa-f]{8}|[0-9A-Fa-f]{16}|[0-9A-Fa-f]{40}|[0-9A-Fa-f]{64})$"));
480 return hex.match(key).hasMatch() ? key.toUpper() : QString();
481}
482
487struct KeyBlock {
488 QString primary;
489 QString name;
490 QStringList keyIds;
491 QStringList fprs;
492};
493
500auto keyBlocks(const QString &listing) -> QList<KeyBlock> {
501 QList<KeyBlock> blocks;
502 bool expectPrimary = false;
503 const QStringList lines =
504 listing.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
505 for (const QString &line : lines) {
506 const QStringList f = line.split(QLatin1Char(':'));
507 const QString type = f.value(0);
508 if (type == QLatin1String("pub")) {
509 blocks.append(KeyBlock{});
510 blocks.last().keyIds << f.value(4).toUpper();
511 expectPrimary = true;
512 } else if (blocks.isEmpty()) {
513 continue;
514 } else if (type == QLatin1String("sub")) {
515 blocks.last().keyIds << f.value(4).toUpper();
516 expectPrimary = false;
517 } else if (type == QLatin1String("fpr")) {
518 const QString fpr = f.value(9).toUpper();
519 blocks.last().fprs << fpr;
520 if (expectPrimary) {
521 blocks.last().primary = fpr;
522 expectPrimary = false;
523 }
524 } else if (type == QLatin1String("uid") && blocks.last().name.isEmpty()) {
525 blocks.last().name = Util::displayable(f.value(9), false);
526 }
527 }
528 return blocks;
529}
530
537auto holderName(const KeyBlock &block) -> QString {
538 const QString id = block.primary.size() == 64 ? block.primary.left(16)
539 : block.primary.right(16);
540 return block.name.isEmpty() ? id
541 : QStringLiteral("%1 (%2)").arg(block.name, id);
542}
543} // namespace
544
545auto Pass::fullKeyListing(QString *listing) -> int {
546 // In the store's environment: the keyring encryption uses.
547 QProcess process;
548 process.setProcessEnvironment(storeEnvironment());
550 process, m_settings.gpgExecutable,
551 {QStringLiteral("--batch"), QStringLiteral("--no-tty"),
552 QStringLiteral("--with-colons"), QStringLiteral("--with-fingerprint"),
553 QStringLiteral("--with-subkey-fingerprint"),
554 QStringLiteral("--list-keys")},
555 QString(), listing);
556}
557
558auto Pass::exportPublicKeys(const QString &gpg, const QStringList &keys,
559 QString *out, QString *err) -> int {
560 QProcess process;
561 process.setProcessEnvironment(storeEnvironment());
563 process, gpg,
564 QStringList{QStringLiteral("--armor"), QStringLiteral("--export")} + keys,
565 QString(), out, err);
566}
567
568auto Pass::refuseKeyLinesHeldTwice(const QStringList &lines) -> bool {
569 const std::optional<QHash<QString, QStringList>> held =
570 keyLinesHeldTwice(lines);
571 if (held && held->isEmpty()) {
572 return false;
573 }
574 emit critical(held ? tr("A recipient key is held twice")
575 : tr("Cannot check the recipient keys"),
577 return true;
578}
579
580auto Pass::enabledKeyLines(const QList<UserInfo> &users) -> QStringList {
581 QStringList lines;
582 for (const UserInfo &user : users) {
583 if (user.enabled) {
584 lines << user.key_id;
585 }
586 }
587 return lines;
588}
589
590auto Pass::keyLinesHeldTwice(const QStringList &lines)
591 -> std::optional<QHash<QString, QStringList>> {
592 if (std::none_of(lines.cbegin(), lines.cend(), [](const QString &line) {
593 return !keyOfLine(line).isEmpty();
594 })) {
595 return QHash<QString, QStringList>();
596 }
597 QString listing;
598 const int rc = fullKeyListing(&listing);
599 // A gpg that does not start encrypts to nobody either: the operation
600 // fails on its own, as it did before this check. One that starts but
601 // cannot list its keyring is not trusted to resolve a key line.
602 if (rc == -1) {
603 return QHash<QString, QStringList>();
604 }
605 if (rc != 0) {
606 return std::nullopt;
607 }
608 return keyLinesHeldTwiceIn(lines, listing);
609}
610
611auto Pass::keyLinesHeldTwiceIn(const QStringList &lines, const QString &listing)
612 -> QHash<QString, QStringList> {
613 // The listing split once, each line looked up in it. A line with "!" is
614 // judged the same: gpg then takes exactly the key named, so it cannot be
615 // redirected to the other block's own subkey, but naming a key two blocks
616 // hold is refused all the same, which is only stricter.
617 const QList<KeyBlock> blocks = keyBlocks(listing);
618 QHash<QString, QStringList> held;
619 for (const QString &line : lines) {
620 const QString key = keyOfLine(line);
621 if (key.isEmpty()) {
622 continue;
623 }
624 const bool isId = key.size() == 8 || key.size() == 16;
625 QStringList named;
626 for (const KeyBlock &block : blocks) {
627 const bool holds =
628 isId ? std::any_of(
629 block.keyIds.cbegin(), block.keyIds.cend(),
630 [&key](const QString &id) { return id.endsWith(key); })
631 : block.fprs.contains(key);
632 if (holds) {
633 named << holderName(block);
634 }
635 }
636 if (named.size() > 1) {
637 held.insert(line, named);
638 }
639 }
640 return held;
641}
642
644 const std::optional<QHash<QString, QStringList>> &held) -> QString {
645 if (!held) {
646 return tr("gpg could not list the keyring, so QtPass cannot tell whether "
647 "each key ID and fingerprint in the recipient list names one "
648 "key. Nothing was encrypted.");
649 }
650 QStringList lines = held->keys();
651 lines.sort();
652 QStringList parts;
653 for (const QString &line : std::as_const(lines)) {
654 parts << tr("%1 is held by more than one key: %2")
655 .arg(line, held->value(line).join(QStringLiteral(", ")));
656 }
657 return parts.join(QStringLiteral("\n")) + QStringLiteral("\n\n") +
658 tr("gpg may encrypt to any of them, so nothing is encrypted to this "
659 "list. A key that holds someone else's key as a subkey was "
660 "made to do so: look at it, and delete it if you did not expect "
661 "it.");
662}
663
664auto Pass::entryReaders(const QString &path) -> QStringList {
665 // As ImitatePass::getKeysFromFile(): --decrypt --list-only, capped, so
666 // data that is not encrypted goes nowhere.
667 QProcess process;
668 process.setProcessEnvironment(storeEnvironment());
669 QString status;
671 process, m_settings.gpgExecutable,
672 {QStringLiteral("--batch"), QStringLiteral("--no-tty"),
673 QStringLiteral("--decrypt"), QStringLiteral("--list-only"),
674 QStringLiteral("--max-output"), QStringLiteral("1"),
675 QStringLiteral("--status-fd=1"),
676 QStringLiteral("--keyid-format=long"), QStringLiteral("--"),
677 Executor::translatePathForWsl(path, m_settings.gpgExecutable)},
678 QString(), &status) != 0) {
679 return {};
680 }
681 static const QRegularExpression encTo(
682 QStringLiteral("^\\[GNUPG:\\] ENC_TO ([0-9A-Fa-f]{16})(?: |$)"));
683 QStringList ids;
684 const QStringList lines =
685 status.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
686 for (const QString &line : lines) {
687 const QRegularExpressionMatch match = encTo.match(line);
688 if (match.hasMatch()) {
689 ids << match.captured(1).toUpper();
690 }
691 }
692 return ids;
693}
694
695auto Pass::exactRecipientArg(const QString &line) -> QString {
696 static const QRegularExpression bareAddress(
697 QStringLiteral("^[^=<>@*+#&\\s][^<>@\\s]*@[^<>@\\s]+$"));
698 return bareAddress.match(line).hasMatch()
699 ? QLatin1Char('<') + line + QLatin1Char('>')
700 : line;
701}
702
703auto Pass::recipientArgument(const QString &line) const -> QString {
704 return exactRecipientArg(line);
705}
706
707auto Pass::encryptionReaches(const QStringList &recipients)
708 -> std::optional<QStringList> {
709 if (recipients.isEmpty()) {
710 return std::nullopt;
711 }
712 QTemporaryDir scratch;
713 if (!scratch.isValid()) {
714 return std::nullopt;
715 }
716 const QString &gpg = m_settings.gpgExecutable;
717 const QString probe = Executor::translatePathForWsl(
718 scratch.filePath(QStringLiteral("probe.gpg")), gpg);
719 // --no-throw-keyids: with throw-keyids in gpg.conf the probe would name
720 // no one.
721 QStringList args{QStringLiteral("--batch"),
722 QStringLiteral("--no-tty"),
723 QStringLiteral("--yes"),
724 QStringLiteral("--quiet"),
725 QStringLiteral("--no-throw-keyids"),
726 QStringLiteral("--no-auto-key-locate"),
727 QStringLiteral("--no-encrypt-to"),
728 QStringLiteral("--output"),
729 probe,
730 QStringLiteral("--encrypt")};
731 for (const QString &recipient : recipients) {
732 args << QStringLiteral("-r") << recipientArgument(recipient);
733 }
734 if (Executor::executeBlocking(gpg, args, QStringLiteral("probe")) != 0) {
735 return std::nullopt;
736 }
737 // As ImitatePass::getKeysFromFile(): --decrypt --list-only, capped.
738 QString status;
740 gpg,
741 {QStringLiteral("--batch"), QStringLiteral("--no-tty"),
742 QStringLiteral("--decrypt"), QStringLiteral("--list-only"),
743 QStringLiteral("--max-output"), QStringLiteral("1"),
744 QStringLiteral("--status-fd=1"),
745 QStringLiteral("--keyid-format=long"), QStringLiteral("--"), probe},
746 QString(), &status) != 0) {
747 return QStringList();
748 }
749 static const QRegularExpression encTo(
750 QStringLiteral("^\\[GNUPG:\\] ENC_TO ([0-9A-Fa-f]{16})(?: |$)"));
751 QStringList ids;
752 const QStringList lines =
753 status.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
754 for (const QString &line : lines) {
755 const QRegularExpressionMatch match = encTo.match(line);
756 if (match.hasMatch()) {
757 ids << match.captured(1).toUpper();
758 }
759 }
760 return ids;
761}
762
763auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
764 QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
765 args.append(secret ? "--list-secret-keys" : "--list-keys");
766
767 for (const QString &keystring : std::as_const(keystrings)) {
768 if (!keystring.isEmpty()) {
769 args.append(keystring);
770 }
771 }
772 QString p_out;
773 if (Executor::executeBlocking(m_settings.gpgExecutable, args, &p_out) != 0) {
774 return {};
775 }
776 return parseGpgColonOutput(p_out, secret);
777}
778
779auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
780 return listKeys(QStringList(keystring), secret);
781}
782
783namespace {
784
785auto containsAny(const QString &str, const QStringList &patterns) -> bool {
786 for (const QString &p : patterns) {
787 if (str.contains(p)) {
788 return true;
789 }
790 }
791 return false;
792}
793
794// @p patterns must already be lowercase; only @p str is lowered.
795auto containsAnyCaseInsensitive(const QString &str, const QStringList &patterns)
796 -> bool {
797 const QString lower = str.toLower();
798 for (const QString &p : patterns) {
799 if (lower.contains(p)) {
800 return true;
801 }
802 }
803 return false;
804}
805
806} // namespace
807
808auto gpgErrorMessage(const QString &err) -> QString {
809 // Machine-readable status tokens added by --status-fd 2
810 if (containsAny(err, {QStringLiteral("[GNUPG:] KEYEXPIRED"),
811 QStringLiteral("[GNUPG:] INV_RECP 5 ")}))
812 return QCoreApplication::translate(
813 "Pass", "Encryption failed: GPG key has expired. Please renew or "
814 "replace it.");
815 if (containsAny(err, {QStringLiteral("[GNUPG:] KEYREVOKED"),
816 QStringLiteral("[GNUPG:] INV_RECP 4 ")}))
817 return QCoreApplication::translate(
818 "Pass", "Encryption failed: GPG key has been revoked.");
819 if (containsAny(err, {QStringLiteral("[GNUPG:] NO_PUBKEY"),
820 QStringLiteral("[GNUPG:] INV_RECP")}))
821 return QCoreApplication::translate(
822 "Pass", "Encryption failed: recipient GPG key not found or invalid. "
823 "Check that the key ID in .gpg-id is correct and imported.");
824 if (err.contains(QStringLiteral("[GNUPG:] FAILURE")))
825 return QCoreApplication::translate(
826 "Pass", "Encryption failed. Check that your GPG key is valid.");
827
828 // Locale-dependent fallbacks
829 if (containsAnyCaseInsensitive(err, {QLatin1String("key has expired"),
830 QLatin1String("key expired")}))
831 return QCoreApplication::translate(
832 "Pass", "Encryption failed: GPG key has expired. Please renew or "
833 "replace it.");
834 if (containsAnyCaseInsensitive(err, {QLatin1String("key has been revoked"),
835 QLatin1String("revoked")}))
836 return QCoreApplication::translate(
837 "Pass", "Encryption failed: GPG key has been revoked.");
838 // pass passes no --status-fd, so this is all gpg says about a key that is
839 // present but cannot encrypt: expired, revoked, without an encryption
840 // subkey, or not trusted ("There is no assurance this key belongs to the
841 // named user"). "Not found ... imported" would send the user the wrong
842 // way; gpg's own lines, shown below this, say which it is.
843 if (containsAnyCaseInsensitive(err, {QLatin1String("unusable public key")}))
844 return QCoreApplication::translate(
845 "Pass", "Encryption failed: a recipient's GPG key cannot be used. It "
846 "may have expired or been revoked, have no encryption subkey, "
847 "or not be trusted; gpg's message below says which.");
848 if (containsAnyCaseInsensitive(err, {QLatin1String("no public key"),
849 QLatin1String("no secret key")}))
850 return QCoreApplication::translate(
851 "Pass", "Encryption failed: recipient GPG key not found or invalid. "
852 "Check that the key ID in .gpg-id is correct and imported.");
853 if (containsAnyCaseInsensitive(err, {QLatin1String("encryption failed")}))
854 return QCoreApplication::translate(
855 "Pass", "Encryption failed. Check that your GPG key is valid.");
856
857 return {};
858}
859
860void Pass::finished(int id, int exitCode, const QString &out,
861 const QString &err) {
862 auto pid = static_cast<PROCESS>(id);
863
864 // Pop the Show() this completion belongs to whether it worked or not, or
865 // the next result would be attributed to the wrong file.
866 QString shownFile;
867 if (pid == PASS_SHOW && !m_pendingShows.isEmpty()) {
868 shownFile = m_pendingShows.dequeue();
869 }
870 // Count this insert off, success or failure, before its result goes out, so
871 // insertsPending() tracks the inserts still awaiting a report. Each insert
872 // reaches here once as PASS_INSERT.
873 // Its entry is handed out (reportedInsert()) while the report goes out.
874 QString reported;
875 if (pid == PASS_INSERT && m_insertsPending > 0) {
877 if (!m_insertedEntries.isEmpty()) {
878 reported = m_insertedEntries.dequeue();
879 }
880 }
881 m_reportedInsert = std::move(reported);
882 const auto reportedOut = qScopeGuard([this] { m_reportedInsert.clear(); });
883
884 if (exitCode != 0) {
885 handleProcessError(pid, exitCode, out, err);
886 return;
887 }
888
889 if (pid == PASS_SHOW) {
890 emit finishedShow(out, shownFile, exec.lastOutputLossless());
891 return;
892 }
893 emitProcessFinishedSignal(pid, out, err);
894}
895
896void Pass::handleProcessError(PROCESS pid, int exitCode, const QString &out,
897 const QString &err) {
898 Q_UNUSED(out);
899
900 if (pid == PASS_INSERT) {
901 const QString friendly = gpgErrorMessage(err);
902 const QString why =
903 friendly.isEmpty() ? err : formatInsertError(friendly, err);
904 const bool written = insertWritten(err);
905 emit insertFailed(why, written);
906 if (written) {
907 // The entry is in the store; a git step after it failed (a commit
908 // that could not be signed, with pass.signcommits, say). The dialog
909 // closes on this, so say it here rather than only in the output
910 // panel.
911 emit critical(tr("Saved, not committed"),
912 tr("The entry is saved in the store, but recording it "
913 "in git failed. What was reported:\n\n%1")
914 .arg(err.trimmed()));
915 }
916 emit processErrorExit(exitCode, why);
917 return;
918 }
919
920 if (pid == GPG_GENKEYS) {
921 emit generateGPGKeysFailed(err);
922 }
923 emit processErrorExit(exitCode, err);
924}
925
926auto Pass::withoutStatusLines(const QString &err) -> QString {
927 QStringList humanLines;
928 for (const QString &line : err.split('\n')) {
929 QString cleanedLine = line;
930 cleanedLine.remove('\r');
931 if (!cleanedLine.startsWith(QLatin1String("[GNUPG:]")))
932 humanLines.append(cleanedLine);
933 }
934 return humanLines.join('\n');
935}
936
937auto Pass::formatInsertError(const QString &friendly, const QString &err)
938 -> QString {
939 const QString humanErr = withoutStatusLines(err).trimmed();
940 return humanErr.isEmpty() ? friendly : friendly + "\n\n" + humanErr;
941}
942
943void Pass::emitProcessFinishedSignal(PROCESS pid, const QString &out,
944 const QString &err) {
945 // Only output that cannot contain a secret reaches the generic listeners
946 // (the output panel among them); Enums::processInfo is the one table.
947 if (pid >= 0 && pid < Enums::PROCESS_COUNT &&
948 !Enums::processInfo(pid).secret) {
949 emit finishedAnyWithPid(out, err, pid);
950 }
951
952 // The kind-specific signal. PASS_SHOW is emitted by finished(), which
953 // knows the file. Content search runs in-process (NativeGrep), not
954 // through `pass grep`, and emits finishedGrep itself.
955 using Signal = void (Pass::*)(const QString &, const QString &);
956 static const QHash<int, Signal> kSignals{
966 };
967 // A store that became a repository after updateEnv() gets its pin now,
968 // before anything is staged in it.
969 if (pid == GIT_INIT) {
971 }
972 if (const Signal signal = kSignals.value(pid, nullptr)) {
973 (this->*signal)(out, err);
974 }
975}
976
977void Pass::setEnvVar(const QString &name, const QString &value) {
978 if (value.isEmpty())
979 env.remove(name);
980 else
981 env.insert(name, value);
982}
983
985 setEnvVar(QStringLiteral("PASSWORD_STORE_SIGNING_KEY"),
987 setEnvVar(QStringLiteral("PASSWORD_STORE_DIR"), m_settings.passStore);
988 // Every path QtPass hands git names one file or folder: an entry called
989 // "a*.gpg" must not make `git rm -f -- a*.gpg` remove every entry that
990 // matches. Also reaches the git that pass runs, which passes names the
991 // same way.
992 setEnvVar(QStringLiteral("GIT_LITERAL_PATHSPECS"), QStringLiteral("1"));
993
995 setEnvVar(QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH"),
996 QString::number(passConfig.length));
997
998 setEnvVar(QStringLiteral("PASSWORD_STORE_CHARACTER_SET"),
999 effectiveCharset(passConfig));
1000
1001 // pass hands PASSWORD_STORE_GPG_OPTS to every gpg it runs: the user's own
1002 // options (split as pass's shell splits them: spaces, tabs, newlines),
1003 // then the output limit ImitatePass passes directly.
1004 static const QRegularExpression whitespace(QStringLiteral("\\s+"));
1005 QStringList gpgOpts = QProcessEnvironment::systemEnvironment()
1006 .value(QStringLiteral("PASSWORD_STORE_GPG_OPTS"))
1007 .split(whitespace, Qt::SkipEmptyParts);
1008 gpgOpts << maxOutputArgs();
1009 setEnvVar(QStringLiteral("PASSWORD_STORE_GPG_OPTS"),
1010 gpgOpts.join(QLatin1Char(' ')));
1011
1012 // As pass does: git never looks for a repository above the store's own
1013 // parent. A store that is not a repository itself but lies inside one (a
1014 // dotfiles repository in the home folder) would otherwise have its entries
1015 // committed and pushed there by native git mode. Only in the environment
1016 // of the processes QtPass runs for the store, never QtPass's own, which a
1017 // file manager or terminal it opens would inherit. pass sets its own
1018 // ceiling whatever this says. A store kept inside a larger repository on
1019 // purpose opts out (gitUseParentRepository), and then, as without a
1020 // store, whatever ceiling QtPass was started with applies.
1021 // A ceiling git cannot take as one entry (the parent's path holds the
1022 // list separator) is backed by GIT_DIR and GIT_WORK_TREE naming the
1023 // store's own repository (Util::gitStoreVariables()); pass unsets those
1024 // for itself and keeps its own ceiling.
1025 setEnvVar(QStringLiteral("GIT_DIR"), QString());
1026 setEnvVar(QStringLiteral("GIT_WORK_TREE"), QString());
1028 setEnvVar(QStringLiteral("GIT_CEILING_DIRECTORIES"),
1029 qEnvironmentVariable("GIT_CEILING_DIRECTORIES"));
1030 } else {
1031 const auto variables =
1033 for (const auto &[name, value] : variables) {
1034 setEnvVar(name, value);
1035 }
1036 }
1037
1038 // Refuse a repository pushed into the store: git started in a folder laid
1039 // out as a bare repository would read its pushed config and run a command
1040 // named there. This reaches the git that pass runs too, which inherits the
1041 // environment.
1043 // pass under WSL needs them too: the count and every entry below it.
1044 QStringList gitConfig{QStringLiteral("GIT_CONFIG_COUNT/u")};
1045 if (env.contains(QStringLiteral("GIT_CONFIG_PARAMETERS"))) {
1046 gitConfig << QStringLiteral("GIT_CONFIG_PARAMETERS/u");
1047 }
1048 const int gitConfigCount =
1049 env.value(QStringLiteral("GIT_CONFIG_COUNT")).toInt();
1050 for (int i = 0; i < gitConfigCount; ++i) {
1051 gitConfig << QStringLiteral("GIT_CONFIG_KEY_%1/u").arg(i)
1052 << QStringLiteral("GIT_CONFIG_VALUE_%1/u").arg(i);
1053 }
1054 mergeIntoWslenv(env, gitConfig);
1055
1057
1059}
1060
1061namespace {
1070auto userAttributeLines(const QString &existing, const QString &marker)
1071 -> QString {
1072 QString preserved;
1073 if (existing.isEmpty()) {
1074 return preserved;
1075 }
1076 const QStringList lines = existing.split(QLatin1Char('\n'));
1077 bool inBlock = false;
1078 for (const QString &line : lines) {
1079 if (line == marker) {
1080 inBlock = true;
1081 continue;
1082 }
1083 if (inBlock) {
1084 if (line.startsWith(QStringLiteral("*.gpg ")) ||
1085 line.startsWith(QStringLiteral(".gpg-id ")) ||
1086 line.startsWith(QStringLiteral(".gpg-id.sig "))) {
1087 continue;
1088 }
1089 inBlock = false;
1090 }
1091 preserved += line + QLatin1Char('\n');
1092 }
1093 while (preserved.endsWith(QStringLiteral("\n\n"))) {
1094 preserved.chop(1);
1095 }
1096 return preserved;
1097}
1098} // namespace
1099
1101 if (m_settings.passStore.isEmpty()) {
1102 return;
1103 }
1104 // Only the common layout, where the store is its own repository, is handled
1105 // by writing directly: a ".git" directory. A worktree ".git" file or a store
1106 // nested in a larger repository is left as-is rather than risk touching
1107 // another repository's attributes.
1108 const QString gitDir =
1109 QDir(m_settings.passStore).absoluteFilePath(QStringLiteral(".git"));
1110 if (!QFileInfo(gitDir).isDir()) {
1111 return;
1112 }
1113
1114 // The marker lets us recognise and refresh our own block without disturbing
1115 // anything a user put in info/attributes by hand. Disabling text/eol,
1116 // working-tree-encoding, filter and ident keeps Git from rewriting the
1117 // bytes gpg produced for these paths - a co-writer can push a .gitattributes
1118 // ("*.gpg text", a working-tree-encoding, a filter) that otherwise corrupts
1119 // the ciphertext QtPass commits. info/attributes outranks the in-tree file.
1120 // diff is left alone: it only changes what Git shows, and pass's own
1121 // "*.gpg diff=gpg" gives decrypted diffs.
1122 static const QString marker =
1123 QStringLiteral("# QtPass: keep encrypted store files byte-for-byte");
1124 const QString block =
1125 marker + QStringLiteral("\n") +
1126 QStringLiteral(
1127 "*.gpg -text -filter -ident -working-tree-encoding\n"
1128 ".gpg-id -text -filter -ident -working-tree-encoding\n"
1129 ".gpg-id.sig -text -filter -ident -working-tree-encoding\n");
1130
1131 const QString infoDir = gitDir + QStringLiteral("/info");
1132 const QString attrPath = infoDir + QStringLiteral("/attributes");
1133
1134 QString existing;
1135 QFile attr(attrPath);
1136 if (attr.exists()) {
1137 // Unreadable: writing now would drop the user's own lines in it.
1138 if (!attr.open(QIODevice::ReadOnly | QIODevice::Text)) {
1139 qCWarning(lcQtPass) << "Cannot read" << attrPath
1140 << "to pin attributes:" << attr.errorString();
1141 return;
1142 }
1143 existing = QString::fromUtf8(attr.readAll());
1144 attr.close();
1145 if (existing.contains(block)) {
1146 return; // already pinned and unchanged
1147 }
1148 }
1149
1150 if (!QDir().mkpath(infoDir)) {
1151 qCWarning(lcQtPass) << "Cannot create" << infoDir << "to pin attributes";
1152 return;
1153 }
1154
1155 // Keep any lines the user added themselves (outside our block), then append a
1156 // fresh copy of our block. A previous QtPass block is dropped so an updated
1157 // set of lines replaces an older one.
1158 const QString preserved = userAttributeLines(existing, marker);
1159
1160 QSaveFile out(attrPath);
1161 const QByteArray payload = (preserved + block).toUtf8();
1162 if (!out.open(QIODevice::WriteOnly | QIODevice::Text) ||
1163 out.write(payload) != payload.size() || !out.commit()) {
1164 qCWarning(lcQtPass) << "Cannot write" << attrPath
1165 << "to pin attributes:" << out.errorString();
1166 }
1167}
1168
1169auto Pass::withCurrentGitPin(QProcessEnvironment base) const
1170 -> QProcessEnvironment {
1171 if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
1172 return base;
1173 }
1174 base.remove(QStringLiteral("GIT_DIR"));
1175 base.remove(QStringLiteral("GIT_WORK_TREE"));
1176 const auto variables =
1177 Util::gitStoreVariables(m_settings.passStore, m_settings.gitExecutable);
1178 for (const auto &[name, value] : variables) {
1179 base.insert(name, value);
1180 }
1181 return base;
1182}
1183
1184auto Pass::maxOutputArgs() -> QStringList {
1185 return {QStringLiteral("--max-output"), QString::number(kMaxPlaintextBytes)};
1186}
1187
1188namespace {
1191#ifdef Q_OS_WIN
1192constexpr auto kPathCase = Qt::CaseInsensitive;
1193#else
1194constexpr auto kPathCase = Qt::CaseSensitive;
1195#endif
1196
1198auto isAtOrUnder(const QString &path, const QString &dir,
1199 const QString &dirPrefix) -> bool {
1200 return path.compare(dir, kPathCase) == 0 ||
1201 path.startsWith(dirPrefix, kPathCase);
1202}
1203
1205struct GpgIdLookup {
1206 QDir start;
1208 QString folder;
1209 QString storeDir;
1210 QString storePrefix;
1211};
1212
1215auto gpgIdLookup(const QString &for_file, const QString &passStore)
1216 -> GpgIdLookup {
1217 const QString normalizedFile = QDir::fromNativeSeparators(for_file);
1218 // Inside the store means at a path boundary: "/store-other/x" is not
1219 // under "/store", however the prefix compares.
1220 const QString storeDir =
1221 QDir::cleanPath(QDir::fromNativeSeparators(passStore));
1222 const QString storePrefix = storeDir.endsWith(QLatin1Char('/'))
1223 ? storeDir
1224 : storeDir + QLatin1Char('/');
1225 const QString cleanFile = QDir::cleanPath(normalizedFile);
1226 const bool insideStore = isAtOrUnder(cleanFile, storeDir, storePrefix);
1227 // A relative name is one inside the store; an absolute path outside it
1228 // stays what it is and the walk stops at once.
1229 const QString fullPath =
1230 insideStore || (QDir::isAbsolutePath(cleanFile) &&
1231 !cleanFile.startsWith(QLatin1Char(':')))
1232 ? cleanFile
1233 : storePrefix + cleanFile;
1234 // A folder (trailing separator, which cleanPath() dropped, or an existing
1235 // directory) wants its own list; an entry wants its folder's.
1236 const bool isFolder =
1237 normalizedFile.endsWith(QLatin1Char('/')) || QFileInfo(fullPath).isDir();
1238 // A folder that does not exist yet (an entry saved into a new folder, a
1239 // move to one) starts the walk at its nearest existing ancestor in the
1240 // store, as pass's set_gpg_recipients does: otherwise the walk ended at
1241 // once and the store root's list was taken over the one in between.
1242 const QString folder =
1243 QDir::cleanPath(isFolder ? fullPath : QFileInfo(fullPath).absolutePath());
1244 QString start = folder;
1245 while (!QFileInfo::exists(start) &&
1246 isAtOrUnder(QDir::cleanPath(start), storeDir, storePrefix) &&
1247 QDir::cleanPath(start) != storeDir) {
1248 start = QFileInfo(start).absolutePath();
1249 }
1250 return {QDir(start), folder, storeDir, storePrefix};
1251}
1252
1257auto isOwnGpgId(const QFileInfo &candidate) -> bool {
1258 return candidate.isFile() && !candidate.isSymLink() &&
1259 !candidate.isJunction();
1260}
1261
1265auto nearestGpgId(const GpgIdLookup &lookup) -> std::optional<QString> {
1266 QDir dir = lookup.start;
1267 while (dir.exists() && isAtOrUnder(QDir::cleanPath(dir.absolutePath()),
1268 lookup.storeDir, lookup.storePrefix)) {
1269 const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
1270 if (isOwnGpgId(candidate)) {
1271 return candidate.absoluteFilePath();
1272 }
1273 if (!dir.cdUp()) {
1274 break;
1275 }
1276 }
1277 return std::nullopt;
1278}
1279
1280} // namespace
1281
1282auto Pass::heldScopes() -> QSet<QString> & {
1283 static QSet<QString> scopes;
1284 return scopes;
1285}
1286
1287auto Pass::scopePath(const QString &path) const -> QString {
1288 return QDir::cleanPath(QDir(m_settings.passStore).absoluteFilePath(path));
1289}
1290
1291auto Pass::autoPushHeld() const -> bool {
1292 const QString store = scopePath(QString());
1293 const QSet<QString> &scopes = heldScopes();
1294 return std::any_of(scopes.cbegin(), scopes.cend(),
1295 [&store](const QString &s) {
1296 return isAtOrUnder(s, store, store + QLatin1Char('/'));
1297 });
1298}
1299
1301 m_pushIsAutomatic = true;
1302 GitPush();
1303 m_pushIsAutomatic = false;
1304}
1305
1306auto Pass::pushIsAutomatic() const -> bool { return m_pushIsAutomatic; }
1307
1308void Pass::holdAutoPush(const QString &scope) {
1309 heldScopes().insert(scopePath(scope));
1310}
1311
1312void Pass::releaseAutoPush(const QString &folder) {
1313 const QString root = scopePath(folder);
1314 QSet<QString> &scopes = heldScopes();
1315 for (auto it = scopes.begin(); it != scopes.end();) {
1316 it = isAtOrUnder(*it, root, root + QLatin1Char('/')) ? scopes.erase(it)
1317 : std::next(it);
1318 }
1319}
1320
1321auto Pass::refuseLinkedPath(const QString &path, LinkScope scope,
1322 PathSpelling spelling) -> bool {
1323 const QString full = Util::joinPath(m_settings.passStore, path);
1324 // The link check below walks only under the store as configured: a path
1325 // spelled through the root's link target would get no more than the
1326 // entry itself judged. No caller makes one; say so if one starts to.
1327 if (spelling == PathSpelling::Configured &&
1328 PathValidator::isTargetSpelled(m_settings.passStore, full)) {
1329 qCWarning(lcQtPass)
1330 << "Path spelled through the store root's link target, not as the "
1331 "store is configured; Pass operations expect the configured "
1332 "spelling:"
1333 << full;
1334 }
1335 if (!Util::isUnderLink(full, m_settings.passStore,
1336 scope == LinkScope::EntryAndParents)) {
1337 return false;
1338 }
1339 const QString why =
1340 tr("%1 is, or lies behind, a symbolic link or junction. What that "
1341 "points to is not part of the password store and is left alone.")
1342 .arg(QDir::toNativeSeparators(QDir::cleanPath(full)));
1344 return true;
1345}
1346
1347auto Pass::refuseFolderOutsideStore(const QString &folder, QString *relative)
1348 -> bool {
1349 if (const std::optional<QString> inStore =
1350 PathValidator::storeRelativePath(m_settings.passStore, folder)) {
1351 if (relative != nullptr) {
1352 *relative = *inStore;
1353 }
1354 return false;
1355 }
1357 tr("%1 is not inside the password store. Recipients are set for the "
1358 "store or a folder in it.")
1359 .arg(QDir::toNativeSeparators(QDir::cleanPath(folder))));
1360 return true;
1361}
1362
1364 if (!m_settings.useGit) {
1365 return {};
1366 }
1367 // One git call names the path of each marker file or directory, whether or
1368 // not it exists; the backend runs it in the store (ImitatePass with
1369 // `-C <store>`, RealPass through `pass git`). The markers, paired with the
1370 // operation each one means, in the order git prints them back.
1371 // The names are Git's own commands, which the user then runs with --abort or
1372 // --continue; the translator comments say so.
1373 const std::array<std::pair<QLatin1String, QString>, 6> markers{{
1374 //: The Git command `git rebase`, inserted into "in the middle of a %1".
1375 //: Best kept as Git's command name.
1376 {QLatin1String("rebase-merge"), tr("rebase")},
1377 //: The Git command `git rebase`, inserted into "in the middle of a %1".
1378 //: Best kept as Git's command name.
1379 {QLatin1String("rebase-apply"), tr("rebase")},
1380 //: The Git command `git merge`, inserted into "in the middle of a %1".
1381 //: Best kept as Git's command name.
1382 {QLatin1String("MERGE_HEAD"), tr("merge")},
1383 //: The Git command `git cherry-pick`, inserted into "in the middle of a
1384 //: %1". Best kept as Git's command name.
1385 {QLatin1String("CHERRY_PICK_HEAD"), tr("cherry-pick")},
1386 //: The Git command `git revert`, inserted into "in the middle of a %1".
1387 //: Best kept as Git's command name.
1388 {QLatin1String("REVERT_HEAD"), tr("revert")},
1389 // A multi-commit cherry-pick or revert keeps its sequencer state after a
1390 // conflict resolution is committed, when CHERRY_PICK_HEAD/REVERT_HEAD is
1391 // already gone but `--continue` has more commits to apply. Checked last,
1392 // so the specific head above names the operation when it is still there.
1393 //: The Git commands `git cherry-pick` and `git revert`, inserted into
1394 //: "in the middle of a %1". Best kept as Git's command names.
1395 {QLatin1String("sequencer"), tr("cherry-pick or revert")},
1396 }};
1397 QStringList args{QStringLiteral("rev-parse")};
1398 for (const auto &marker : markers) {
1399 args << QStringLiteral("--git-path") << marker.first;
1400 }
1401 QString out;
1402 if (!storeGit(args, &out)) {
1403 // Git is off, the store is not a repository, or git could not be asked:
1404 // nothing is refused, as the operation would run anyway.
1405 return {};
1406 }
1407 const QStringList paths = out.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
1408 for (int i = 0; i < paths.size() && i < static_cast<int>(markers.size());
1409 ++i) {
1410 const QString path = paths.at(i).trimmed();
1411 const QString full = QDir::isAbsolutePath(path)
1412 ? path
1413 : QDir(m_settings.passStore).filePath(path);
1414 if (!QFileInfo::exists(full)) {
1415 continue;
1416 }
1417 //: %1 is a Git command name: rebase, merge, cherry-pick, revert, or
1418 //: "cherry-pick or revert".
1419 return tr("The password store's Git repository is in the middle of a %1. "
1420 "Finish or abort it with Git before changing the password store, "
1421 "or what you change may be lost.")
1422 .arg(markers.at(static_cast<size_t>(i)).second);
1423 }
1424 return {};
1425}
1426
1428 if (!m_settings.useGit || !exec.hasQueued(Enums::GIT_PULL)) {
1429 return false;
1430 }
1431 const QString why =
1432 tr("The password store is being updated (a Git pull is in progress). "
1433 "Wait until it has finished, then try again.");
1434 // Like refuseAsNotPartOfStore(): the interface arms when an operation starts
1435 // and is released by processErrorExit(); a refusal starts nothing.
1437 emit critical(tr("Update in progress"), why);
1438 emit processErrorExit(1, why);
1439 return true;
1440}
1441
1442auto Pass::initIfUnchanged(const QString &path, const QList<UserInfo> &users,
1443 const QString &dir, const QString &passStore,
1444 const RecipientsForEditing &read) -> bool {
1445 m_expectedList = ExpectedList{dir, passStore, read.state, read.recipients};
1446 m_expectedListRefused = false;
1447 const auto done = qScopeGuard([this] { m_expectedList.reset(); });
1448 Init(path, users);
1449 return !m_expectedListRefused;
1450}
1451
1453 if (!m_expectedList) {
1454 return false;
1455 }
1456 // A copy: recipientsForEditing() is a member call, after which the
1457 // optional cannot be known to hold a value any more.
1458 const ExpectedList expected = *m_expectedList;
1459 const RecipientsForEditing now =
1460 recipientsForEditing(expected.dir, expected.passStore);
1461 if (now.state == expected.state && now.recipients == expected.recipients) {
1462 return false;
1463 }
1464 const QString why =
1465 tr("The recipient list of this folder changed after the users dialog "
1466 "read it, for example through an update from Git. Nothing was "
1467 "written. Open the dialog again to see the new list.");
1468 m_expectedListRefused = true;
1470 emit critical(tr("Recipients not changed"), why);
1471 emit processErrorExit(1, why);
1472 return true;
1473}
1474
1476 if (!m_expectedList || exec.isIdle()) {
1477 return false;
1478 }
1479 const QString why =
1480 tr("Another operation is still running. Wait until it has finished, "
1481 "then save the recipients again.");
1482 m_expectedListRefused = true;
1484 emit critical(tr("Recipients not changed"), why);
1485 emit processErrorExit(1, why);
1486 return true;
1487}
1488
1490 const QString why = unfinishedGitOperationReason();
1491 if (why.isEmpty()) {
1492 return false;
1493 }
1494 // Like refuseAsNotPartOfStore(): the interface arms when an operation starts
1495 // and is released by finished()/processErrorExit(); a refusal starts
1496 // nothing, so it emits both ends.
1498 emit critical(tr("Unfinished Git operation"), why);
1499 emit processErrorExit(1, why);
1500 return true;
1501}
1502
1503void Pass::refuseAsNotPartOfStore(const QString &why) {
1504 // The interface arms itself when an operation starts and is released by
1505 // finished or processErrorExit; a refusal starts nothing, so emits both.
1507 emit critical(tr("Not part of the store"), why);
1508 emit processErrorExit(1, why);
1509}
1510
1511auto Pass::getGpgIdPath(const QString &for_file, const QString &passStore)
1512 -> QString {
1513 return nearestGpgId(gpgIdLookup(for_file, passStore))
1514 .value_or(
1515 QDir(QDir::fromNativeSeparators(passStore)).filePath(".gpg-id"));
1516}
1517
1518auto Pass::refuseSkippedGpgId(const QString &file, bool signing,
1519 const QString &except, SkippedWalks *walks)
1520 -> bool {
1521 // Without a signing key the parent's list applies, as it does for pass.
1522 if (!signing) {
1523 return false;
1524 }
1525 QString recordError;
1526 const std::optional<QString> skipped =
1527 skippedGpgId(file, m_settings.passStore, &recordError, walks);
1528 if (!skipped || (!except.isEmpty() &&
1529 QDir::cleanPath(*skipped) == QDir::cleanPath(except))) {
1530 return false;
1531 }
1532 // The strings keep the context they were translated in.
1533 if (!recordError.isEmpty()) {
1534 emit critical(QCoreApplication::translate(
1535 "ImitatePass", "Cannot check the recipient list"),
1536 QCoreApplication::translate(
1537 "ImitatePass", "%1 Whether %2 was removed cannot be "
1538 "told, so nothing was encrypted.")
1539 .arg(recordError, QDir::toNativeSeparators(*skipped)));
1540 return true;
1541 }
1542 emit critical(
1543 QCoreApplication::translate("ImitatePass", "Recipient list missing"),
1544 QCoreApplication::translate(
1545 "ImitatePass",
1546 "The signed recipient list %1 is missing or is not a regular file. "
1547 "QtPass does not fall back to a parent folder's list for it: that "
1548 "list was not signed for this folder. If a link is under that name, "
1549 "remove it. Then open Users for that folder and save its "
1550 "recipients, which writes and signs a fresh list.")
1551 .arg(QDir::toNativeSeparators(*skipped)));
1552 return true;
1553}
1554
1555auto Pass::verifySignedList(const GpgIdSigner &signer, const QString &gpgIdFile,
1556 QByteArray *contents, QString *why) const -> bool {
1557 if (!signer.verifyFile(gpgIdFile, contents)) {
1558 // A good signature refused for its key (held by two key blocks) says
1559 // why, and what to do.
1560 if (why != nullptr && !signer.refusal().isEmpty()) {
1561 *why = signer.refusal();
1562 }
1563 return false;
1564 }
1565 // Authentic and unmodified is not the same as current: an older signed
1566 // list put back into the store is refused once this device has seen a
1567 // newer one, and one signed for another folder is refused here.
1568 QString reason;
1569 if (GpgIdGeneration::accept(gpgIdFile, *contents, m_settings.passStore,
1571 if (why != nullptr) {
1572 *why = std::move(reason);
1573 }
1574 return false;
1575 }
1576 return true;
1577}
1578
1579auto Pass::gpgIdVerdictIn(const QString &dir) -> std::optional<SkippedWalk> {
1580 const QFileInfo candidate(dir + QStringLiteral("/.gpg-id"));
1581 if (isOwnGpgId(candidate)) {
1582 return SkippedWalk{std::nullopt, QString()};
1583 }
1584 // A link under the name (dangling or not), or nothing under it where
1585 // this device accepted a list before: both are the folder's list gone,
1586 // not a folder that never had one.
1587 if (candidate.isSymLink() || candidate.isJunction()) {
1588 return SkippedWalk{candidate.absoluteFilePath(), QString()};
1589 }
1590 // An unreadable record is not "never seen": whether a list was accepted
1591 // here cannot be told, so this folder is refused too (fail closed), with
1592 // the record's own reason for the caller to show.
1593 QString why;
1594 const std::optional<bool> seen =
1595 GpgIdGeneration::seen(candidate.absoluteFilePath(), &why);
1596 if (!seen) {
1597 return SkippedWalk{candidate.absoluteFilePath(),
1598 why.isEmpty()
1599 ? tr("The generation record of the recipient lists "
1600 "cannot be read.")
1601 : why};
1602 }
1603 if (*seen) {
1604 return SkippedWalk{candidate.absoluteFilePath(), QString()};
1605 }
1606 return std::nullopt;
1607}
1608
1609auto Pass::skippedGpgId(const QString &forFile, const QString &passStore,
1610 QString *recordError, SkippedWalks *walks)
1611 -> std::optional<QString> {
1612 const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
1613 // A folder's answer depends only on it and the folders above it: kept
1614 // for every folder climbed, a tree check asks each one record lookup,
1615 // where climbing again from every folder cost depth squared.
1616 QStringList climbed;
1617 // By value: on a hit they come out of walks, which the inserts below
1618 // may rehash.
1619 // NOLINTBEGIN(performance-unnecessary-value-param): by value, see above.
1620 const auto answer = [&climbed, walks, recordError](
1621 std::optional<QString> skipped, QString why) {
1622 // NOLINTEND(performance-unnecessary-value-param)
1623 if (walks != nullptr) {
1624 for (const QString &folder : std::as_const(climbed)) {
1625 walks->insert(folder, {skipped, why});
1626 }
1627 }
1628 if (recordError != nullptr && !why.isEmpty()) {
1629 *recordError = std::move(why);
1630 }
1631 return skipped;
1632 };
1633 // The same walk as nearestGpgId(), stopping at the list it finds, and
1634 // short of the store root: the root's own list has no parent to fall
1635 // back to, and the signature check refuses it when it is missing. It
1636 // starts at the folder asked for, not at its nearest existing one: a
1637 // folder removed together with its list is asked of the record too.
1638 QString dir = lookup.folder;
1639 while (dir.startsWith(lookup.storePrefix, kPathCase)) {
1640 if (walks != nullptr) {
1641 if (const auto known = walks->constFind(dir);
1642 known != walks->constEnd()) {
1643 return answer(known->skipped, known->recordError);
1644 }
1645 }
1646 climbed << dir;
1647 if (const std::optional<SkippedWalk> found = gpgIdVerdictIn(dir)) {
1648 return answer(found->skipped, found->recordError);
1649 }
1650 const QString parent = QDir::cleanPath(QFileInfo(dir).absolutePath());
1651 if (parent == dir) {
1652 break;
1653 }
1654 dir = parent;
1655 }
1656 return answer(std::nullopt, QString());
1657}
1658
1659auto Pass::linkedGpgId(const QString &forFile, const QString &passStore,
1660 LinkedWalks *walks) -> std::optional<QString> {
1661 const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
1662 // As in skippedGpgId(): a folder's answer depends only on it and the
1663 // folders above it, so a tree check climbs each folder once instead of
1664 // once per folder below it.
1665 QStringList climbed;
1666 const auto answer = [&climbed, walks](std::optional<QString> linked) {
1667 if (walks != nullptr) {
1668 for (const QString &folder : std::as_const(climbed)) {
1669 walks->insert(folder, linked);
1670 }
1671 }
1672 return linked;
1673 };
1674 // The walk of nearestGpgId(), root included, stopping at the list it
1675 // finds.
1676 QDir dir = lookup.start;
1677 while (dir.exists()) {
1678 const QString here = QDir::cleanPath(dir.absolutePath());
1679 if (!isAtOrUnder(here, lookup.storeDir, lookup.storePrefix)) {
1680 break;
1681 }
1682 if (walks != nullptr) {
1683 // By value: the inserts in answer() may rehash walks.
1684 if (const auto known = walks->constFind(here);
1685 known != walks->constEnd()) {
1686 return answer(std::optional<QString>(*known));
1687 }
1688 }
1689 climbed << here;
1690 const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
1691 if (isOwnGpgId(candidate)) {
1692 return answer(std::nullopt);
1693 }
1694 if (candidate.isSymLink() || candidate.isJunction()) {
1695 return answer(candidate.absoluteFilePath());
1696 }
1697 if (!dir.cdUp()) {
1698 break;
1699 }
1700 }
1701 return answer(std::nullopt);
1702}
1703
1704namespace {
1705
1708auto judgedRecipients(GpgIdGeneration::Verdict verdict,
1709 const QByteArray &contents, const QString &gpgIdPath,
1710 const QString &why) -> Pass::RecipientsForEditing {
1711 using RecipientsForEditing = Pass::RecipientsForEditing;
1712 RecipientsForEditing result;
1713 switch (verdict) {
1715 result.state = RecipientsForEditing::State::Verified;
1716 result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1717 break;
1719 // Authentic and this folder's, only older: the recovery goes through
1720 // this dialog, so it is preselected, with the reason in view.
1721 result.state = RecipientsForEditing::State::VerifiedRollback;
1722 result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1723 result.warning = why;
1724 break;
1731 // Signed, but not shown to be this folder's list, not a list to trust,
1732 // or nothing to judge it by: preselecting it would sign it in.
1733 result.state = RecipientsForEditing::State::Rejected;
1734 result.warning =
1735 Pass::tr("%1 Nothing is preselected: saving would sign whatever is "
1736 "in it. Select the recipients yourself.")
1737 .arg(why);
1738 break;
1739 }
1740 return result;
1741}
1742
1743} // namespace
1744
1745auto Pass::recipientsForEditing(const QString &dir, const QString &passStore)
1747 RecipientsForEditing result;
1748 const QString folder = dir.isEmpty() ? QString() : dir;
1749 const QString gpgIdPath = getGpgIdPath(folder, passStore);
1750 GpgIdSigner signer(m_settings.gpgExecutable,
1752 signer.setStoreRoot(passStore);
1753 if (!signer.enabled()) {
1754 // A list that is there but cannot be read as one (too large, not a
1755 // regular file, unreadable) is not an empty list: preselecting nothing
1756 // without a word would let OK write a new list over it, and later
1757 // re-encryptions drop whoever it named.
1758 // Read once and parsed from those bytes: a second read could find
1759 // something else under the name. A link counts as there, dangling too.
1760 const QFileInfo info(gpgIdPath);
1761 if (!info.exists() && !info.isSymLink()) {
1763 return result;
1764 }
1765 const std::optional<QByteArray> bytes = Util::readRegularFileInStore(
1766 passStore, gpgIdPath, Util::kMaxGpgIdBytes);
1767 if (!bytes) {
1769 result.warning =
1770 tr("%1 cannot be read as a recipient list (a regular file of at "
1771 "most %2), so nothing is preselected. Check it before choosing "
1772 "recipients here: OK writes a new list over it.")
1773 .arg(gpgIdPath,
1774 QLocale().formattedDataSize(Util::kMaxGpgIdBytes));
1775 return result;
1776 }
1778 result.recipients = parseRecipients(*bytes, gpgIdPath);
1779 const QString misread = passReadsDifferently(*bytes);
1780 if (!misread.isEmpty()) {
1781 //: %1 is the list's path, %2 says what is wrong with it.
1782 result.warning =
1783 tr("pass reads %1 differently from this dialog (%2), so it may "
1784 "encrypt to recipients not shown here. QtPass will not encrypt "
1785 "with it through pass: check the recipients, then OK writes the "
1786 "list anew.")
1787 .arg(gpgIdPath, misread);
1788 }
1789 return result;
1790 }
1791 QString recordError;
1792 if (const std::optional<QString> skipped =
1793 skippedGpgId(folder, passStore, &recordError)) {
1794 // The folder's own list was removed or replaced by a link (or the record
1795 // that would tell cannot be read): the list the walk found further up
1796 // was not signed for this folder, so preselecting it would sign it in
1797 // here with one click.
1799 result.warning =
1800 recordError.isEmpty()
1801 ? tr("The recipient list %1 is missing or is not a regular file, "
1802 "so nothing is preselected: the list of a parent folder was "
1803 "not signed for this one. Select this folder's recipients "
1804 "yourself; OK writes and signs a fresh list.")
1805 .arg(*skipped)
1806 : tr("%1 Nothing is preselected: whether %2 was removed cannot "
1807 "be told.")
1808 .arg(recordError, *skipped);
1809 return result;
1810 }
1811 if (!QFileInfo::exists(gpgIdPath)) {
1812 // A folder without a list yet (new store, new profile): nothing to
1813 // verify and nothing to preselect.
1815 return result;
1816 }
1817 QByteArray contents;
1818 if (!signer.verifyFile(gpgIdPath, &contents)) {
1820 result.warning =
1821 tr("The recipient list %1 does not verify against the signing key, "
1822 "so nothing is preselected: saving would sign whatever is in it. "
1823 "Select the recipients yourself; OK writes and signs a fresh list.")
1824 .arg(gpgIdPath);
1825 return result;
1826 }
1827 QString why;
1828 const GpgIdGeneration::Verdict verdict =
1829 GpgIdGeneration::accept(gpgIdPath, contents, passStore, &why);
1830 return judgedRecipients(verdict, contents, gpgIdPath, why);
1831}
1832
1833auto Pass::getRecipientList(const QString &for_file, const QString &passStore)
1834 -> QStringList {
1835 const QString gpgIdPath = getGpgIdPath(for_file, passStore);
1836 // The root .gpg-id comes back whatever it is; a link is not a list.
1837 if (Util::isLinkedFolder(gpgIdPath)) {
1838 return {};
1839 }
1840 const std::optional<QByteArray> bytes =
1842 if (!bytes) {
1843 return {};
1844 }
1845 return parseRecipients(*bytes, gpgIdPath);
1846}
1847
1848auto Pass::parseRecipients(const QByteArray &contents,
1849 const QString &sourceName) -> QStringList {
1850 QStringList recipients;
1851 const QString text = QString::fromUtf8(contents);
1852 for (const QString &line : text.split(QLatin1Char('\n'))) {
1853 QString recipient = line.split(QLatin1Char('#')).first().trimmed();
1854 if (recipient.isEmpty()) {
1855 continue;
1856 }
1857 if (!Util::isValidKeyId(recipient)) {
1858 // Never drop a recipient silently: the list is written back verbatim
1859 // by UsersDialog, so a skipped line disappears from .gpg-id.
1860 qCWarning(lcQtPass) << "Skipping unusable recipient in" << sourceName
1861 << ":" << recipient;
1862 continue;
1863 }
1864 recipients += recipient;
1865 }
1866 return recipients;
1867}
1868
1869auto Pass::passReadsDifferently(const QByteArray &contents) -> QString {
1870 if (contents.startsWith("\xEF\xBB\xBF")) {
1871 return tr("it starts with a byte-order mark");
1872 }
1873 if (contents.contains('\0')) {
1874 return tr("it holds a NUL byte");
1875 }
1876 if (contents.contains('\r')) {
1877 return tr("it has Windows line ends (a carriage return)");
1878 }
1879 const QString text = QString::fromUtf8(contents);
1880 if (text.toUtf8() != contents) {
1881 return tr("it is not valid UTF-8");
1882 }
1883 const QStringList lines = text.split(QLatin1Char('\n'));
1884 for (qsizetype i = 0; i < lines.size(); ++i) {
1885 const QString &line = lines.at(i);
1886 const QString recipient = line.left(line.indexOf(QLatin1Char('#')));
1887 for (const QChar c : recipient) {
1888 // read strips blanks and tabs; trimmed() strips every space.
1889 if (c.isSpace() && c != QLatin1Char(' ') && c != QLatin1Char('\t')) {
1890 return tr("line %1 holds whitespace other than blanks and tabs")
1891 .arg(i + 1);
1892 }
1893 }
1894 const QString trimmed = recipient.trimmed();
1895 if (trimmed.startsWith(QLatin1Char('-'))) {
1896 return tr("line %1 starts with a dash").arg(i + 1);
1897 }
1898 // The text after the last line feed: read hands it over but the loop
1899 // ends without using it.
1900 if (i == lines.size() - 1 && !trimmed.isEmpty()) {
1901 return tr("its last line has no line end");
1902 }
1903 }
1904 return {};
1905}
1906
1907/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
1908 */
1909
1910auto Pass::boundedRandom(quint32 bound) -> quint32 {
1911 if (bound < 2) {
1912 return 0;
1913 }
1914
1915 quint32 randval;
1916 // arc4random_uniform-style rejection against modulo bias: drop values
1917 // below 2^32 % bound, which (1 + ~bound) % bound computes in quint32.
1918 const quint32 rejectionThreshold = (1 + ~bound) % bound;
1919
1920 do {
1921 randval = QRandomGenerator::system()->generate();
1922 } while (randval < rejectionThreshold);
1923
1924 return randval % bound;
1925}
1926
1927auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1928 -> QString {
1929 if (charset.isEmpty() || length == 0U) {
1930 return {};
1931 }
1932 QString out;
1933 for (unsigned int i = 0; i < length; ++i) {
1934 out.append(charset.at(static_cast<int>(
1935 boundedRandom(static_cast<quint32>(charset.length())))));
1936 }
1937 return out;
1938}
1939
1940auto Pass::pullTimedOut(int timeoutMs) -> QString {
1941 // The count in a variable first: older lupdate versions lose a tr() with
1942 // template arguments among its arguments.
1943 const int seconds = (timeoutMs + 999) / 1000;
1944 return tr("Git pull did not finish within %n second(s); editing the entry "
1945 "as it is here.",
1946 nullptr, seconds);
1947}
static void seedStore(const QString &storeRoot)
Record every entry of a store the first time it is seen; later calls for the same store do nothing....
auto lastOutputLossless() const -> bool
Whether the stdout of the item whose finished() or error() is being emitted encodes back (toUtf8(),...
Definition executor.h:632
void dequeuing(int id, bool completes)
Emitted, synchronously, when the queue's head leaves it: just before it is started,...
static auto executeBlocking(const QString &app, const QStringList &args, const QString &input=QString(), QString *process_out=nullptr, QString *process_err=nullptr) -> int
Run a command synchronously and return its exit code.
Definition executor.cpp:700
static auto translatePathForWsl(const QString &path, const QString &exe) -> QString
Translate a native path for a WSL-routed executable.
Definition executor.cpp:335
void execute(int id, const QString &app, const QStringList &args, bool readStdout, bool readStderr=true)
Queue a command without stdin input.
Definition executor.cpp:439
void drained()
Emitted once the last queued item is done and nothing runs or waits any more (isIdle()),...
void error(int id, int exitCode, const QString &output, const QString &errout)
Emitted instead of finished() when a queued process could not be started, had no executable configure...
void finished(int id, int exitCode, const QString &output, const QString &errout)
Emitted when a queued process exits normally, whatever its exit code; a non-zero code is the receiver...
void starting()
Emitted just before a queued process is started; the main window shows the busy indicator on it.
void setEnvironment(const QProcessEnvironment &env)
Set the environment passed to all child processes.
Definition executor.cpp:731
static auto parseWslCommand(const QString &app) -> std::optional< WslCommand >
Parse a configured executable as a WSL command.
Definition executor.cpp:272
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 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...
The detached signature on a store's .gpg-id: whether the configured signing key is usable,...
Definition gpgidsigner.h:29
void setStoreRoot(const QString &root)
The store the lists and signatures this signer reads belong to.
Definition gpgidsigner.h:76
auto enabled() const -> bool
Whether any signing key is configured at all.
static auto settingOrExported(const QString &passSigningKey) -> QString
The signing key to use: the setting, or with none set, the PASSWORD_STORE_SIGNING_KEY exported for pa...
auto verifyFile(const QString &gpgIdFile, QByteArray *contents) const -> bool
Read gpgIdFile and verify it against <file>.sig.
static auto keysFromSetting(const QString &passSigningKey) -> QStringList
Split the settings value into keys, upper-cased the way gpg prints fingerprints.
auto storeEnvironment() const -> QProcessEnvironment
The environment QtPass runs the store's processes in.
Definition pass.h:124
auto exportPublicKeys(const QString &gpg, const QStringList &keys, QString *out, QString *err) -> int
gpg --armor --export of keys, in the store's environment: the keyring keyLinesHeldTwice() reads.
Definition pass.cpp:558
void startingExecuteWrapper()
Emitted each time a queued process is about to start, and by the refusals that go on to emit processE...
virtual void beforeExecute(PROCESS id)
Hook invoked just before a wrapped command is dispatched.
Definition pass.cpp:169
void GenerateGPGKeys(QString batch)
Generate GPG keys using batch script.
Definition pass.cpp:420
static auto skippedGpgId(const QString &forFile, const QString &passStore, QString *recordError=nullptr, SkippedWalks *walks=nullptr) -> std::optional< QString >
The folder list getGpgIdPath() passed over on its way up to the one it returns, if it passed one over...
Definition pass.cpp:1609
static QString getDefaultKeyTemplate(const QString &gpgExecutable={})
Get default key template for new GPG keys.
Definition pass.cpp:317
void finishedAnyWithPid(const QString &out, const QString &err, Enums::PROCESS pid)
A process of any kind finished successfully and its output cannot contain a secret.
void finishedInsert(const QString &out, const QString &err)
An Insert() succeeded: the entry is in the store and, with Git in use, committed.
void pinStoreGitAttributes()
Pin byte-for-byte Git attributes for the store's encrypted files.
Definition pass.cpp:1100
virtual auto recipientArgument(const QString &line) const -> QString
The -r argument for one recipient line, as this backend's encryption hands it to gpg: the probe (encr...
Definition pass.cpp:703
AppSettings m_settings
Application settings snapshot injected at init() time.
Definition pass.h:145
static auto passReadsDifferently(const QByteArray &contents) -> QString
Why pass would read a .gpg-id differently from parseRecipients(), if it would.
Definition pass.cpp:1869
static auto getGpgIdPath(const QString &for_file, const QString &passStore) -> QString
Get .gpg-id file path for a password file.
Definition pass.cpp:1511
void handleProcessError(PROCESS pid, int exitCode, const QString &out, const QString &err)
Report a process that exited non-zero; called by finished().
Definition pass.cpp:896
virtual auto encryptionReaches(const QStringList &recipients) -> std::optional< QStringList >
The keys a gpg encryption to recipients reaches: a throwaway encryption outside the store,...
Definition pass.cpp:707
auto scopePath(const QString &path) const -> QString
path as an absolute, cleaned path, relative ones taken from the current store.
Definition pass.cpp:1287
auto refusePendingPull() -> bool
Refuse a store change while a Git pull is still queued or running.
Definition pass.cpp:1427
auto initIfUnchanged(const QString &path, const QList< UserInfo > &users, const QString &dir, const QString &passStore, const RecipientsForEditing &read) -> bool
Init(), but only while the list of dir still reads as the caller read it with recipientsForEditing().
Definition pass.cpp:1442
void releaseAutoPush(const QString &folder)
Release the holds a clean re-encryption of folder covers: those for folder itself and everything unde...
Definition pass.cpp:1312
QString m_reportedInsert
The entry of the insert whose report is going out; see reportedInsert().
Definition pass.h:1139
void finishedGenerateGPGKeys(const QString &out, const QString &err)
GenerateGPGKeys() succeeded; the new key pair is in the keyring.
Enums::PROCESS PROCESS
Alias for Enums::PROCESS used throughout this class.
Definition pass.h:154
static auto describeKeyLinesHeldTwice(const std::optional< QHash< QString, QStringList > > &held) -> QString
A message naming each line keyLinesHeldTwice() found and what the user can do about it.
Definition pass.cpp:643
virtual auto generatePassword(unsigned int length, const QString &charset) -> QString
Generate random password.
Definition pass.cpp:243
void statusMsg(const QString &msg, int timeout)
Progress or a non-fatal problem worth a line in the status bar ("Creating backup commit",...
QProcessEnvironment env
The environment the store's processes run in: the system environment plus what updateEnv() sets (PASS...
Definition pass.h:87
auto unfinishedGitOperationReason() -> QString
The unfinished git operation in progress in the store, if any.
Definition pass.cpp:1363
void GitPushAutomatic()
GitPush() for an automatic push, the one after a change. A backend that has to make the push later dr...
Definition pass.cpp:1300
PathSpelling
How a path handed to refuseLinkedPath() is spelled.
Definition pass.h:868
@ Configured
As the store is configured or relative to it, the class's path rule. A path spelled through the targe...
Definition pass.h:874
virtual auto fullKeyListing(QString *listing) -> int
The whole public keyring as keyLinesHeldTwice() reads it.
Definition pass.cpp:545
auto boundedRandom(quint32 bound) -> quint32
Generate random number in range.
Definition pass.cpp:1910
void insertFailed(const QString &err, bool written)
Emitted when an Insert() fails through a queued command, before the generic processErrorExit(): the p...
static auto gpgIdVerdictIn(const QString &dir) -> std::optional< SkippedWalk >
What skippedGpgId() concludes at one folder on its way up.
Definition pass.cpp:1579
auto pushIsAutomatic() const -> bool
Whether the GitPush() running now is an automatic one.
Definition pass.cpp:1306
static auto keyLinesHeldTwiceIn(const QStringList &lines, const QString &listing) -> QHash< QString, QStringList >
keyLinesHeldTwice() on a listing already made.
Definition pass.cpp:611
void emitProcessFinishedSignal(PROCESS pid, const QString &out, const QString &err)
Emit the signals for a process that exited with 0; called by finished() for everything but PASS_SHOW.
Definition pass.cpp:943
static bool gpgSupportsEd25519(const QString &gpgExecutable={})
Check if GPG supports Ed25519 encryption.
Definition pass.cpp:298
void refuseAsNotPartOfStore(const QString &why)
Refuse an operation on something that is not part of the store.
Definition pass.cpp:1503
static auto maxOutputArgs() -> QStringList
The gpg options that enforce kMaxPlaintextBytes.
Definition pass.cpp:1184
virtual auto storeGit(const QStringList &args, QString *out) -> bool
Run a git command in the store's repository, blocking.
Definition pass.h:932
Pass()
Construct a Pass instance.
Definition pass.cpp:83
virtual auto insertWritten(const QString &err) const -> bool
Whether the insert that just failed had put its entry in the store before a later step failed....
Definition pass.h:828
void holdAutoPush(const QString &scope)
Hold automatic pushes of the store that holds scope (autoPushHeld()): its re-encryption did not finis...
Definition pass.cpp:1308
void finishedCopy(const QString &out, const QString &err)
A Copy() succeeded; the copy exists beside the original.
void finishedMove(const QString &out, const QString &err)
A Move() succeeded; the entry or folder is under its new name.
void executeWrapper(PROCESS id, const QString &app, const QStringList &args, bool readStdout=true, bool readStderr=true)
Execute external wrapper command.
Definition pass.cpp:126
void finishedShow(const QString &out, const QString &file, bool lossless=true)
Emitted when a Show() succeeds.
static auto resolveGpgconfCommand(const QString &gpgPath) -> ResolvedGpgconfCommand
Resolve the gpgconf command to kill agents.
Definition pass.cpp:380
static auto exactRecipientArg(const QString &line) -> QString
A bare mail address in gpg's exact form, <address>; any other line as written.
Definition pass.cpp:695
auto refuseLinkedPath(const QString &path, LinkScope scope=LinkScope::EntryAndParents, PathSpelling spelling=PathSpelling::Configured) -> bool
Refuse an operation on something that is, or lies behind, a symbolic link or NTFS junction inside the...
Definition pass.cpp:1321
auto listKeys(QStringList keystrings, bool secret=false) -> QList< UserInfo >
List GPG keys matching patterns.
Definition pass.cpp:763
QQueue< QString > m_insertedEntries
The entries of the inserts counted in m_insertsPending, in queue order.
Definition pass.h:1137
QHash< QString, SkippedWalk > SkippedWalks
SkippedWalk per absolute folder, for one check of many folders.
Definition pass.h:165
static auto enabledKeyLines(const QList< UserInfo > &users) -> QStringList
The enabled users' key IDs, as Init() writes them to .gpg-id.
Definition pass.cpp:580
void finishedGitPull(const QString &out, const QString &err)
git pull succeeded; entries may have changed on disk.
virtual void GitPush()=0
Push changes to remote Git repository.
bool m_expectedListRefused
Set when refuseChangedList() or refuseBusyForExpectedList() refused during initIfUnchanged().
Definition pass.h:1131
void finishedGitPush(const QString &out, const QString &err)
git push succeeded.
auto recipientsForEditing(const QString &dir, const QString &passStore) -> RecipientsForEditing
The recipients a dialog may preselect for editing the list of dir.
Definition pass.cpp:1745
static auto linkedGpgId(const QString &forFile, const QString &passStore, LinkedWalks *walks=nullptr) -> std::optional< QString >
The link or junction under the name .gpg-id that getGpgIdPath() skips on its way up from forFile,...
Definition pass.cpp:1659
auto refuseBusyForExpectedList() -> bool
Refuse an Init() under initIfUnchanged() while the executor has work queued or running,...
Definition pass.cpp:1475
auto keyLinesHeldTwice(const QStringList &lines) -> std::optional< QHash< QString, QStringList > >
The key ID and fingerprint lines of a recipient list that more than one key block holds,...
Definition pass.cpp:590
Executor exec
Internal command executor for queuing and running subprocesses.
Definition pass.h:149
std::optional< ExpectedList > m_expectedList
Set during initIfUnchanged().
Definition pass.h:1128
void processErrorExit(int exitCode, const QString &err)
An operation ended in failure: its process exited non-zero, could not be started or crashed,...
auto verifySignedList(const GpgIdSigner &signer, const QString &gpgIdFile, QByteArray *contents, QString *why) const -> bool
Whether gpgIdFile is a signed list QtPass accepts: its signature verifies (GpgIdSigner::verifyFile())...
Definition pass.cpp:1555
void init(const AppSettings &settings)
Initialize the Pass instance with a settings snapshot.
Definition pass.cpp:171
auto refuseChangedList() -> bool
Refuse an Init() under initIfUnchanged() when the folder's list no longer reads as the caller read it...
Definition pass.cpp:1452
bool m_pushIsAutomatic
Set while GitPushAutomatic() runs GitPush().
Definition pass.h:1112
auto formatInsertError(const QString &friendly, const QString &err) -> QString
Put the translated reason for a failed insert above what gpg itself printed, leaving out the machine-...
Definition pass.cpp:937
auto entryReaders(const QString &path) -> QStringList
The long key IDs an entry is encrypted to, as gpg lists them without anyone's secret key (ENC_TO).
Definition pass.cpp:664
void finishedGitInit(const QString &out, const QString &err)
git init in the store succeeded; the store is a repository now and the tree is re-read.
static auto withoutStatusLines(const QString &err) -> QString
gpg's stderr without its machine-readable [GNUPG:] lines (and without carriage returns),...
Definition pass.cpp:926
static auto heldScopes() -> QSet< QString > &
The folders (cleaned absolute paths) whose re-encryption did not finish, for every store and both bac...
Definition pass.cpp:1282
auto withCurrentGitPin(QProcessEnvironment base) const -> QProcessEnvironment
base with GIT_DIR and GIT_WORK_TREE as the store is now (Util::gitStoreVariables()),...
Definition pass.cpp:1169
void setEnvVar(const QString &name, const QString &value)
Set or remove an environment variable.
Definition pass.cpp:977
static auto loggableArgs(const QStringList &args) -> QStringList
The arguments as they may appear in the debug log: the value of --passphrase and friends,...
Definition pass.cpp:141
auto autoPushHeld() const -> bool
Whether automatic pushes of the current store are held because its last re-encryption did not finish ...
Definition pass.cpp:1291
static auto pullTimedOut(int timeoutMs) -> QString
The status-bar text for a blocking pull stopped at its deadline.
Definition pass.cpp:1940
void updateEnv()
Update environment for subprocesses.
Definition pass.cpp:984
void finishedInit(const QString &out, const QString &err)
An Init() succeeded: the folder's .gpg-id holds the new recipient list.
QHash< QString, std::optional< QString > > LinkedWalks
Definition pass.h:168
void idle()
Nothing of the store's runs or waits any more (isIdle()).
virtual void finished(int id, int exitCode, const QString &out, const QString &err)
Handle process completion.
Definition pass.cpp:860
void critical(const QString &title, const QString &message)
Something went wrong that the user has to be told about in a dialog, such as a refused path or a fail...
auto refuseSkippedGpgId(const QString &file, bool signing, const QString &except=QString(), SkippedWalks *walks=nullptr) -> bool
With signing on, refuse to encrypt file when the lookup passed over its folder's own list (skippedGpg...
Definition pass.cpp:1518
auto refuseKeyLinesHeldTwice(const QStringList &lines) -> bool
Refuse, with critical(), a recipient list with a line that more than one key block holds (keyLinesHel...
Definition pass.cpp:568
void generateGPGKeysFailed(const QString &err)
Emitted when GPG key generation fails, alongside the generic processErrorExit(); lets the keygen dial...
static constexpr qint64 kMaxPlaintextBytes
Most bytes of plaintext a gpg decryption may produce.
Definition pass.h:511
int m_insertsPending
Inserts that have started queueing but not yet reported; see queueInsert.
Definition pass.h:1135
static auto getRecipientList(const QString &for_file, const QString &passStore) -> QStringList
Get list of recipients for a password file.
Definition pass.cpp:1833
virtual void Init(QString path, const QList< UserInfo > &users)=0
Initialize new password store.
LinkScope
What refuseLinkedPath() judges.
Definition pass.h:858
@ EntryAndParents
The entry itself and every folder above it in the store.
Definition pass.h:860
void finishedRemove(const QString &out, const QString &err)
A Remove() succeeded; the entry or folder is gone from the store.
auto refuseUnfinishedGitOperation() -> bool
Refuse to change the store while git is mid-rebase, -merge, -cherry-pick or -revert.
Definition pass.cpp:1489
QQueue< QString > m_pendingShows
Files of the Show() calls still in flight, oldest first.
Definition pass.h:1133
static auto parseRecipients(const QByteArray &contents, const QString &sourceName) -> QStringList
Parse the contents of a .gpg-id: one recipient per line, # starts a comment, unusable lines are logge...
Definition pass.cpp:1848
auto refuseFolderOutsideStore(const QString &folder, QString *relative=nullptr) -> bool
Refuse recipients for a folder outside the store, as pass refuses a path with .. in it.
Definition pass.cpp:1347
auto generateRandomPassword(const QString &charset, unsigned int length) -> QString
Generate random password from charset.
Definition pass.cpp:1927
static auto storeRelativePath(const QString &storeRoot, const QString &candidate) -> std::optional< QString >
Where candidate lies in the store, judged as isPathInStore() judges it.
static auto isTargetSpelled(const QString &storeRoot, const QString &path) -> bool
Whether path is spelled through the target of a store root that is itself a link, rather than from th...
static auto isUnderLink(const QString &path, const QString &storeRoot, bool includeSelf=true) -> bool
Whether the way from storeRoot down to path passes through a symbolic link or NTFS junction: path its...
Definition util.cpp:1217
static void requireExplicitBareRepository(QProcessEnvironment &env)
Make git in env refuse a folder that is merely laid out as a bare repository (safe....
Definition util.cpp:511
static constexpr qint64 kMaxGpgIdBytes
Most bytes of a .gpg-id QtPass reads.
Definition util.h:561
static auto gitStoreVariables(const QString &store, const QString &git={}, std::optional< uint > asUser=std::nullopt) -> QList< std::pair< QString, QString > >
The variables that keep git in store's own repository, never one above it: GIT_CEILING_DIRECTORIES (g...
Definition util.cpp:553
static auto displayable(const QString &text, bool lineBreaks=true) -> QString
text with the characters that change how the text around them reads replaced by U+FFFD,...
Definition util.cpp:898
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
static auto joinPath(const QString &dir, const QString &name) -> QString
name in dir, as the file system means it.
Definition util.cpp:110
static auto isValidKeyId(const QString &keyId) -> bool
Check whether a .gpg-id token may be passed to gpg as a key selector. Accepts any non-empty token tha...
Definition util.cpp:1063
static auto newLinesRegex() -> const QRegularExpression &
Returns a regex to match newline characters.
Definition util.cpp:1055
static auto readRegularFileInStore(const QString &store, const QString &path, qint64 maxBytes) -> std::optional< QByteArray >
readRegularFileUnder() for a file of the store at store, spelled under the store as configured or und...
Definition util.cpp:1564
EntryRecord: the entry paths this device has saved, kept outside the store.
Rollback detection for signed .gpg-id files: the generation counter and the record of what was last s...
GpgIdSigner, which signs a store's .gpg-id and verifies an existing .gpg-id.sig against the configure...
auto parseGpgColonOutput(const QString &output, bool secret) -> QList< UserInfo >
Parse a gpg colon listing into one UserInfo per key.
Parsing of gpg --with-colons key listings into UserInfo records.
@ PASS_INIT
Definition enums.h:53
@ PASS_INSERT
Definition enums.h:51
@ GIT_INIT
Definition enums.h:44
@ PASS_COPY
Definition enums.h:56
@ PASS_MOVE
Definition enums.h:55
@ GPG_GENKEYS
Definition enums.h:54
@ PASS_REMOVE
Definition enums.h:52
@ PASS_SHOW
Definition enums.h:50
@ GIT_PULL
Definition enums.h:48
@ GIT_PUSH
Definition enums.h:49
@ PASS_INIT
Definition enums.h:53
@ PASS_INSERT
Definition enums.h:51
@ GIT_INIT
Definition enums.h:44
@ PASS_COPY
Definition enums.h:56
@ PASS_MOVE
Definition enums.h:55
@ GPG_GENKEYS
Definition enums.h:54
@ PASS_REMOVE
Definition enums.h:52
@ PASS_SHOW
Definition enums.h:50
@ PROCESS_COUNT
Definition enums.h:62
@ GIT_PULL
Definition enums.h:48
@ GIT_PUSH
Definition enums.h:49
auto processInfo(PROCESS pid) -> const ProcessInfo &
What is known about pid.
auto gpgErrorMessage(const QString &err) -> QString
Maps GPG stderr (which may include –status-fd 2 tokens) to a translated user-friendly encryption erro...
Definition pass.cpp:808
Pass, the abstract password-store backend that RealPass and ImitatePass implement,...
QString gpgErrorMessage(const QString &err)
Maps GPG stderr (which may include –status-fd 2 tokens) to a translated user-friendly encryption erro...
Definition pass.cpp:808
PathValidator: is a path inside the password store, and how is it spelled relative to the store root.
Enums::ProcessInfo, the one table that names each kind of subprocess and says whether its output may ...
The "qtpass" logging category.
Plain value-object holding all flat QtPass configuration.
Definition appsettings.h:36
QString gpgExecutable
Path to the gpg/gpg2 executable.
Definition appsettings.h:66
QString passSigningKey
GPG key used to sign .gpg-id files.
Definition appsettings.h:61
QString passStore
Password-store root path.
Definition appsettings.h:60
QString gitExecutable
Path to the git executable.
Definition appsettings.h:65
QString gpgHome
GPG home directory (read-only externally).
Definition appsettings.h:69
bool gitUseParentRepository
PasswordConfiguration passwordConfiguration
Length/charset/custom chars.
What initIfUnchanged() expects the list to read as, for refuseChangedList(); empty outside it.
Definition pass.h:1117
QString passStore
The store root given to recipientsForEditing().
Definition pass.h:1121
QString dir
The folder given to recipientsForEditing().
Definition pass.h:1119
QStringList recipients
The recipients read then.
Definition pass.h:1125
RecipientsForEditing::State state
The state read then.
Definition pass.h:1123
What a dialog may do with the list of a folder (recipientsForEditing()).
Definition pass.h:604
QStringList recipients
The recipients to preselect; empty when Rejected.
Definition pass.h:627
State state
How the list on disk stood up.
Definition pass.h:625
QString warning
What the dialog should show, if anything.
Definition pass.h:629
@ Verified
Signature and generation and folder all accepted.
Definition pass.h:610
@ Unsigned
No signing key: the list as it is.
Definition pass.h:608
@ Rejected
Not to be used: signature invalid, written for another folder or for no folder in particular while a ...
Definition pass.h:622
What skippedGpgId() found on its way up from one folder.
Definition pass.h:158
Holds the password generator settings: which character set is selected, the alphabet of every set,...
int length
Length of the generated password, in characters.
Represents a command invocation for gpgconf operations.
Definition pass.h:39
QStringList arguments
Full argv list, including any wrapper/prefix args followed by the actual gpgconf operation flags (e....
Definition pass.h:49
QString program
Executable to run — may be a bare name resolved via PATH or a wrapper (e.g. wsl.exe) rather than a di...
Definition pass.h:44
Stores GPG key info including validity, creation date, and more.
Definition userinfo.h:20
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...