Branch data Line data Source code
1 : : // SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
2 : : // SPDX-License-Identifier: GPL-3.0-or-later
3 : : /**
4 : : * @file
5 : : * @brief Implements GpgIdSigner on top of gpg's `--status-fd` output.
6 : : */
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 : :
21 : 944 : GpgIdSigner::GpgIdSigner(QString gpgExecutable, QStringList signingKeys,
22 [ + + ]: 944 : Exec exec)
23 : : : m_gpg(std::move(gpgExecutable)), m_keys(std::move(signingKeys)),
24 : : m_exec(std::move(exec)) {
25 [ + + ]: 944 : if (!m_exec) {
26 : 91 : m_exec = [](const QString &app, const QStringList &args,
27 : : const QString &input, QString *out, QString *err) {
28 : 16 : return Executor::executeBlocking(app, args, input, out, err);
29 : 91 : };
30 : : }
31 : 944 : }
32 : :
33 : 926 : auto GpgIdSigner::keysFromSetting(const QString &passSigningKey)
34 : : -> QStringList {
35 : 926 : 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 [ + + + ]: 2080 : for (QString &key : keys) {
39 : 228 : key = key.toUpper();
40 : : }
41 : 926 : return keys;
42 : : }
43 : :
44 : 1059 : auto GpgIdSigner::settingOrExported(const QString &passSigningKey) -> QString {
45 : : QString own = passSigningKey.trimmed();
46 [ + + ]: 1059 : if (!own.isEmpty()) {
47 : 53 : return own;
48 : : }
49 : 1006 : return QProcessEnvironment::systemEnvironment()
50 : 2012 : .value(QStringLiteral("PASSWORD_STORE_SIGNING_KEY"))
51 : : .trimmed();
52 : : }
53 : :
54 : 398 : auto GpgIdSigner::run(const QStringList &args, QString *out, QString *err,
55 : : const QString &input) const -> int {
56 : 398 : return m_exec(m_gpg, args, input, out, err);
57 : : }
58 : :
59 : : namespace {
60 : : /// One key of a `--list-secret-keys` listing, as haveSecretKey() judges it.
61 : 338 : struct Key {
62 : : bool signs = false; ///< Can sign: valid, `s` capability, secret here.
63 : : bool valid = false; ///< Not revoked, expired or invalid.
64 : : bool primary = false; ///< A `sec` record, not an `ssb`.
65 : : QString fpr; ///< Its own fingerprint, from the `fpr` after it.
66 : : };
67 : :
68 : : /**
69 : : * @brief Read gpg's `--with-colons --list-secret-keys` output into blocks:
70 : : * a primary key, then its subkeys.
71 : : * @param out gpg's standard output.
72 : : * @return The blocks, in listing order.
73 : : */
74 : 50 : auto 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 : 50 : QList<QList<Key>> blocks;
83 : : bool awaitingFpr = false;
84 : 50 : const QStringList lines = out.split(QLatin1Char('\n'));
85 [ + + ]: 242 : for (const QString &line : lines) {
86 : 192 : const QStringList fields = line.trimmed().split(QLatin1Char(':'));
87 : : const QString &type = fields.first();
88 [ + + ]: 192 : const bool primary = type == QLatin1String("sec");
89 [ + + + + ]: 192 : if (primary || type == QLatin1String("ssb")) {
90 [ + + ]: 62 : if (primary) {
91 : 96 : blocks.append(QList<Key>());
92 : : }
93 [ - + ]: 62 : if (blocks.isEmpty()) {
94 : : awaitingFpr = false;
95 : 0 : continue;
96 : : }
97 : 62 : const QString validity = fields.value(1);
98 : 62 : Key k;
99 : 62 : k.primary = primary;
100 [ + + + + ]: 62 : k.valid = validity != QLatin1String("r") &&
101 [ + + + + : 62 : validity != QLatin1String("e") &&
- + ]
102 [ - + ]: 57 : validity != QLatin1String("i");
103 [ + + + + : 178 : k.signs = k.valid && fields.value(11).contains(QLatin1Char('s')) &&
+ + + ]
104 [ + + ]: 116 : fields.value(14) != QLatin1String("#");
105 : : blocks.last().append(k);
106 : : awaitingFpr = true;
107 [ + + - + ]: 130 : } else if (type == QLatin1String("fpr") && awaitingFpr) {
108 : 124 : blocks.last().last().fpr = fields.value(9);
109 : : awaitingFpr = false;
110 : : }
111 : : }
112 : 50 : return blocks;
113 : : }
114 : :
115 : : /**
116 : : * @brief Whether @p blocks hold a secret key that signs as @p key.
117 : : * @param blocks The listing, as signingBlocks() reads it.
118 : : * @param key The configured key's fingerprint.
119 : : * @return Whether gpg can sign with @p key here.
120 : : */
121 : 50 : auto 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 [ + + ]: 60 : for (const QList<Key> &block : std::as_const(blocks)) {
126 : : // A revoked or expired primary key takes its subkeys with it.
127 [ + - + + ]: 48 : if (block.isEmpty() || !block.first().valid) {
128 : 4 : continue;
129 : : }
130 [ + + ]: 55 : for (const Key &k : block) {
131 [ + + ]: 49 : if (k.fpr.compare(key, Qt::CaseInsensitive) != 0) {
132 : 7 : continue;
133 : : }
134 [ + + ]: 42 : if (k.signs) {
135 : : return true;
136 : : }
137 [ + + + + ]: 7 : if (k.primary && std::any_of(block.cbegin(), block.cend(),
138 [ + + ]: 4 : [](const Key &sub) { return sub.signs; })) {
139 : : return true;
140 : : }
141 : : }
142 : : }
143 : : return false;
144 : : }
145 : : } // namespace
146 : :
147 : 56 : auto GpgIdSigner::haveSecretKey() const -> bool {
148 [ + + ]: 56 : 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 : 55 : QString out;
155 : : const int rc =
156 : 440 : run({QStringLiteral("--with-colons"), QStringLiteral("--fixed-list-mode"),
157 : 55 : QStringLiteral("--list-secret-keys"), QStringLiteral("--"), key},
158 : : &out);
159 [ + + ]: 55 : if (rc != 0) {
160 : 5 : qCDebug(lcQtPass) << "GPG list-secret-keys failed with code:" << rc;
161 : 5 : return false;
162 : : }
163 : 100 : return signsWith(signingBlocks(out), key);
164 : : }
165 : :
166 : 42 : auto GpgIdSigner::sign(const QString &gpgIdFile, const QByteArray &contents,
167 : : QString *error) const -> bool {
168 [ + + ]: 42 : if (!enabled()) {
169 : : return true;
170 : : }
171 [ + + ]: 41 : if (m_keys.size() > 1) {
172 : 4 : qCDebug(lcQtPass)
173 : 0 : << "Multiple signing keys configured; using only the first key:"
174 : 0 : << m_keys.first();
175 : : }
176 : : // The executor feeds stdin as UTF-8 text (see verify()).
177 : : const QString text = QString::fromUtf8(contents);
178 [ + + ]: 41 : if (text.toUtf8() != contents) {
179 [ + - ]: 1 : if (error)
180 : 2 : *error = QCoreApplication::translate(
181 : : "GpgIdSigner", "the recipient list is not valid UTF-8");
182 : 1 : return false;
183 : : }
184 : 40 : QTemporaryDir scratch;
185 [ + - + ]: 40 : if (!scratch.isValid()) {
186 [ # # ]: 0 : if (error)
187 : 0 : *error = scratch.errorString();
188 : 0 : return false;
189 : : }
190 : 80 : 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 : 360 : const int rc = run(
195 : 40 : {QStringLiteral("--local-user"), m_keys.first(), QStringLiteral("--yes"),
196 : 40 : QStringLiteral("--detach-sign"), QStringLiteral("--output"),
197 : 40 : Executor::translatePathForWsl(output, m_gpg), QStringLiteral("-")},
198 : : nullptr, error, text);
199 [ + + ]: 40 : if (rc != 0) {
200 : 5 : qCDebug(lcQtPass) << "GPG signing failed with code:" << rc;
201 : 5 : return false;
202 : : }
203 : 35 : QFile signature(output);
204 [ + + + + : 35 : if (!signature.open(QIODevice::ReadOnly) || signature.size() <= 0) {
+ + ]
205 [ + - ]: 2 : if (error)
206 : : *error =
207 : 4 : QCoreApplication::translate("GpgIdSigner", "gpg wrote no signature");
208 : 2 : return false;
209 : : }
210 : 33 : const QByteArray bytes = signature.readAll();
211 : 33 : 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 : 33 : GpgIdSigner scratchSigner = *this;
218 : 33 : scratchSigner.m_storeRoot.clear();
219 [ + + + ]: 33 : if (!scratchSigner.verify(contents, output)) {
220 [ + - ]: 4 : if (error)
221 : 8 : *error = QCoreApplication::translate(
222 : : "GpgIdSigner",
223 : : "the new signature does not verify as one of the signing keys");
224 : 4 : return false;
225 : : }
226 : 58 : return Util::writeFileReplacing(gpgIdFile + QStringLiteral(".sig"), bytes,
227 : : true, error);
228 : 148 : }
229 : :
230 : 163 : auto 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 : 12 : R"(^\[GNUPG:\] VALIDSIG ([A-F0-9]{40}(?:[A-F0-9]{24})?) .* )"
235 : : R"(([A-F0-9]{40}(?:[A-F0-9]{24})?)\r?$)",
236 [ + + + - : 187 : 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 : 6 : QStringLiteral(R"(^\[GNUPG:\] (?:REVKEYSIG|KEYREVOKED)\b)"),
245 [ + + + - : 175 : QRegularExpression::MultilineOption);
+ ]
246 : : static const QRegularExpression newSig(
247 : 6 : QStringLiteral(R"(^\[GNUPG:\] NEWSIG\b)"),
248 [ + + + - : 175 : QRegularExpression::MultilineOption);
+ ]
249 : 163 : const QRegularExpressionMatch m = re.match(statusOutput);
250 [ + + + ]: 163 : if (!m.hasMatch()) {
251 : 5 : return {};
252 : : }
253 : : const qsizetype from =
254 [ + + ]: 158 : statusOutput.lastIndexOf(newSig, m.capturedStart()) < 0
255 [ + + ]: 158 : ? 0
256 : 47 : : statusOutput.lastIndexOf(newSig, m.capturedStart());
257 : 158 : const qsizetype to = statusOutput.indexOf(newSig, m.capturedEnd());
258 [ + + + ]: 158 : const QString block = statusOutput.mid(from, to < 0 ? -1 : to - from);
259 [ + + + + ]: 158 : if (revoked.match(block).hasMatch()) {
260 : 4 : return {};
261 : : }
262 : 462 : return {m.captured(1), m.captured(2)};
263 : 317 : }
264 : :
265 : 334 : auto GpgIdSigner::readOwnFile(const QString &path, qint64 maxBytes) const
266 : : -> std::optional<QByteArray> {
267 : : return m_storeRoot.isEmpty()
268 [ + + ]: 334 : ? Util::readRegularFile(path, maxBytes)
269 : 334 : : Util::readRegularFileInStore(m_storeRoot, path, maxBytes);
270 : : }
271 : :
272 : 194 : auto GpgIdSigner::verify(const QByteArray &contents,
273 : : const QString &signatureFile) const -> bool {
274 : 194 : m_refusal.clear();
275 [ + + ]: 194 : 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 [ + + ]: 193 : if (text.toUtf8() != contents) {
284 : 1 : qCDebug(lcQtPass) << "Refusing to verify" << signatureFile
285 : 0 : << ": the signed file is not valid UTF-8";
286 : 1 : 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 [ + + + - : 204 : QStringLiteral(R"(\A(?:tree|object) [0-9a-f]{40}(?:[0-9a-f]{24})?\n)"));
+ ]
298 [ + + + + ]: 192 : if (commitOrTag.match(text).hasMatch()) {
299 : 3 : qCDebug(lcQtPass) << "Refusing to verify" << signatureFile
300 : 0 : << ": the signed data is a git commit or tag object";
301 : 3 : 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 [ + + + ]: 189 : if (Util::isLinkedFolder(signatureFile)) {
306 : 1 : qCDebug(lcQtPass) << "Refusing to verify" << signatureFile
307 : 0 : << ": the signature file is a link";
308 : 1 : 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 : 188 : readOwnFile(signatureFile, kMaxSignatureBytes);
317 [ + + ]: 188 : if (!signature) {
318 : 32 : qCDebug(lcQtPass) << "Refusing to verify" << signatureFile
319 : 0 : << ": not a regular file of at most" << kMaxSignatureBytes
320 : 0 : << "bytes";
321 : 32 : return false;
322 : : }
323 : 156 : QTemporaryDir scratch;
324 [ + + - ]: 156 : if (!scratch.isValid()) {
325 : : return false;
326 : : }
327 : 312 : const QString copy = scratch.filePath(QStringLiteral("sig"));
328 : : {
329 : 156 : QFile file(copy);
330 [ + + - - : 312 : if (!file.open(QIODevice::WriteOnly) ||
+ ]
331 : 156 : file.write(*signature) != signature->size()) {
332 : : return false;
333 : : }
334 : 156 : }
335 : 156 : QString out;
336 : 156 : 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 : 1716 : run({QStringLiteral("--batch"), QStringLiteral("--trust-model=pgp"),
350 : 156 : QStringLiteral("--no-auto-check-trustdb"),
351 : 156 : QStringLiteral("--verify"), QStringLiteral("--status-fd=1"),
352 : 156 : QStringLiteral("--"), sig, QStringLiteral("-")},
353 : : &out, nullptr, text);
354 [ + + ]: 156 : if (rc != 0) {
355 : 3 : qCDebug(lcQtPass) << "GPG verify failed with code:" << rc;
356 : 3 : return false;
357 : : }
358 : 153 : const QStringList fingerprints = validSigFingerprints(out);
359 [ + + ]: 162 : for (const QString &key : m_keys) {
360 [ + + ]: 154 : if (fingerprints.contains(key)) {
361 : 290 : return heldByOneKey(fingerprints.value(0));
362 : : }
363 : : }
364 : : return false;
365 : 156 : }
366 : :
367 : 145 : auto 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 : 145 : QStringLiteral("--batch"), QStringLiteral("--with-colons"),
376 : 870 : QStringLiteral("--list-keys"), QStringLiteral("--"), signingFingerprint};
377 : 145 : QString listing;
378 : 145 : QString listErr;
379 : 145 : int rc = run(QStringList{QStringLiteral("--list-filter"),
380 : 580 : QStringLiteral("select=key_size>0")} +
381 : 145 : listArgs,
382 : 145 : &listing, &listErr, QString());
383 [ + + - + ]: 147 : if (rc != 0 && listErr.contains(QLatin1String("list-filter"))) {
384 : 2 : listing.clear();
385 : 4 : rc = run(listArgs, &listing, nullptr, QString());
386 : : }
387 [ - + ]: 145 : if (rc != 0) {
388 : 0 : qCDebug(lcQtPass) << "Refusing the signature: gpg cannot list the key"
389 : 0 : << signingFingerprint;
390 : 0 : return false;
391 : : }
392 : : // Each block by its first user ID, or its key ID when it has none.
393 : 145 : QStringList holders;
394 : : bool named = true;
395 [ + + + + : 568 : for (const QString &line : listing.split(QLatin1Char('\n'))) {
+ ]
396 : 423 : const QStringList field = line.split(QLatin1Char(':'));
397 [ + + ]: 846 : if (field.value(0) == QLatin1String("pub")) {
398 : 294 : holders << field.value(4);
399 : : named = false;
400 [ + + - + : 552 : } else if (field.value(0) == QLatin1String("uid") && !named &&
- + + + ]
401 : : !holders.isEmpty()) {
402 : 60 : holders.last() = QStringLiteral("%1 (%2)").arg(
403 : 60 : Util::displayable(field.value(9)), holders.last());
404 : : named = true;
405 : : }
406 : : }
407 [ + + ]: 145 : if (holders.size() != 1) {
408 : 4 : qCDebug(lcQtPass) << "Refusing the signature:" << holders.size()
409 : 0 : << "key blocks hold the signing key"
410 : 0 : << signingFingerprint;
411 [ + + ]: 4 : if (holders.size() > 1) {
412 : : m_refusal =
413 : 3 : 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 : 6 : .arg(signingFingerprint, holders.join(QStringLiteral(", ")));
422 : : }
423 : 4 : return false;
424 : : }
425 : : return true;
426 : : }
427 : :
428 : 147 : auto 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 [ + + ]: 147 : if (Util::isLinkedFolder(gpgIdFile)) {
433 : 1 : contents->clear();
434 : 1 : 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 =
439 : 146 : readOwnFile(gpgIdFile, Util::kMaxGpgIdBytes);
440 [ + + ]: 146 : if (!bytes) {
441 : 13 : contents->clear();
442 : : return false;
443 : : }
444 : : *contents = *std::move(bytes);
445 : 266 : return verify(*contents, gpgIdFile + QStringLiteral(".sig"));
446 : : }
|