QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
gpgkeystate.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
8#include "gpgkeystate.h"
9#include "gpgkeystate_p.h"
10
11#include "util.h"
12
13#include <QDateTime>
14#include <QRegularExpression>
15
16#include <cctype>
17
19constexpr int GPG_MIN_FIELDS = 10;
21constexpr int GPG_FIELD_VALIDITY = 1;
23constexpr int GPG_FIELD_KEY_ID = 4;
25constexpr int GPG_FIELD_CREATED = 5;
27constexpr int GPG_FIELD_EXPIRY = 6;
29constexpr int GPG_FIELD_USERID = 9;
34constexpr int GPG_FIELD_FINGERPRINT = 9;
35
36auto classifyRecord(const QString &record_type) -> GpgRecordType {
37 if (record_type == "pub") {
38 return GpgRecordType::Pub;
39 }
40 if (record_type == "sec") {
41 return GpgRecordType::Sec;
42 }
43 if (record_type == "uid") {
44 return GpgRecordType::Uid;
45 }
46 if (record_type == "fpr") {
47 return GpgRecordType::Fpr;
48 }
49 if (record_type == "sub") {
50 return GpgRecordType::Sub;
51 }
52 if (record_type == "ssb") {
53 return GpgRecordType::Ssb;
54 }
55 if (record_type == "grp") {
56 return GpgRecordType::Grp;
57 }
59}
60
61void handlePubSecRecord(const QStringList &props, bool secret,
62 UserInfo &current_user) {
63 if (props.size() < GPG_MIN_FIELDS) {
64 return;
65 }
66 current_user.key_id = props[GPG_FIELD_KEY_ID];
67 current_user.name = props[GPG_FIELD_USERID];
68 if (!props[GPG_FIELD_VALIDITY].isEmpty()) {
69 current_user.validity = props[GPG_FIELD_VALIDITY][0].toLatin1();
70 }
71
72 // An empty field (GnuPG's "no expiry") leaves the QDateTime null, so
73 // callers distinguish "unset" from "set" with isValid() alone.
74 bool okCreated = false;
75 const qint64 createdSecs = props[GPG_FIELD_CREATED].toLongLong(&okCreated);
76 if (okCreated) {
77 current_user.created = QDateTime::fromSecsSinceEpoch(createdSecs);
78 }
79
80 bool okExpiry = false;
81 const qint64 expirySecs = props[GPG_FIELD_EXPIRY].toLongLong(&okExpiry);
82 if (okExpiry) {
83 current_user.expiry = QDateTime::fromSecsSinceEpoch(expirySecs);
84 }
85
86 current_user.have_secret = secret;
87}
88
100auto uidNameRank(const QString &validity) -> int {
101 switch (validity.isEmpty() ? '\0' : validity.at(0).toLatin1()) {
102 case 'u':
103 case 'f':
104 return 3;
105 case 'm':
106 return 2;
107 case '-':
108 case 'q':
109 return 1;
110 default:
111 return 0;
112 }
113}
114
121auto decodeColonField(const QString &field) -> QString {
122 if (!field.contains(QLatin1String("\\x"))) {
123 return field;
124 }
125 const QByteArray in = field.toUtf8();
126 const auto isHex = [](char c) {
127 return std::isxdigit(static_cast<unsigned char>(c)) != 0;
128 };
129 QByteArray out;
130 out.reserve(in.size());
131 for (int i = 0; i < in.size(); ++i) {
132 if (in.at(i) == '\\' && i + 3 < in.size() && in.at(i + 1) == 'x' &&
133 isHex(in.at(i + 2)) && isHex(in.at(i + 3))) {
134 out.append(static_cast<char>(in.mid(i + 2, 2).toInt(nullptr, 16)));
135 i += 3;
136 } else {
137 out.append(in.at(i));
138 }
139 }
140 return QString::fromUtf8(out);
141}
142
150void handleUidRecord(const QStringList &props, UserInfo &current_user,
151 int &nameRank) {
152 current_user.uids.append(decodeColonField(props[GPG_FIELD_USERID]));
153 const int rank = uidNameRank(props[GPG_FIELD_VALIDITY]);
154 if (current_user.name.isEmpty() || rank > nameRank) {
155 current_user.name = props[GPG_FIELD_USERID];
156 nameRank = rank;
157 }
158}
159
160void handleFprRecord(const QStringList &props, UserInfo &current_user) {
161 if (props.size() < GPG_MIN_FIELDS) {
162 return;
163 }
164 // GnuPG reports the v4 key ID from the fingerprint's tail, and the v5/v6
165 // key ID from its head. Promote only an exact 16-hex key ID with the
166 // version-specific fingerprint shape and location; malformed or mismatched
167 // input stays a key ID rather than becoming a false full identity.
168 static const QRegularExpression keyIdShape(
169 QStringLiteral("^[0-9A-Fa-f]{16}$"));
170 static const QRegularExpression v4FingerprintShape(
171 QStringLiteral("^[0-9A-Fa-f]{40}$"));
172 static const QRegularExpression v5v6FingerprintShape(
173 QStringLiteral("^[0-9A-Fa-f]{64}$"));
174 const QString &keyId = current_user.key_id;
175 if (!keyIdShape.match(keyId).hasMatch()) {
176 return;
177 }
178
179 const QString &fingerprint = props[GPG_FIELD_FINGERPRINT];
180 const bool isV4 = v4FingerprintShape.match(fingerprint).hasMatch() &&
181 fingerprint.endsWith(keyId, Qt::CaseInsensitive);
182 const bool isV5V6 = v5v6FingerprintShape.match(fingerprint).hasMatch() &&
183 fingerprint.startsWith(keyId, Qt::CaseInsensitive);
184 if (isV4 || isV5V6) {
185 current_user.key_id = fingerprint;
186 }
187}
188
189namespace {
190
195struct ColonListing {
196 QList<UserInfo> users;
197 UserInfo current;
201 bool expectPrimaryFingerprint{};
203 bool expectSubkeyFingerprint{};
206 int nameRank = 0;
207
211 void keepCurrent() {
212 if (!current.key_id.isEmpty()) {
213 users.append(current);
214 }
215 }
216
220 void takeShort() {
221 expectPrimaryFingerprint = false;
222 expectSubkeyFingerprint = false;
223 }
224
231 void startKey(const QStringList &props, bool secret) {
232 keepCurrent();
233 current = UserInfo();
234 handlePubSecRecord(props, secret, current);
235 nameRank = current.name.isEmpty() ? 0 : 1;
236 expectPrimaryFingerprint = true;
237 expectSubkeyFingerprint = false;
238 }
239
244 void takeUid(const QStringList &props) {
245 expectPrimaryFingerprint = false;
246 handleUidRecord(props, current, nameRank);
247 expectSubkeyFingerprint = false;
248 }
249
254 void takeSubkey(const QStringList &props) {
255 expectPrimaryFingerprint = false;
256 if (!props[GPG_FIELD_KEY_ID].isEmpty()) {
257 current.subkeys.append(props[GPG_FIELD_KEY_ID]);
258 }
259 expectSubkeyFingerprint = true;
260 }
261
266 void takeFingerprint(const QStringList &props) {
267 if (expectPrimaryFingerprint) {
268 handleFprRecord(props, current);
269 expectPrimaryFingerprint = false;
270 } else if (expectSubkeyFingerprint &&
271 !props[GPG_FIELD_FINGERPRINT].isEmpty()) {
272 current.subkeys.append(props[GPG_FIELD_FINGERPRINT]);
273 }
274 expectSubkeyFingerprint = false;
275 }
276};
277
278} // namespace
279
280auto parseGpgColonOutput(const QString &output, bool secret)
281 -> QList<UserInfo> {
282 const QStringList lines =
283 output.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
284
285 ColonListing listing;
286 for (const QString &key : lines) {
287 QStringList props = key.split(':');
288 if (props.size() < GPG_MIN_FIELDS) {
289 listing.takeShort();
290 continue;
291 }
292
293 const QString &record_type = props[0];
294 const GpgRecordType type = classifyRecord(record_type);
295 switch (type) {
298 listing.startKey(props, secret && (type == GpgRecordType::Sec));
299 break;
301 listing.takeUid(props);
302 break;
305 listing.takeSubkey(props);
306 break;
308 listing.takeFingerprint(props);
309 break;
310 default:
311 break;
312 }
313 }
314
315 listing.keepCurrent();
316 return listing.users;
317}
318
319auto primaryFingerprintOf(const QString &output, const QString &key)
320 -> QString {
321 const QStringList holders = blocksHolding(output, key);
322 return holders.size() == 1 ? holders.first() : QString();
323}
324
325namespace {
332auto bareKey(const QString &key) -> QString {
333 QString wanted = key.trimmed().toUpper();
334 if (wanted.endsWith(QLatin1Char('!'))) {
335 wanted.chop(1);
336 }
337 if (wanted.startsWith(QLatin1String("0X"))) {
338 wanted.remove(0, 2);
339 }
340 return wanted;
341}
342
350void addHolder(QStringList &holders, const QString &primary, bool holds) {
351 if (holds && !primary.isEmpty() && !holders.contains(primary)) {
352 holders << primary;
353 }
354}
355} // namespace
356
357auto blocksHolding(const QString &output, const QString &key) -> QStringList {
358 const QString wanted = bareKey(key);
359 if (wanted.isEmpty()) {
360 return {};
361 }
362 const bool isId = wanted.size() == 8 || wanted.size() == 16;
363 QStringList holders;
364 QString primary;
365 bool expectPrimary = false;
366 bool holds = false;
367 // A pub or sub record carries the key's own ID: the fingerprint's tail
368 // for v4 keys, its head for v5/v6. A short ID is the long one's tail.
369 const auto namesKeyId = [&](const QStringList &props) {
370 return isId && props[GPG_FIELD_KEY_ID].toUpper().endsWith(wanted);
371 };
372 const auto endBlock = [&] {
373 addHolder(holders, primary, holds);
374 primary.clear();
375 holds = false;
376 };
377 const QStringList lines =
378 output.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
379 for (const QString &line : lines) {
380 const QStringList props = line.split(QLatin1Char(':'));
381 if (props.size() < GPG_MIN_FIELDS) {
382 continue;
383 }
384 switch (classifyRecord(props[0])) {
386 endBlock();
387 expectPrimary = true;
388 holds = holds || namesKeyId(props);
389 break;
391 expectPrimary = false;
392 holds = holds || namesKeyId(props);
393 break;
395 if (expectPrimary) {
396 primary = props[GPG_FIELD_FINGERPRINT].toUpper();
397 expectPrimary = false;
398 }
399 if (!isId && props[GPG_FIELD_FINGERPRINT].toUpper() == wanted) {
400 holds = true;
401 }
402 break;
403 default:
404 break;
405 }
406 }
407 endBlock();
408 return holders;
409}
static auto newLinesRegex() -> const QRegularExpression &
Returns a regex to match newline characters.
Definition util.cpp:1055
void handlePubSecRecord(const QStringList &props, bool secret, UserInfo &current_user)
Start a key from a pub or sec record: key ID, the user ID the record may carry, validity,...
auto parseGpgColonOutput(const QString &output, bool secret) -> QList< UserInfo >
Parse a gpg colon listing into one UserInfo per key.
auto primaryFingerprintOf(const QString &output, const QString &key) -> QString
The primary key fingerprint of the key that key names.
constexpr int GPG_FIELD_KEY_ID
Field index of the key ID.
constexpr int GPG_FIELD_VALIDITY
Field index of the validity letter (u, f, r, ...).
auto blocksHolding(const QString &output, const QString &key) -> QStringList
The primary fingerprints of every key block in output that holds key, as its primary key or as a subk...
constexpr int GPG_FIELD_EXPIRY
Field index of the expiry time; empty for a key without one.
auto uidNameRank(const QString &validity) -> int
How far a uid record's own validity vouches for its name.
constexpr int GPG_FIELD_CREATED
Field index of the creation time, in seconds since the epoch.
auto decodeColonField(const QString &field) -> QString
Decode a field of GPG colon output: gpg writes a colon, a backslash and control characters in a user ...
constexpr int GPG_MIN_FIELDS
Fewest fields a record must have to be read at all.
auto classifyRecord(const QString &record_type) -> GpgRecordType
Classify a record of a gpg colon listing by its first field.
void handleFprRecord(const QStringList &props, UserInfo &current_user)
Replace the key ID of the key being built with its fingerprint.
void handleUidRecord(const QStringList &props, UserInfo &current_user, int &nameRank)
Handle a uid record in GPG colon output: its name is the key's name unless an earlier uid vouches at ...
constexpr int GPG_FIELD_USERID
Field index of the user ID.
constexpr int GPG_FIELD_FINGERPRINT
Field 9 of an fpr record: the fingerprint, in the slot the user ID occupies in a uid record.
Parsing of gpg --with-colons key listings into UserInfo records.
GpgRecordType
The record types of a gpg --with-colons listing that the parser tells apart; the first field of each ...
Definition gpgkeystate.h:21
Record handlers of the gpg colon-listing parser, declared separately only so the unit tests can call ...
Stores GPG key info including validity, creation date, and more.
Definition userinfo.h:20
bool have_secret
Whether secret key is available (can decrypt with this key).
Definition userinfo.h:72
QStringList uids
Every user ID on the key, revoked ones included, with gpg's colon escapes (such as \x3a) decoded: the...
Definition userinfo.h:58
UserInfo()=default
Construct a UserInfo with default (invalid/disabled) state.
QString key_id
Hexadecimal representation of the GnuPG key identifier.
Definition userinfo.h:53
QDateTime created
Date/time when key was created.
Definition userinfo.h:84
QString name
GPG user ID / full name.
Definition userinfo.h:49
char validity
GnuPG representation of validity. http://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg....
Definition userinfo.h:68
QDateTime expiry
Date/time when key expires.
Definition userinfo.h:80
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...