QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
keygendialog.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2015 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
9#include "keygendialog.h"
10#include "configdialog.h"
11#include "pass.h"
12#include "qprogressindicator.h"
13#include "qtpasssettings.h"
14#include "ui_keygendialog.h"
15#include "windowstatestore.h"
16#include <QCheckBox>
17#include <QMessageBox>
18#include <QRegularExpression>
19#include <algorithm>
20
21#include "qtpasslogging.h"
22
23KeygenDialog::KeygenDialog(const QString &gpgExe, Pass *pass, QWidget *parent)
24 : QDialog(parent), ui(new Ui::KeygenDialog), m_pass(pass),
25 m_progressIndicator(nullptr) {
26 ui->setupUi(this);
27 connect(ui->checkBox, &QCheckBox::toggled, this,
29 connect(ui->noPassphrase, &QCheckBox::toggled, this,
32
33 WindowStateStore::attach(*this, QStringLiteral("keygenDialog"));
34
35 ui->plainTextEdit->setPlainText(Pass::getDefaultKeyTemplate(gpgExe));
36 // The batch template is only of interest in expert mode; keep it out of
37 // sight otherwise so the %no-protection placeholder cannot be mistaken for
38 // the effective setting once a passphrase has been typed.
39 ui->plainTextEdit->setVisible(ui->checkBox->isChecked());
40}
41
43
44// The passphrase never goes into the template box: that widget is always
45// readable, which would defeat the masked fields. applyPassphrase() splices it
46// into the batch on accept.
48 Q_UNUSED(arg1)
50}
51
52auto KeygenDialog::passphraseChosen() const -> bool {
53 const QString passphrase = ui->passphrase1->text();
54 const bool agreed = passphrase == ui->passphrase2->text();
55 return agreed && (!passphrase.isEmpty() || ui->noPassphrase->isChecked());
56}
57
59 ui->buttonBox->setEnabled(passphraseChosen());
60}
61
63 if (checked) {
64 ui->passphrase1->clear();
65 ui->passphrase2->clear();
66 }
67 ui->passphrase1->setEnabled(!checked);
68 ui->passphrase2->setEnabled(!checked);
70}
71
75
76void KeygenDialog::setExpertMode(bool checked) {
77 ui->plainTextEdit->setReadOnly(!checked);
78 ui->plainTextEdit->setEnabled(checked);
79 ui->plainTextEdit->setVisible(checked);
80}
81
82void KeygenDialog::on_email_textChanged(const QString &arg1) {
83 replace("Name-Email", arg1);
84}
85
86void KeygenDialog::on_name_textChanged(const QString &arg1) {
87 replace("Name-Real", arg1);
88}
89
99static QStringList batchLines(QString batch) {
100 batch.replace(QLatin1Char('\r'), QLatin1Char('\n'));
101 return batch.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
102}
103
104void KeygenDialog::replace(const QString &key, const QString &value) {
105 // A pasted line break would put batch directives of its own into the
106 // template, and correcting the field later would leave them there:
107 // nothing such goes in. done() refuses the field itself.
108 if (!isBatchValue(value)) {
109 return;
110 }
111 QStringList clear;
112 const QStringList lines = batchLines(ui->plainTextEdit->toPlainText());
113 for (QString line : lines) {
114 line.replace(QRegularExpression(key + ":.*"), key + ": " + value);
115 clear.append(line);
116 }
117 ui->plainTextEdit->setPlainText(clear.join("\n"));
118}
119
130static bool isControlStatement(const QString &line, const QString &control) {
131 const QString trimmed = line.trimmed();
132 if (!trimmed.startsWith(control, Qt::CaseInsensitive))
133 return false;
134 return trimmed.size() == control.size() ||
135 trimmed.at(control.size()).isSpace();
136}
137
138// Keywords are matched as gpg matches them: an expert's "%No-Protection" left
139// next to the Passphrase: line makes gpg generate an unprotected key anyway.
140// The value is spliced in as a plain string, never through a regex.
141QString KeygenDialog::applyPassphrase(const QString &batch,
142 const QString &passphrase) {
143 static const QString noProtection = QStringLiteral("%no-protection");
144 static const QString commit = QStringLiteral("%commit");
145 static const QString passphraseKey = QStringLiteral("Passphrase:");
146 const QString protection =
147 passphrase.isEmpty() ? noProtection : passphraseKey + " " + passphrase;
148
149 QStringList clear;
150 bool spliced = false;
151 const QStringList lines = batchLines(batch);
152 for (QString line : lines) {
153 // gpg reads each line as a C string, so it ends at a NUL: what follows
154 // one would hide "%no-protection" from the check below and not from
155 // gpg. Cut it here as gpg does.
156 if (const qsizetype nul = line.indexOf(QChar::Null); nul >= 0) {
157 line.truncate(nul);
158 }
159 if (isControlStatement(line, noProtection) ||
160 line.trimmed().startsWith(passphraseKey, Qt::CaseInsensitive)) {
161 if (!spliced) {
162 clear.append(protection);
163 spliced = true;
164 }
165 continue;
166 }
167 clear.append(line);
168 }
169
170 if (!spliced && !passphrase.isEmpty()) {
171 // Parameters must precede %commit; append when the template has none.
172 const auto commitLine =
173 std::find_if(clear.cbegin(), clear.cend(), [](const QString &line) {
174 return isControlStatement(line, commit);
175 });
176 clear.insert(commitLine - clear.cbegin(), protection);
177 }
178 return clear.join("\n");
179}
180
181auto KeygenDialog::isBatchValue(const QString &value) -> bool {
182 return !hasBatchBreak(value) && QStringView(value).isValidUtf16();
183}
184
185// The value goes into the template box and comes back through
186// toPlainText(), which hands the Unicode line and paragraph separators and
187// Qt's frame markers back as LF. A line edit shows the separators as a
188// space, so a pasted name looked like one line and still added its own
189// batch directives (%pubring <file> has gpg overwrite that file).
190auto KeygenDialog::hasBatchBreak(const QString &value) -> bool {
191 return std::any_of(value.cbegin(), value.cend(), [](QChar c) {
192 switch (c.unicode()) {
193 case u'\n':
194 case u'\r':
195 case u'\0':
196 case QChar::LineSeparator:
197 case QChar::ParagraphSeparator:
198 case 0xFDD0: // QTextBeginningOfFrame
199 case 0xFDD1: // QTextEndOfFrame
200 return true;
201 default:
202 return false;
203 }
204 });
205}
206
207// What gpg's batch reader takes off a value: C isspace() after the colon,
208// spaces and tabs at the end. A trailing \v or \f is refused too, though gpg
209// keeps it; nobody types one.
210auto KeygenDialog::isBatchPassphrase(const QString &passphrase) -> bool {
211 const auto blank = [](QChar c) {
212 return c == QLatin1Char(' ') ||
213 (c >= QLatin1Char('\t') && c <= QLatin1Char('\r'));
214 };
215 return passphrase.isEmpty() ||
216 (!blank(passphrase.front()) && !blank(passphrase.back()));
217}
218
220 if (QDialog::Accepted == r) {
221 // The button is disabled without a passphrase choice, but done() can be
222 // reached otherwise (a default button, a script); the rule holds here.
223 // No dialog: the disabled OK already says what is missing.
224 if (!passphraseChosen()) {
226 return;
227 }
228 // Pasted text with a line break would become batch directives of its
229 // own (replace() kept it out of the template); the email is matched
230 // whole by its pattern below.
231 if (hasBatchBreak(ui->name->text()) ||
232 hasBatchBreak(ui->passphrase1->text())) {
233 QMessageBox::critical(this, tr("Invalid input"),
234 tr("The name and the passphrase cannot contain "
235 "line breaks."));
236 return;
237 }
238 // Half of a character (one surrogate of an emoji, pasted in-process or
239 // from a UTF-16 clipboard) is no text gpg can take: the name would not
240 // be the one typed, and the passphrase would protect the key with
241 // another one.
242 if (!isBatchValue(ui->name->text()) ||
243 !isBatchValue(ui->passphrase1->text())) {
244 QMessageBox::critical(this, tr("Invalid input"),
245 tr("The name or the passphrase holds half of a "
246 "character, such as a broken emoji. Type it "
247 "again."));
248 return;
249 }
250 // gpg would protect the key without the blanks, and then refuse the
251 // passphrase as typed.
252 if (!isBatchPassphrase(ui->passphrase1->text())) {
253 QMessageBox::critical(
254 this, tr("Invalid input"),
255 tr("The passphrase cannot start or end with a space or a tab."));
256 return;
257 }
258 if (ui->name->text().length() < 5) {
259 QMessageBox::critical(this, tr("Invalid name"),
260 tr("Name must be at least 5 characters long."));
261 return;
262 }
263
264 static const QRegularExpression mailre(
265 QRegularExpression::anchoredPattern(
266 R"(\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b)"),
267 QRegularExpression::CaseInsensitiveOption);
268 if (!mailre.match(ui->email->text()).hasMatch()) {
269 QMessageBox::critical(
270 this, tr("Invalid email"),
271 tr("The email address you typed is not a valid email address."));
272 return;
273 }
274
275 ui->widget->setEnabled(false);
276 ui->buttonBox->setEnabled(false);
277 ui->checkBox->setEnabled(false);
278 ui->plainTextEdit->setEnabled(false);
279
280 if (!m_progressIndicator) {
281 m_progressIndicator = std::make_unique<QProgressIndicator>();
282 m_progressIndicator->setParent(this);
283 m_progressIndicator->setSizePolicy(QSizePolicy::Expanding,
284 QSizePolicy::Expanding);
285 this->layout()->addWidget(m_progressIndicator.get());
286 }
287 // A retry after generationFailed() reuses the indicator it stopped and hid.
288 m_progressIndicator->show();
289 m_progressIndicator->startAnimation();
290
291 ui->frame->hide();
292 ui->label->setText(
293 tr("This operation can take some minutes.<br />"
294 "We need to generate a lot of random bytes. It is a good idea to "
295 "perform some other action (type on the keyboard, move the mouse, "
296 "utilize the disks) during the prime generation; this gives the "
297 "random number generator a better chance to gain enough entropy."));
298
299 this->show();
300 startGeneration(applyPassphrase(ui->plainTextEdit->toPlainText(),
301 ui->passphrase1->text()));
302 } else {
303 QObject::disconnect(m_finished);
304 QObject::disconnect(m_failed);
305 QDialog::done(r);
306 return;
307 }
308}
309
310// Success accepts the dialog, so an exec() caller (the first-run wizard's
311// checkSecretKeys()) sees Accepted; failure gives the form back.
312void KeygenDialog::startGeneration(const QString &batch) {
313 if (m_pass == nullptr) {
314 generationFailed(tr("No password store backend available"));
315 return;
316 }
318 [this](const QString &, const QString &) {
319 QObject::disconnect(m_finished);
320 QObject::disconnect(m_failed);
321 QDialog::done(QDialog::Accepted);
322 });
323 // Not processErrorExit: that fires for any command that fails while the
324 // key is being generated (a queued git push, say) and would take the
325 // dialog down while gpg is still working.
327 [this](const QString &error) {
328 QObject::disconnect(m_finished);
329 QObject::disconnect(m_failed);
330 generationFailed(error);
331 });
332 m_pass->GenerateGPGKeys(batch);
333}
334
335void KeygenDialog::generationFailed(const QString &error) {
337 m_progressIndicator->stopAnimation();
338 m_progressIndicator->hide();
339 }
340 ui->frame->show();
341 ui->widget->setEnabled(true);
342 ui->checkBox->setEnabled(true);
343 ui->plainTextEdit->setEnabled(true);
344 // OK comes back under the same rule as before the attempt, not
345 // unconditionally: the passphrase choice still has to stand.
347 ui->label->setText(
348 tr("Key generation failed: %1").arg(error.toHtmlEscaped()));
349}
static auto isBatchPassphrase(const QString &passphrase) -> bool
Whether gpg reads passphrase back as typed from a batch Passphrase: line.
static QString applyPassphrase(const QString &batch, const QString &passphrase)
Splice a passphrase into a GPG batch template.
void replace(const QString &key, const QString &value)
Rewrites every <key>: ... line of the batch template to carry value. Values that fail isBatchValue() ...
std::unique_ptr< QProgressIndicator > m_progressIndicator
Spinner shown while gpg works; created lazily on the first attempt, reused (hidden) across retries.
KeygenDialog(const QString &gpgExe, Pass *pass, QWidget *parent=nullptr)
Construct a KeygenDialog.
static auto hasBatchBreak(const QString &value) -> bool
Whether a field's text holds a line break or NUL, which would end its batch line early.
void setExpertMode(bool checked)
Enable or disable expert mode (the editable batch template).
void setNoPassphrase(bool checked)
Ticking "no passphrase" clears and disables the passphrase fields and makes OK available; unticking i...
void on_passphrase1_textChanged(const QString &arg1)
First passphrase field edited: re-evaluates whether OK may be enabled. The text itself stays out of t...
void generationFailed(const QString &error)
Stops and hides the progress indicator, re-enables the form under the usual OK rule and shows error i...
void done(int r) override
On Accepted, validates the form (passphrase chosen, no line breaks, name of 5+ characters,...
QMetaObject::Connection m_failed
Connection to Pass::generateGPGKeysFailed, live only during an attempt.
void startGeneration(const QString &batch)
Connects to the backend's finished/failed signals for this one attempt and calls Pass::GenerateGPGKey...
void on_email_textChanged(const QString &arg1)
Mirrors the e-mail field into the template's Name-Email: line.
QScopedPointer< Ui::KeygenDialog > ui
Generated form (keygendialog.ui); owned.
~KeygenDialog() override
Destroys the dialog and its generated UI.
void updateOkState()
OK is available when a passphrase is typed twice the same, or when no passphrase was asked for explic...
Pass * m_pass
Backend that runs gpg; not owned, may be nullptr.
void on_name_textChanged(const QString &arg1)
Mirrors the name field into the template's Name-Real: line.
QMetaObject::Connection m_finished
Connection to Pass::finishedGenerateGPGKeys, live only during an attempt.
auto passphraseChosen() const -> bool
Whether the passphrase question has an answer: typed twice the same, or waived with the checkbox....
void on_passphrase2_textChanged(const QString &arg1)
Confirmation field edited: same as on_passphrase1_textChanged().
static auto isBatchValue(const QString &value) -> bool
Whether value can go into a GPG batch line as one value.
Abstract base class for password store operations.
Definition pass.h:77
void GenerateGPGKeys(QString batch)
Generate GPG keys using batch script.
Definition pass.cpp:420
static QString getDefaultKeyTemplate(const QString &gpgExecutable={})
Get default key template for new GPG keys.
Definition pass.cpp:317
void finishedGenerateGPGKeys(const QString &out, const QString &err)
GenerateGPGKeys() succeeded; the new key pair is in the keyring.
void generateGPGKeysFailed(const QString &err)
Emitted when GPG key generation fails, alongside the generic processErrorExit(); lets the keygen dial...
Settings dialog: every page of the configuration window and the profile table, with the validation th...
static bool isControlStatement(const QString &line, const QString &control)
Whether a batch line is the control statement control.
static QStringList batchLines(QString batch)
Cut a batch template into its non-empty lines at CR and LF.
Dialog that collects name, e-mail and passphrase for a new GPG keypair and drives gpg --gen-key --bat...
void attach(QDialog &dialog, const QString &key)
restore() now, save() whenever the dialog finishes.
Pass, the abstract password-store backend that RealPass and ImitatePass implement,...
Spinner widget that shows the application is busy.
The "qtpass" logging category.
QtPassSettings, the QSettings singleton behind every saved setting, the profiles and the Pass backend...
WindowStateStore: saves and restores top-level window geometry through QtPassSettings,...