11#include <QCoreApplication>
13#include <QProcessEnvironment>
14#include <QRegularExpression>
15#include <QTemporaryDir>
23 :
m_gpg(std::move(gpgExecutable)),
m_keys(std::move(signingKeys)),
26 m_exec = [](
const QString &app,
const QStringList &args,
27 const QString &input, QString *out, QString *err) {
35 QStringList
keys = passSigningKey.split(QLatin1Char(
' '), Qt::SkipEmptyParts);
38 for (QString &key :
keys) {
45 QString own = passSigningKey.trimmed();
49 return QProcessEnvironment::systemEnvironment()
50 .value(QStringLiteral(
"PASSWORD_STORE_SIGNING_KEY"))
55 const QString &input)
const ->
int {
74auto signingBlocks(
const QString &out) -> QList<QList<Key>> {
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")) {
91 blocks.append(QList<Key>());
93 if (blocks.isEmpty()) {
97 const QString validity = fields.value(1);
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);
107 }
else if (type == QLatin1String(
"fpr") && awaitingFpr) {
108 blocks.last().last().fpr = fields.value(9);
121auto signsWith(
const QList<QList<Key>> &blocks,
const QString &key) ->
bool {
125 for (
const QList<Key> &block : std::as_const(blocks)) {
127 if (block.isEmpty() || !block.first().valid) {
130 for (
const Key &k : block) {
131 if (k.fpr.compare(key, Qt::CaseInsensitive) != 0) {
137 if (k.primary && std::any_of(block.cbegin(), block.cend(),
138 [](
const Key &sub) { return sub.signs; })) {
153 const QString &key =
m_keys.first();
156 run({QStringLiteral(
"--with-colons"), QStringLiteral(
"--fixed-list-mode"),
157 QStringLiteral(
"--list-secret-keys"), QStringLiteral(
"--"), key},
160 qCDebug(lcQtPass) <<
"GPG list-secret-keys failed with code:" << rc;
163 return signsWith(signingBlocks(out), key);
167 QString *error)
const ->
bool {
173 <<
"Multiple signing keys configured; using only the first key:"
177 const QString text = QString::fromUtf8(contents);
178 if (text.toUtf8() != contents) {
180 *error = QCoreApplication::translate(
181 "GpgIdSigner",
"the recipient list is not valid UTF-8");
184 QTemporaryDir scratch;
185 if (!scratch.isValid()) {
187 *error = scratch.errorString();
190 const QString output = scratch.filePath(QStringLiteral(
"sig"));
195 {QStringLiteral(
"--local-user"),
m_keys.first(), QStringLiteral(
"--yes"),
196 QStringLiteral(
"--detach-sign"), QStringLiteral(
"--output"),
198 nullptr, error, text);
200 qCDebug(lcQtPass) <<
"GPG signing failed with code:" << rc;
203 QFile signature(output);
204 if (!signature.open(QIODevice::ReadOnly) || signature.size() <= 0) {
207 QCoreApplication::translate(
"GpgIdSigner",
"gpg wrote no signature");
210 const QByteArray bytes = signature.readAll();
219 if (!scratchSigner.
verify(contents, output)) {
221 *error = QCoreApplication::translate(
223 "the new signature does not verify as one of the signing keys");
232 static const QRegularExpression re(
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);
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);
253 const qsizetype from =
254 statusOutput.lastIndexOf(newSig, m.capturedStart()) < 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()) {
262 return {m.captured(1), m.captured(2)};
266 -> std::optional<QByteArray> {
273 const QString &signatureFile)
const ->
bool {
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";
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";
306 qCDebug(lcQtPass) <<
"Refusing to verify" << signatureFile
307 <<
": the signature file is a link";
315 const std::optional<QByteArray> signature =
318 qCDebug(lcQtPass) <<
"Refusing to verify" << signatureFile
323 QTemporaryDir scratch;
324 if (!scratch.isValid()) {
327 const QString copy = scratch.filePath(QStringLiteral(
"sig"));
330 if (!file.open(QIODevice::WriteOnly) ||
331 file.write(*signature) != signature->size()) {
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);
355 qCDebug(lcQtPass) <<
"GPG verify failed with code:" << rc;
359 for (
const QString &key :
m_keys) {
360 if (fingerprints.contains(key)) {
374 const QStringList listArgs{
375 QStringLiteral(
"--batch"), QStringLiteral(
"--with-colons"),
376 QStringLiteral(
"--list-keys"), QStringLiteral(
"--"), signingFingerprint};
379 int rc =
run(QStringList{QStringLiteral(
"--list-filter"),
380 QStringLiteral(
"select=key_size>0")} +
382 &listing, &listErr, QString());
383 if (rc != 0 && listErr.contains(QLatin1String(
"list-filter"))) {
385 rc =
run(listArgs, &listing,
nullptr, QString());
388 qCDebug(lcQtPass) <<
"Refusing the signature: gpg cannot list the key"
389 << signingFingerprint;
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);
400 }
else if (field.value(0) == QLatin1String(
"uid") && !named &&
401 !holders.isEmpty()) {
402 holders.last() = QStringLiteral(
"%1 (%2)").arg(
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) {
413 QCoreApplication::translate(
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 "
421 .arg(signingFingerprint, holders.join(QStringLiteral(
", ")));
429 QByteArray *contents)
const ->
bool {
438 std::optional<QByteArray> bytes =
444 *contents = *std::move(bytes);
445 return verify(*contents, gpgIdFile + QStringLiteral(
".sig"));
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.
static auto translatePathForWsl(const QString &path, const QString &exe) -> QString
Translate a native path for a WSL-routed executable.
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.
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.
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().
static constexpr qint64 kMaxGpgIdBytes
Most bytes of a .gpg-id QtPass reads.
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.
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,...
static auto isLinkedFolder(const QString &path) -> bool
Whether path names a symbolic link or NTFS junction, with or without a trailing separator (which woul...
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...
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...