QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
gpgidsigner.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
7#include "gpgidsigner.h"
8
9#include "executor.h"
10#include "util.h"
11#include <QCoreApplication>
12#include <QFile>
13#include <QProcessEnvironment>
14#include <QRegularExpression>
15#include <QTemporaryDir>
16#include <algorithm>
17#include <utility>
18
19#include "qtpasslogging.h"
20
21GpgIdSigner::GpgIdSigner(QString gpgExecutable, QStringList signingKeys,
22 Exec exec)
23 : m_gpg(std::move(gpgExecutable)), m_keys(std::move(signingKeys)),
24 m_exec(std::move(exec)) {
25 if (!m_exec) {
26 m_exec = [](const QString &app, const QStringList &args,
27 const QString &input, QString *out, QString *err) {
28 return Executor::executeBlocking(app, args, input, out, err);
29 };
30 }
31}
32
33auto GpgIdSigner::keysFromSetting(const QString &passSigningKey)
34 -> QStringList {
35 QStringList keys = passSigningKey.split(QLatin1Char(' '), Qt::SkipEmptyParts);
36 // gpg prints fingerprints in upper case in its status lines; accept them
37 // typed either way.
38 for (QString &key : keys) {
39 key = key.toUpper();
40 }
41 return keys;
42}
43
44auto GpgIdSigner::settingOrExported(const QString &passSigningKey) -> QString {
45 QString own = passSigningKey.trimmed();
46 if (!own.isEmpty()) {
47 return own;
48 }
49 return QProcessEnvironment::systemEnvironment()
50 .value(QStringLiteral("PASSWORD_STORE_SIGNING_KEY"))
51 .trimmed();
52}
53
54auto GpgIdSigner::run(const QStringList &args, QString *out, QString *err,
55 const QString &input) const -> int {
56 return m_exec(m_gpg, args, input, out, err);
57}
58
59namespace {
61struct Key {
62 bool signs = false;
63 bool valid = false;
64 bool primary = false;
65 QString fpr;
66};
67
74auto signingBlocks(const QString &out) -> QList<QList<Key>> {
75 // Records, one per line: a key (sec, or ssb for a subkey) and later its
76 // own fpr (an rvk may come between). A user ID is a record of its own,
77 // with its colons and line breaks escaped, so nothing a key's owner
78 // wrote can pass for either; a search of the whole output for the
79 // fingerprint could be fooled by one. A key signs when it can (s in its
80 // own capabilities), is not revoked, expired or invalid, and its secret
81 // part is here (field 15 is # for a stub).
82 QList<QList<Key>> blocks;
83 bool awaitingFpr = false;
84 const QStringList lines = out.split(QLatin1Char('\n'));
85 for (const QString &line : lines) {
86 const QStringList fields = line.trimmed().split(QLatin1Char(':'));
87 const QString &type = fields.first();
88 const bool primary = type == QLatin1String("sec");
89 if (primary || type == QLatin1String("ssb")) {
90 if (primary) {
91 blocks.append(QList<Key>());
92 }
93 if (blocks.isEmpty()) {
94 awaitingFpr = false;
95 continue;
96 }
97 const QString validity = fields.value(1);
98 Key k;
99 k.primary = primary;
100 k.valid = validity != QLatin1String("r") &&
101 validity != QLatin1String("e") &&
102 validity != QLatin1String("i");
103 k.signs = k.valid && fields.value(11).contains(QLatin1Char('s')) &&
104 fields.value(14) != QLatin1String("#");
105 blocks.last().append(k);
106 awaitingFpr = true;
107 } else if (type == QLatin1String("fpr") && awaitingFpr) {
108 blocks.last().last().fpr = fields.value(9);
109 awaitingFpr = false;
110 }
111 }
112 return blocks;
113}
114
121auto signsWith(const QList<QList<Key>> &blocks, const QString &key) -> bool {
122 // Configured as a subkey, that subkey must sign. Configured as a primary
123 // key, gpg's --local-user picks a signing key from its whole block, so
124 // the primary or any of its subkeys will do.
125 for (const QList<Key> &block : std::as_const(blocks)) {
126 // A revoked or expired primary key takes its subkeys with it.
127 if (block.isEmpty() || !block.first().valid) {
128 continue;
129 }
130 for (const Key &k : block) {
131 if (k.fpr.compare(key, Qt::CaseInsensitive) != 0) {
132 continue;
133 }
134 if (k.signs) {
135 return true;
136 }
137 if (k.primary && std::any_of(block.cbegin(), block.cend(),
138 [](const Key &sub) { return sub.signs; })) {
139 return true;
140 }
141 }
142 }
143 return false;
144}
145} // namespace
146
147auto GpgIdSigner::haveSecretKey() const -> bool {
148 if (!enabled()) {
149 return false;
150 }
151 // Only the first key signs (see sign()), so only its secret key matters:
152 // a usable second key would let Init start and fail at the signature.
153 const QString &key = m_keys.first();
154 QString out;
155 const int rc =
156 run({QStringLiteral("--with-colons"), QStringLiteral("--fixed-list-mode"),
157 QStringLiteral("--list-secret-keys"), QStringLiteral("--"), key},
158 &out);
159 if (rc != 0) {
160 qCDebug(lcQtPass) << "GPG list-secret-keys failed with code:" << rc;
161 return false;
162 }
163 return signsWith(signingBlocks(out), key);
164}
165
166auto GpgIdSigner::sign(const QString &gpgIdFile, const QByteArray &contents,
167 QString *error) const -> bool {
168 if (!enabled()) {
169 return true;
170 }
171 if (m_keys.size() > 1) {
172 qCDebug(lcQtPass)
173 << "Multiple signing keys configured; using only the first key:"
174 << m_keys.first();
175 }
176 // The executor feeds stdin as UTF-8 text (see verify()).
177 const QString text = QString::fromUtf8(contents);
178 if (text.toUtf8() != contents) {
179 if (error)
180 *error = QCoreApplication::translate(
181 "GpgIdSigner", "the recipient list is not valid UTF-8");
182 return false;
183 }
184 QTemporaryDir scratch;
185 if (!scratch.isValid()) {
186 if (error)
187 *error = scratch.errorString();
188 return false;
189 }
190 const QString output = scratch.filePath(QStringLiteral("sig"));
191 // --local-user, not --default-key: without that secret key gpg would
192 // print "all values passed to '--default-key' ignored", sign with
193 // whatever secret key it has and exit 0.
194 const int rc = run(
195 {QStringLiteral("--local-user"), m_keys.first(), QStringLiteral("--yes"),
196 QStringLiteral("--detach-sign"), QStringLiteral("--output"),
197 Executor::translatePathForWsl(output, m_gpg), QStringLiteral("-")},
198 nullptr, error, text);
199 if (rc != 0) {
200 qCDebug(lcQtPass) << "GPG signing failed with code:" << rc;
201 return false;
202 }
203 QFile signature(output);
204 if (!signature.open(QIODevice::ReadOnly) || signature.size() <= 0) {
205 if (error)
206 *error =
207 QCoreApplication::translate("GpgIdSigner", "gpg wrote no signature");
208 return false;
209 }
210 const QByteArray bytes = signature.readAll();
211 signature.close();
212 // Checked before it is placed: a signature by any key but the configured
213 // ones (an older gpg, a wrapper, a smartcard picking its own) is not
214 // written, and the one there, if any, stays.
215 // The signature is in this call's own scratch folder, outside the store:
216 // checked by a copy of this signer without the store root.
217 GpgIdSigner scratchSigner = *this;
218 scratchSigner.m_storeRoot.clear();
219 if (!scratchSigner.verify(contents, output)) {
220 if (error)
221 *error = QCoreApplication::translate(
222 "GpgIdSigner",
223 "the new signature does not verify as one of the signing keys");
224 return false;
225 }
226 return Util::writeFileReplacing(gpgIdFile + QStringLiteral(".sig"), bytes,
227 true, error);
228}
229
230auto GpgIdSigner::validSigFingerprints(const QString &statusOutput)
231 -> QStringList {
232 static const QRegularExpression re(
233 // 40 hex for v4 keys, 64 for v5/v6 (gpg 2.5+), either position.
234 R"(^\‍[GNUPG:\‍] VALIDSIG ([A-F0-9]{40}(?:[A-F0-9]{24})?) .* )"
235 R"(([A-F0-9]{40}(?:[A-F0-9]{24})?)\r?$)",
236 QRegularExpression::MultilineOption);
237 // gpg reports a signature by a revoked key as REVKEYSIG plus KEYREVOKED,
238 // and still prints VALIDSIG and exits 0. A signing key revoked because it
239 // was compromised must not vouch for a recipient list, so a signature
240 // whose block (from one NEWSIG to the next) says so does not count. One
241 // by an expired key does, as gpg calls it a good signature: expiry is not
242 // compromise, and pass accepts it too.
243 static const QRegularExpression revoked(
244 QStringLiteral(R"(^\‍[GNUPG:\‍] (?:REVKEYSIG|KEYREVOKED)\b)"),
245 QRegularExpression::MultilineOption);
246 static const QRegularExpression newSig(
247 QStringLiteral(R"(^\‍[GNUPG:\‍] NEWSIG\b)"),
248 QRegularExpression::MultilineOption);
249 const QRegularExpressionMatch m = re.match(statusOutput);
250 if (!m.hasMatch()) {
251 return {};
252 }
253 const qsizetype from =
254 statusOutput.lastIndexOf(newSig, m.capturedStart()) < 0
255 ? 0
256 : statusOutput.lastIndexOf(newSig, m.capturedStart());
257 const qsizetype to = statusOutput.indexOf(newSig, m.capturedEnd());
258 const QString block = statusOutput.mid(from, to < 0 ? -1 : to - from);
259 if (revoked.match(block).hasMatch()) {
260 return {};
261 }
262 return {m.captured(1), m.captured(2)};
263}
264
265auto GpgIdSigner::readOwnFile(const QString &path, qint64 maxBytes) const
266 -> std::optional<QByteArray> {
267 return m_storeRoot.isEmpty()
268 ? Util::readRegularFile(path, maxBytes)
269 : Util::readRegularFileInStore(m_storeRoot, path, maxBytes);
270}
271
272auto GpgIdSigner::verify(const QByteArray &contents,
273 const QString &signatureFile) const -> bool {
274 m_refusal.clear();
275 if (!enabled()) {
276 return true;
277 }
278 // The executor feeds stdin as UTF-8 text. A .gpg-id is one: key IDs,
279 // fingerprints, e-mail addresses, comments. Bytes that would not survive
280 // the round trip cannot be verified faithfully, so they are not verified
281 // at all rather than as something else.
282 const QString text = QString::fromUtf8(contents);
283 if (text.toUtf8() != contents) {
284 qCDebug(lcQtPass) << "Refusing to verify" << signatureFile
285 << ": the signed file is not valid UTF-8";
286 return false;
287 }
288 // git signs a commit or tag the same way a .gpg-id is signed: a detached
289 // signature over the object without its own signature header. With
290 // pass.signcommits (or commit.gpgsign) the signing key signs QtPass's
291 // commits, so such a commit and its signature could be pushed as .gpg-id and
292 // .gpg-id.sig and would verify here as a signed recipient list - whose lines
293 // (the commit's headers and message, part of which can be a pushed entry
294 // name) then become recipients. A commit begins "tree <hash>" and a tag
295 // "object <hash>"; refuse either before gpg is asked.
296 static const QRegularExpression commitOrTag(
297 QStringLiteral(R"(\A(?:tree|object) [0-9a-f]{40}(?:[0-9a-f]{24})?\n)"));
298 if (commitOrTag.match(text).hasMatch()) {
299 qCDebug(lcQtPass) << "Refusing to verify" << signatureFile
300 << ": the signed data is a git commit or tag object";
301 return false;
302 }
303 // Same for the signature: a valid pair replayed from elsewhere through two
304 // links is not this folder's list.
305 if (Util::isLinkedFolder(signatureFile)) {
306 qCDebug(lcQtPass) << "Refusing to verify" << signatureFile
307 << ": the signature file is a link";
308 return false;
309 }
310 // Read as a regular file of bounded size, as the list itself is, and
311 // give gpg a copy of those bytes: a FIFO planted under the name would
312 // block gpg, and the GUI thread waiting for it, a sparse file of
313 // gigabytes would be read whole, and either could be swapped in between
314 // a check of the name and gpg opening it.
315 const std::optional<QByteArray> signature =
316 readOwnFile(signatureFile, kMaxSignatureBytes);
317 if (!signature) {
318 qCDebug(lcQtPass) << "Refusing to verify" << signatureFile
319 << ": not a regular file of at most" << kMaxSignatureBytes
320 << "bytes";
321 return false;
322 }
323 QTemporaryDir scratch;
324 if (!scratch.isValid()) {
325 return false;
326 }
327 const QString copy = scratch.filePath(QStringLiteral("sig"));
328 {
329 QFile file(copy);
330 if (!file.open(QIODevice::WriteOnly) ||
331 file.write(*signature) != signature->size()) {
332 return false;
333 }
334 }
335 QString out;
336 const QString sig = Executor::translatePathForWsl(copy, m_gpg);
337 // "-" makes gpg read the signed data from stdin: the bytes we hold.
338 // --batch stops at the first bad signature; without it gpg checked every
339 // packet in the file, each against the key it names, however slow.
340 // --trust-model pgp, whatever gpg.conf says: under `trust-model always`
341 // gpg skips the trust check that reports KEYREVOKED, so a revoked key that
342 // has also expired came back as merely expired (EXPKEYSIG) and its
343 // signature counted. The model changes no verdict on the signature
344 // itself, only which notes gpg adds to it. --no-auto-check-trustdb: a
345 // keyring kept under another model would otherwise have its trustdb
346 // rebuilt on the first such call; the revoked flag comes from the key
347 // block, not from that computation.
348 const int rc =
349 run({QStringLiteral("--batch"), QStringLiteral("--trust-model=pgp"),
350 QStringLiteral("--no-auto-check-trustdb"),
351 QStringLiteral("--verify"), QStringLiteral("--status-fd=1"),
352 QStringLiteral("--"), sig, QStringLiteral("-")},
353 &out, nullptr, text);
354 if (rc != 0) {
355 qCDebug(lcQtPass) << "GPG verify failed with code:" << rc;
356 return false;
357 }
358 const QStringList fingerprints = validSigFingerprints(out);
359 for (const QString &key : m_keys) {
360 if (fingerprints.contains(key)) {
361 return heldByOneKey(fingerprints.value(0));
362 }
363 }
364 return false;
365}
366
367auto GpgIdSigner::heldByOneKey(const QString &signingFingerprint) const
368 -> bool {
369 // A list-filter in gpg.conf hides key blocks from the listing, also with
370 // --with-colons, and could hide the second one: one given here replaces
371 // it and selects every key. The rest of gpg.conf stays, so the keyrings
372 // listed are those the verification read. A gpg older than 2.4 knows no
373 // --list-filter, and so none in gpg.conf either: listed without it.
374 const QStringList listArgs{
375 QStringLiteral("--batch"), QStringLiteral("--with-colons"),
376 QStringLiteral("--list-keys"), QStringLiteral("--"), signingFingerprint};
377 QString listing;
378 QString listErr;
379 int rc = run(QStringList{QStringLiteral("--list-filter"),
380 QStringLiteral("select=key_size>0")} +
381 listArgs,
382 &listing, &listErr, QString());
383 if (rc != 0 && listErr.contains(QLatin1String("list-filter"))) {
384 listing.clear();
385 rc = run(listArgs, &listing, nullptr, QString());
386 }
387 if (rc != 0) {
388 qCDebug(lcQtPass) << "Refusing the signature: gpg cannot list the key"
389 << signingFingerprint;
390 return false;
391 }
392 // Each block by its first user ID, or its key ID when it has none.
393 QStringList holders;
394 bool named = true;
395 for (const QString &line : listing.split(QLatin1Char('\n'))) {
396 const QStringList field = line.split(QLatin1Char(':'));
397 if (field.value(0) == QLatin1String("pub")) {
398 holders << field.value(4);
399 named = false;
400 } else if (field.value(0) == QLatin1String("uid") && !named &&
401 !holders.isEmpty()) {
402 holders.last() = QStringLiteral("%1 (%2)").arg(
403 Util::displayable(field.value(9)), holders.last());
404 named = true;
405 }
406 }
407 if (holders.size() != 1) {
408 qCDebug(lcQtPass) << "Refusing the signature:" << holders.size()
409 << "key blocks hold the signing key"
410 << signingFingerprint;
411 if (holders.size() > 1) {
412 m_refusal =
413 QCoreApplication::translate(
414 "GpgIdSigner",
415 "The signing key %1 is held by more than one key: %2. "
416 "gpg may judge a signature by any of them, so no "
417 "signed recipient list is accepted. A key that holds "
418 "someone else's signing key as a subkey was made to "
419 "do so: look at it, and delete it if you did not "
420 "expect it.")
421 .arg(signingFingerprint, holders.join(QStringLiteral(", ")));
422 }
423 return false;
424 }
425 return true;
426}
427
428auto GpgIdSigner::verifyFile(const QString &gpgIdFile,
429 QByteArray *contents) const -> bool {
430 // A link under the name is not the store's .gpg-id, whatever it points
431 // to and however well that is signed.
432 if (Util::isLinkedFolder(gpgIdFile)) {
433 contents->clear();
434 return false;
435 }
436 // Read as the regular file it is and bounded: a FIFO would block, a
437 // sparse file of gigabytes be read whole, before any signature is checked.
438 std::optional<QByteArray> bytes =
440 if (!bytes) {
441 contents->clear();
442 return false;
443 }
444 *contents = *std::move(bytes);
445 return verify(*contents, gpgIdFile + QStringLiteral(".sig"));
446}
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
static auto validSigFingerprints(const QString &statusOutput) -> QStringList
Pick the fingerprints out of gpg's --status-fd VALIDSIG line.
Exec m_exec
How gpg is run; replaced by a fake in the unit tests.
auto enabled() const -> bool
Whether any signing key is configured at all.
auto run(const QStringList &args, QString *out=nullptr, QString *err=nullptr, const QString &input=QString()) const -> int
Run gpg with args through m_exec.
auto sign(const QString &gpgIdFile, const QByteArray &contents, QString *error=nullptr) const -> bool
Write <file>.sig, a detached signature by the first key over contents, the bytes the caller just wrot...
QString m_refusal
See refusal(); set by the last verify().
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...
GpgIdSigner(QString gpgExecutable, QStringList signingKeys, Exec exec=Exec())
Create a signer.
std::function< int(const QString &app, const QStringList &args, const QString &input, QString *out, QString *err)> Exec
Blocking process runner: Executor::executeBlocking()'s shape.
Definition gpgidsigner.h:47
QStringList m_keys
The configured signing keys. The first one signs; a signature by any of them verifies.
auto keys() const -> const QStringList &
The keys this signer was given.
auto verifyFile(const QString &gpgIdFile, QByteArray *contents) const -> bool
Read gpgIdFile and verify it against <file>.sig.
static constexpr qint64 kMaxSignatureBytes
Most bytes of a .gpg-id.sig verify() hands to gpg.
Definition gpgidsigner.h:41
auto heldByOneKey(const QString &signingFingerprint) const -> bool
Whether exactly one key block holds the key that made a signature.
QString m_gpg
The gpg executable, as configured.
QString m_storeRoot
See setStoreRoot(); empty when not set.
auto readOwnFile(const QString &path, qint64 maxBytes) const -> std::optional< QByteArray >
Read a list or signature of the store: under m_storeRoot when set (see setStoreRoot()).
static auto keysFromSetting(const QString &passSigningKey) -> QStringList
Split the settings value into keys, upper-cased the way gpg prints fingerprints.
auto verify(const QByteArray &contents, const QString &signatureFile) const -> bool
Check a detached signature against the given bytes: gpg must report a VALIDSIG whose key or primary-k...
auto haveSecretKey() const -> bool
Whether gpg has the secret key that sign() will use, i.e. the first configured key....
static auto writeFileReplacing(const QString &path, const QByteArray &bytes, bool replace, QString *error=nullptr) -> bool
Write bytes as the file path through stageFileReplacing().
Definition util.cpp:1911
static constexpr qint64 kMaxGpgIdBytes
Most bytes of a .gpg-id QtPass reads.
Definition util.h:561
static auto readRegularFile(const QString &path, qint64 maxBytes) -> std::optional< QByteArray >
Read path whole, as the regular file it is (openRegularFile()), when it holds at most maxBytes.
Definition util.cpp:1555
static auto 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 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
Executor, the FIFO queue every gpg, git and pass child process of QtPass goes through,...
GpgIdSigner, which signs a store's .gpg-id and verifies an existing .gpg-id.sig against the configure...
The "qtpass" logging category.
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...