QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
importkeydialog.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 "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
28namespace {
29
33auto lineBreak() -> const QRegularExpression & {
34 static const QRegularExpression regex(QStringLiteral("\\r?\\n"));
35 return regex;
36}
37
38} // namespace
39
40ImportKeyDialog::ImportKeyDialog(QString gpgExe, QWidget *parent, int timeoutMs)
41 : QDialog(parent), ui(new Ui::ImportKeyDialog), m_gpgExe(std::move(gpgExe)),
42 m_timeoutMs(timeoutMs) {
43 ui->setupUi(this);
44 ui->importButton->setEnabled(false);
45}
46
48
49auto ImportKeyDialog::importedKeyId() const -> QString {
50 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.
57auto ImportKeyDialog::fitsTheEditor(QStringView text) -> bool {
58 qsizetype lines = 1;
59 qsizetype run = 0;
60 for (qsizetype i = 0; i < text.size(); ++i) {
61 switch (text.at(i).unicode()) {
62 case u'\r':
63 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 if (++lines > kMaxKeyLines) {
73 return false;
74 }
75 run = 0;
76 break;
77 default:
78 if (++run > kMaxKeyLine) {
79 return false;
80 }
81 }
82 }
83 return true;
84}
85
91static auto notLaidOutLikeAKey(const QString &what) -> QString {
92 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 .arg(what, QString::number(ImportKeyDialog::kMaxKeyLine),
97 QString::number(ImportKeyDialog::kMaxKeyLines));
98}
99
101 const QString fileName = QFileDialog::getOpenFileName(
102 this, tr("Import GPG key"), QString(),
103 tr("ASCII-armored GPG key") + " (*.asc);;" + tr("All files") + " (*)");
104
105 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 QFile file;
117 const QString target = QFileInfo(fileName).canonicalFilePath();
118 if (target.isEmpty() || !Util::openRegularFile(target, file)) {
119 PlainMessageBox::warning(this, tr("Import key"),
120 tr("Could not open file: %1").arg(fileName));
121 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 const bool tooLarge = file.size() > kMaxKeyFileBytes;
127 const QByteArray bytes =
128 tooLarge ? QByteArray() : file.read(kMaxKeyFileBytes + 1);
129 file.close();
130 if (tooLarge || bytes.size() > kMaxKeyFileBytes) {
132 this, tr("Import key"),
133 tr("%1 is larger than a key file can be.").arg(fileName));
134 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 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 QMessageBox::warning(
144 this, tr("Import key"),
145 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 .arg(fileName.toHtmlEscaped()));
149 return;
150 }
151
152 const QString text = QString::fromUtf8(bytes);
153 if (!fitsTheEditor(text)) {
154 PlainMessageBox::warning(this, tr("Import key"),
155 notLaidOutLikeAKey(fileName));
156 return;
157 }
158 ui->inputTextEdit->setPlainText(text);
159}
160
162 const QClipboard *clipboard = QApplication::clipboard();
163 const QString text = clipboard->text();
164 if (text.isEmpty()) {
165 // Don't wipe whatever the user already typed/loaded for an empty
166 // clipboard.
167 return;
168 }
169 if (!fitsTheEditor(text)) {
170 PlainMessageBox::warning(this, tr("Import key"),
171 notLaidOutLikeAKey(tr("The clipboard")));
172 return;
173 }
174 ui->inputTextEdit->setPlainText(text);
175}
176
178 const QString input = ui->inputTextEdit->toPlainText().trimmed();
179 if (input.isEmpty()) {
180 return;
181 }
182
183 if (importFromString(input)) {
184 accept();
185 }
186}
187
189 const bool hasInput = !ui->inputTextEdit->toPlainText().trimmed().isEmpty();
190 ui->importButton->setEnabled(hasInput);
191}
192
193bool ImportKeyDialog::importFromString(const QString &input) {
194 QElapsedTimer timer;
195 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 QString listing;
204 QString listErr;
205 if (!runGpg({QStringLiteral("--no-options"), QStringLiteral("--batch"),
206 QStringLiteral("--with-colons"),
207 QStringLiteral("--import-options"), QStringLiteral("show-only"),
208 QStringLiteral("--import")},
209 input, &listing, &listErr, timer)) {
210 return false;
211 }
212 const BlockKeys keys = keysInBlock(listing);
213 if (keys.secretKeys > 0) {
214 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 return false;
218 }
219 if (keys.publicKeys == 0) {
220 showError(tr("gpg found no key in this text, so nothing was imported."));
221 return false;
222 }
223 if (keys.publicKeys > 1) {
224 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 return false;
229 }
230
231 QString stdOut;
232 QString stdErr;
233 if (!runGpg({QStringLiteral("--no-options"), QStringLiteral("--status-fd"),
234 QStringLiteral("1"), QStringLiteral("--import"),
235 QStringLiteral("--batch"), QStringLiteral("--yes")},
236 input, &stdOut, &stdErr, timer)) {
237 return false;
238 }
239
240 QString keyId = parseGpgImportOutput(stdOut);
241 if (keyId.isEmpty()) {
242 keyId = parseGpgImportOutput(stdErr);
243 }
244
245 if (keyId.isEmpty()) {
246 showError(tr("Could not parse imported key id from GPG output."));
247 return false;
248 }
249
250 m_importedKeyId = keyId;
251 showSuccess(keyId);
252 return true;
253}
254
255auto ImportKeyDialog::runGpg(const QStringList &args, const QString &input,
256 QString *stdOut, QString *stdErr,
257 const QElapsedTimer &timer) -> bool {
258 const QString gpgExe = m_gpgExe.isEmpty() ? QStringLiteral("gpg") : m_gpgExe;
259 const qint64 left = m_timeoutMs - timer.elapsed();
260 int result = -1;
261 if (left > 0) {
262 QProcess gpg;
263 result = Executor::executeBlocking(gpg, gpgExe, args, input, stdOut, stdErr,
264 nullptr, static_cast<int>(left));
265 }
266 if (result != 0 && timer.elapsed() >= m_timeoutMs) {
267 const int seconds = (m_timeoutMs + 999) / 1000;
268 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 return false;
273 }
274 if (result != 0) {
275 showError(tr("GPG import failed:\n%1").arg(*stdErr));
276 return false;
277 }
278 return true;
279}
280
281auto ImportKeyDialog::keysInBlock(const QString &listing) -> BlockKeys {
282 BlockKeys keys;
283 const QStringList lines = listing.split(lineBreak(), Qt::SkipEmptyParts);
284 for (const QString &line : lines) {
285 if (line.startsWith(QLatin1String("pub:"))) {
286 ++keys.publicKeys;
287 } else if (line.startsWith(QLatin1String("sec:"))) {
288 ++keys.secretKeys;
289 }
290 }
291 return keys;
292}
293
294auto 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 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 static const QRegularExpression importOk(QStringLiteral(
308 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 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 static const QRegularExpression humanImported(QStringLiteral(
316 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 for (const QString &line : lines) {
325 const QRegularExpressionMatch match = importOk.match(line);
326 if (match.hasMatch()) {
327 return match.captured(1);
328 }
329 }
330 for (const QString &line : lines) {
331 const QRegularExpressionMatch match = imported.match(line);
332 if (match.hasMatch()) {
333 return match.captured(1);
334 }
335 }
336 for (const QString &line : lines) {
337 const QRegularExpressionMatch match = humanImported.match(line);
338 if (match.hasMatch()) {
339 return match.captured(1);
340 }
341 }
342 return {};
343}
344
345void 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 PlainMessageBox::warning(this, tr("Import key"), message);
349}
350
351void ImportKeyDialog::showSuccess(const QString &keyId) {
352 QMessageBox::information(this, tr("Import key"),
353 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 .arg(keyId));
358}
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 constexpr qsizetype kMaxKeyLines
Most lines fitsTheEditor() lets through: a 16 MiB key file in armor's 64-character lines.
static auto fitsTheEditor(QStringView text) -> bool
Whether text is laid out as armor can be, so the input field can show it at a bounded cost.
~ImportKeyDialog() override
Destroys the dialog and its generated UI.
static auto parseGpgImportOutput(const QString &output) -> QString
Parse GPG import output to extract a key id or fingerprint.
void showError(const QString &message)
Shows message in a plain-text warning box (gpg's stderr quotes user IDs, which must not be read as ma...
auto importedKeyId() const -> QString
Get the imported key id on success.
static auto keysInBlock(const QString &listing) -> BlockKeys
Count the keys in the listing of gpg --with-colons --import-options show-only --import.
int m_timeoutMs
Most milliseconds gpg may take to import (kImportTimeoutMs).
QString m_importedKeyId
Key id or fingerprint of the last successful import; empty until then. Read back through importedKeyI...
ImportKeyDialog(QString gpgExe, QWidget *parent=nullptr, int timeoutMs=kImportTimeoutMs)
Construct an ImportKeyDialog.
void on_fileButton_clicked()
"From file" button: picks a file, reads it as a regular file of at most 16 MiB, requires the -----BEG...
auto runGpg(const QStringList &args, const QString &input, QString *stdOut, QString *stdErr, const QElapsedTimer &timer) -> bool
Runs gpg with args on input within what is left of m_timeoutMs since timer started.
QString m_gpgExe
Path of the gpg binary to run; empty means plain gpg on PATH.
void on_pasteButton_clicked()
"From clipboard" button: replaces the input field with the clipboard text, unless the clipboard is em...
void showSuccess(const QString &keyId)
Shows the "imported, now verify the fingerprint" information box.
QScopedPointer< Ui::ImportKeyDialog > ui
Generated form (importkeydialog.ui); owned.
auto importFromString(const QString &input) -> bool
Lists the keys in input first, with nothing written, and refuses a block that holds a private key or ...
void on_importButton_clicked()
"Import" button: runs importFromString() on the trimmed input and closes the dialog with accept() on ...
static constexpr qsizetype kMaxKeyLine
Longest line fitsTheEditor() lets through, in characters.
void on_inputTextEdit_textChanged()
Enables the Import button only while the input field holds non-blank text.
static auto openRegularFile(const QString &path, QFile &file) -> bool
Open path for reading as the regular file it is, not as what a link under that name points to: the ob...
Definition util.cpp:1529
Executor, the FIFO queue every gpg, git and pass child process of QtPass goes through,...
static auto notLaidOutLikeAKey(const QString &what) -> QString
The message for text that fails ImportKeyDialog::fitsTheEditor().
Dialog that imports an ASCII-armored GPG public key from a file or the clipboard by running gpg --imp...
void warning(QWidget *parent, const QString &title, const QString &text)
Show a warning in plain text.
QMessageBox helpers that force Qt::PlainText so store-controlled names can never be read as rich-text...
How many keys an armored block holds, by kind.
int publicKeys
Public keys: pub records.
int secretKeys
Keys with their secret part: sec records.
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...