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 ImportKeyDialog: the guarded key-file read, the blocking
6 : : * `gpg --import` call and the status-line parser for the imported key id.
7 : : */
8 : : #include "importkeydialog.h"
9 : : #include "plainmessagebox.h"
10 : : #include "util.h"
11 : :
12 : : #include "executor.h"
13 : : #include "ui_importkeydialog.h"
14 : :
15 : : #include <QApplication>
16 : : #include <QClipboard>
17 : : #include <QElapsedTimer>
18 : : #include <QFile>
19 : : #include <QFileDialog>
20 : : #include <QFileInfo>
21 : : #include <QMessageBox>
22 : : #include <QPlainTextEdit>
23 : : #include <QProcess>
24 : : #include <QRegularExpression>
25 : : #include <QString>
26 : : #include <utility>
27 : :
28 : : namespace {
29 : :
30 : : /// A line break, a CRLF one included (gpg on Windows). Not
31 : : /// Util::newLinesRegex(): a lone carriage return stays inside its line,
32 : : /// so that one in a user ID gpg echoes cannot start a line of its own.
33 : 57 : auto lineBreak() -> const QRegularExpression & {
34 : 65 : static const QRegularExpression regex(QStringLiteral("\\r?\\n"));
35 : 57 : return regex;
36 : : }
37 : :
38 : : } // namespace
39 : :
40 : 29 : ImportKeyDialog::ImportKeyDialog(QString gpgExe, QWidget *parent, int timeoutMs)
41 : 29 : : QDialog(parent), ui(new Ui::ImportKeyDialog), m_gpgExe(std::move(gpgExe)),
42 : 29 : m_timeoutMs(timeoutMs) {
43 : 29 : ui->setupUi(this);
44 : 29 : ui->importButton->setEnabled(false);
45 : 29 : }
46 : :
47 : 58 : ImportKeyDialog::~ImportKeyDialog() = default;
48 : :
49 : 13 : auto ImportKeyDialog::importedKeyId() const -> QString {
50 : 13 : return m_importedKeyId;
51 : : }
52 : :
53 : : // Every character the editor starts a new block (or line) at counts, as
54 : : // QTextCursor::insertText() splits: LF, a CR alone or before an LF (one
55 : : // separator), the paragraph and line separators and Qt's frame markers. A
56 : : // CR ignored, a file of CRs only made millions of blocks all the same.
57 : 19 : auto ImportKeyDialog::fitsTheEditor(QStringView text) -> bool {
58 : : qsizetype lines = 1;
59 : : qsizetype run = 0;
60 [ + + ]: 3927932 : for (qsizetype i = 0; i < text.size(); ++i) {
61 [ + + + ]: 3927924 : switch (text.at(i).unicode()) {
62 : 786431 : case u'\r':
63 [ + + + + ]: 786431 : if (i + 1 < text.size() && text.at(i + 1) == QLatin1Char('\n')) {
64 : : ++i;
65 : : }
66 : : [[fallthrough]];
67 : : case u'\n':
68 : : case QChar::LineSeparator:
69 : : case QChar::ParagraphSeparator:
70 : : case 0xFDD0: // QTextBeginningOfFrame
71 : : case 0xFDD1: // QTextEndOfFrame
72 [ + + ]: 2641451 : if (++lines > kMaxKeyLines) {
73 : : return false;
74 : : }
75 : : run = 0;
76 : : break;
77 : 1286473 : default:
78 [ + + ]: 1286473 : if (++run > kMaxKeyLine) {
79 : : return false;
80 : : }
81 : : }
82 : : }
83 : : return true;
84 : : }
85 : :
86 : : /**
87 : : * @brief The message for text that fails ImportKeyDialog::fitsTheEditor().
88 : : * @param what What holds the text: a file name, or "The clipboard".
89 : : * @return The plain-text message.
90 : : */
91 : 3 : static auto notLaidOutLikeAKey(const QString &what) -> QString {
92 : 3 : return QCoreApplication::translate(
93 : : "ImportKeyDialog",
94 : : "%1 is not laid out like an ASCII-armored key: it has a line of "
95 : : "more than %2 characters or more than %3 lines.")
96 : 6 : .arg(what, QString::number(ImportKeyDialog::kMaxKeyLine),
97 [ + + ]: 9 : QString::number(ImportKeyDialog::kMaxKeyLines));
98 : : }
99 : :
100 : 8 : void ImportKeyDialog::on_fileButton_clicked() {
101 : : const QString fileName = QFileDialog::getOpenFileName(
102 : 16 : this, tr("Import GPG key"), QString(),
103 [ + + + + : 32 : tr("ASCII-armored GPG key") + " (*.asc);;" + tr("All files") + " (*)");
+ + ]
104 : :
105 [ + + ]: 8 : if (fileName.isEmpty()) {
106 : : return;
107 : : }
108 : :
109 : : // A key file, so a regular one of sensible size: a FIFO would block the
110 : : // GUI and /dev/zero (or a sparse file) would be read without end.
111 : : constexpr qint64 kMaxKeyFileBytes = 16LL * 1024 * 1024;
112 : : // A link is followed, deliberately: the user picked this file, unlike a
113 : : // name found in the store. Its target is then opened as the regular file
114 : : // it is at the moment of the open, without blocking: a FIFO swapped in
115 : : // after the pick would otherwise hang the GUI waiting for a writer.
116 : 7 : QFile file;
117 : 7 : const QString target = QFileInfo(fileName).canonicalFilePath();
118 [ + - + + : 7 : if (target.isEmpty() || !Util::openRegularFile(target, file)) {
+ ]
119 : 4 : PlainMessageBox::warning(this, tr("Import key"),
120 : 4 : tr("Could not open file: %1").arg(fileName));
121 : 2 : return;
122 : : }
123 : :
124 : : // The size first, so a large file is not read at all; the read limit
125 : : // still guards one that grows meanwhile.
126 : 5 : const bool tooLarge = file.size() > kMaxKeyFileBytes;
127 : : const QByteArray bytes =
128 [ - + + ]: 5 : tooLarge ? QByteArray() : file.read(kMaxKeyFileBytes + 1);
129 : 5 : file.close();
130 [ + - + - ]: 5 : if (tooLarge || bytes.size() > kMaxKeyFileBytes) {
131 : 0 : PlainMessageBox::warning(
132 : 0 : this, tr("Import key"),
133 : 0 : tr("%1 is larger than a key file can be.").arg(fileName));
134 : 0 : return;
135 : : }
136 : :
137 : : // Only ASCII-armored content is shown in the text edit; binary keyrings
138 : : // would lose bytes through UTF-8 conversion. Reject anything that doesn't
139 : : // start with the PGP armor header.
140 [ + + ]: 5 : if (!bytes.trimmed().startsWith("-----BEGIN PGP")) {
141 : : // Message body is rich text (uses <code>/<b>); escape the path so any
142 : : // characters in it cannot reach the HTML subset Qt renders.
143 : 2 : QMessageBox::warning(
144 : 1 : this, tr("Import key"),
145 : 1 : tr("%1 does not look like an ASCII-armored GPG key. Convert it with "
146 : : "<code>gpg --armor --export</code> first, or paste the armored "
147 : : "block via <b>From clipboard</b>.")
148 [ + + ]: 2 : .arg(fileName.toHtmlEscaped()));
149 : 1 : return;
150 : : }
151 : :
152 : : const QString text = QString::fromUtf8(bytes);
153 [ + + + ]: 4 : if (!fitsTheEditor(text)) {
154 : 4 : PlainMessageBox::warning(this, tr("Import key"),
155 : 4 : notLaidOutLikeAKey(fileName));
156 : : return;
157 : : }
158 : 2 : ui->inputTextEdit->setPlainText(text);
159 : 7 : }
160 : :
161 : 3 : void ImportKeyDialog::on_pasteButton_clicked() {
162 : 3 : const QClipboard *clipboard = QApplication::clipboard();
163 : 3 : const QString text = clipboard->text();
164 [ + + ]: 3 : if (text.isEmpty()) {
165 : : // Don't wipe whatever the user already typed/loaded for an empty
166 : : // clipboard.
167 : : return;
168 : : }
169 [ + + + ]: 2 : if (!fitsTheEditor(text)) {
170 : 2 : PlainMessageBox::warning(this, tr("Import key"),
171 : 1 : notLaidOutLikeAKey(tr("The clipboard")));
172 : 1 : return;
173 : : }
174 : 1 : ui->inputTextEdit->setPlainText(text);
175 : : }
176 : :
177 : 14 : void ImportKeyDialog::on_importButton_clicked() {
178 : 28 : const QString input = ui->inputTextEdit->toPlainText().trimmed();
179 [ + + ]: 14 : if (input.isEmpty()) {
180 : : return;
181 : : }
182 : :
183 [ + + + ]: 13 : if (importFromString(input)) {
184 : 4 : accept();
185 : : }
186 : : }
187 : :
188 : 22 : void ImportKeyDialog::on_inputTextEdit_textChanged() {
189 : 66 : const bool hasInput = !ui->inputTextEdit->toPlainText().trimmed().isEmpty();
190 : 22 : ui->importButton->setEnabled(hasInput);
191 : 22 : }
192 : :
193 : 13 : bool ImportKeyDialog::importFromString(const QString &input) {
194 : 13 : QElapsedTimer timer;
195 : 13 : timer.start();
196 : :
197 : : // gpg imports every key in the block, and all the user learns is the one
198 : : // fingerprint named below. List the block first, writing nothing, so a
199 : : // second key or a private key cannot come along unmentioned. Both runs
200 : : // skip gpg.conf, so they judge the block alike: a list-filter there hides
201 : : // keys from this listing only, and allow-non-selfsigned-uid lets the
202 : : // import take a key the listing would have skipped.
203 : 13 : QString listing;
204 : 13 : QString listErr;
205 [ + + + + : 117 : if (!runGpg({QStringLiteral("--no-options"), QStringLiteral("--batch"),
+ - - ]
206 : 13 : QStringLiteral("--with-colons"),
207 : 13 : QStringLiteral("--import-options"), QStringLiteral("show-only"),
208 : 13 : QStringLiteral("--import")},
209 : : input, &listing, &listErr, timer)) {
210 : : return false;
211 : : }
212 : 10 : const BlockKeys keys = keysInBlock(listing);
213 [ + + ]: 10 : if (keys.secretKeys > 0) {
214 : 2 : showError(tr("This text holds a private key. QtPass imports public keys "
215 : : "only, so nothing was imported. Import the public key: "
216 : : "gpg --armor --export writes it."));
217 : 2 : return false;
218 : : }
219 [ + + ]: 8 : if (keys.publicKeys == 0) {
220 : 1 : showError(tr("gpg found no key in this text, so nothing was imported."));
221 : 1 : return false;
222 : : }
223 [ + + ]: 7 : if (keys.publicKeys > 1) {
224 : 2 : showError(tr("This text holds %n keys. QtPass imports one key at a time "
225 : : "and names it, so you can check its fingerprint: nothing "
226 : : "was imported. Import each key on its own.",
227 : : nullptr, keys.publicKeys));
228 : 2 : return false;
229 : : }
230 : :
231 : 5 : QString stdOut;
232 : 5 : QString stdErr;
233 [ + + + + : 45 : if (!runGpg({QStringLiteral("--no-options"), QStringLiteral("--status-fd"),
- - - ]
234 : 5 : QStringLiteral("1"), QStringLiteral("--import"),
235 : 5 : QStringLiteral("--batch"), QStringLiteral("--yes")},
236 : : input, &stdOut, &stdErr, timer)) {
237 : : return false;
238 : : }
239 : :
240 : 5 : QString keyId = parseGpgImportOutput(stdOut);
241 [ + + ]: 5 : if (keyId.isEmpty()) {
242 : 4 : keyId = parseGpgImportOutput(stdErr);
243 : : }
244 : :
245 [ + + ]: 5 : if (keyId.isEmpty()) {
246 : 1 : showError(tr("Could not parse imported key id from GPG output."));
247 : 1 : return false;
248 : : }
249 : :
250 : 4 : m_importedKeyId = keyId;
251 : 4 : showSuccess(keyId);
252 : : return true;
253 : : }
254 : :
255 : 18 : auto ImportKeyDialog::runGpg(const QStringList &args, const QString &input,
256 : : QString *stdOut, QString *stdErr,
257 : : const QElapsedTimer &timer) -> bool {
258 [ - + ]: 18 : const QString gpgExe = m_gpgExe.isEmpty() ? QStringLiteral("gpg") : m_gpgExe;
259 : 18 : const qint64 left = m_timeoutMs - timer.elapsed();
260 : : int result = -1;
261 [ + - ]: 18 : if (left > 0) {
262 : 18 : QProcess gpg;
263 : 18 : result = Executor::executeBlocking(gpg, gpgExe, args, input, stdOut, stdErr,
264 : : nullptr, static_cast<int>(left));
265 : 18 : }
266 [ + + + + ]: 18 : if (result != 0 && timer.elapsed() >= m_timeoutMs) {
267 : 1 : const int seconds = (m_timeoutMs + 999) / 1000;
268 : 1 : showError(tr("gpg did not finish the import within %n second(s) and was "
269 : : "stopped. Part of the key may be in your keyring already: "
270 : : "check it with gpg --list-keys before you use it.",
271 : : nullptr, seconds));
272 : 1 : return false;
273 : : }
274 [ + + ]: 17 : if (result != 0) {
275 : 4 : showError(tr("GPG import failed:\n%1").arg(*stdErr));
276 : 2 : return false;
277 : : }
278 : : return true;
279 : : }
280 : :
281 : 16 : auto ImportKeyDialog::keysInBlock(const QString &listing) -> BlockKeys {
282 : : BlockKeys keys;
283 : 16 : const QStringList lines = listing.split(lineBreak(), Qt::SkipEmptyParts);
284 [ + + ]: 72 : for (const QString &line : lines) {
285 [ + + + ]: 56 : if (line.startsWith(QLatin1String("pub:"))) {
286 : 16 : ++keys.publicKeys;
287 [ + + + ]: 40 : } else if (line.startsWith(QLatin1String("sec:"))) {
288 : 4 : ++keys.secretKeys;
289 : : }
290 : : }
291 : 16 : return keys;
292 : : }
293 : :
294 : 41 : auto ImportKeyDialog::parseGpgImportOutput(const QString &output) -> QString {
295 : : // Line by line, a CRLF end included (gpg on Windows): the patterns are
296 : : // anchored at both ends of the line.
297 : 41 : const QStringList lines = output.split(lineBreak(), Qt::SkipEmptyParts);
298 : : // Locale-independent: gpg's machine-readable status output via --status-fd 1.
299 : : // See doc/DETAILS in the GnuPG source for IMPORT_OK / IMPORTED grammar.
300 : : // All three are anchored at the start of the line: gpg echoes the key's
301 : : // user ID, which whoever made the key chooses, on the IMPORTED line and in
302 : : // the human line, so "[GNUPG:] IMPORT_OK 1 <hex>" inside a user ID must not
303 : : // pass for gpg's own status line and name the fingerprint to verify.
304 : : // `[GNUPG:] IMPORT_OK <reason> <fingerprint>`: captures the full fingerprint
305 : : // (40 hex, or 64 for v5/v6 keys), the preferred identifier, which ends the
306 : : // line.
307 : 2 : static const QRegularExpression importOk(QStringLiteral(
308 [ + + + - : 45 : R"(^\[GNUPG:\] IMPORT_OK \d+ ([0-9A-Fa-f]{40}|[0-9A-Fa-f]{64})$)"));
+ ]
309 : : // `[GNUPG:] IMPORTED <keyid> <userid>`: captures the 16-hex long key id,
310 : : // tried after importOk.
311 : : static const QRegularExpression imported(
312 [ + + + - : 45 : QStringLiteral(R"(^\[GNUPG:\] IMPORTED ([0-9A-Fa-f]{16})(?: |$))"));
+ ]
313 : : // Fallback for the human-readable (English-locale) `gpg: key <id>: ...
314 : : // imported` line, last resort when no status line was seen.
315 : 2 : static const QRegularExpression humanImported(QStringLiteral(
316 [ + + + - : 45 : R"(^gpg: key ([0-9A-Fa-f]{40}|[0-9A-Fa-f]{16}):.*imported)"));
+ ]
317 : : // The order here is the priority order: prefer the locale-independent
318 : : // status lines over the English human-readable line, and within the
319 : : // status lines prefer IMPORT_OK (full fingerprint) over IMPORTED
320 : : // (long key id). Each regex is scanned across every line before we
321 : : // fall through to the next regex; the per-line ordering of gpg's
322 : : // output (which emits IMPORTED before IMPORT_OK) must not pick the
323 : : // weaker identifier.
324 [ + + ]: 70 : for (const QString &line : lines) {
325 : 45 : const QRegularExpressionMatch match = importOk.match(line);
326 [ + + + ]: 45 : if (match.hasMatch()) {
327 : 16 : return match.captured(1);
328 : : }
329 : 45 : }
330 [ + + ]: 44 : for (const QString &line : lines) {
331 : 24 : const QRegularExpressionMatch match = imported.match(line);
332 [ + + + ]: 24 : if (match.hasMatch()) {
333 : 5 : return match.captured(1);
334 : : }
335 : 24 : }
336 [ + + ]: 33 : for (const QString &line : lines) {
337 : 19 : const QRegularExpressionMatch match = humanImported.match(line);
338 [ + + + ]: 19 : if (match.hasMatch()) {
339 : 6 : return match.captured(1);
340 : : }
341 : 19 : }
342 : 14 : return {};
343 : : }
344 : :
345 : 9 : void ImportKeyDialog::showError(const QString &message) {
346 : : // gpg's stderr quotes user IDs ("Name <a@b>"): plain, so they show as
347 : : // written and cannot be markup.
348 : 9 : PlainMessageBox::warning(this, tr("Import key"), message);
349 : 9 : }
350 : :
351 : 4 : void ImportKeyDialog::showSuccess(const QString &keyId) {
352 : 12 : QMessageBox::information(this, tr("Import key"),
353 : 4 : tr("Public key %1 imported. Check its fingerprint "
354 : : "with its owner before encrypting to it: "
355 : : "importing a key says nothing about who holds "
356 : : "it.")
357 : 8 : .arg(keyId));
358 : 4 : }
|