Branch data Line data Source code
1 : : // SPDX-FileCopyrightText: 2015 Anne Jan Brouwer
2 : : // SPDX-License-Identifier: GPL-3.0-or-later
3 : : /**
4 : : * @file
5 : : * @brief Implements KeygenDialog: form validation, splicing the passphrase
6 : : * into the GPG batch the way gpg itself reads it, and the one-attempt
7 : : * connections to the Pass backend.
8 : : */
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 : :
23 : 33 : KeygenDialog::KeygenDialog(const QString &gpgExe, Pass *pass, QWidget *parent)
24 : 66 : : QDialog(parent), ui(new Ui::KeygenDialog), m_pass(pass),
25 : 33 : m_progressIndicator(nullptr) {
26 : 33 : ui->setupUi(this);
27 : 33 : connect(ui->checkBox, &QCheckBox::toggled, this,
28 : 33 : &KeygenDialog::setExpertMode);
29 : 33 : connect(ui->noPassphrase, &QCheckBox::toggled, this,
30 : 33 : &KeygenDialog::setNoPassphrase);
31 : 33 : updateOkState();
32 : :
33 : 66 : WindowStateStore::attach(*this, QStringLiteral("keygenDialog"));
34 : :
35 : 66 : 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 : 33 : ui->plainTextEdit->setVisible(ui->checkBox->isChecked());
40 : 33 : }
41 : :
42 : 33 : KeygenDialog::~KeygenDialog() = default;
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.
47 : 32 : void KeygenDialog::on_passphrase1_textChanged(const QString &arg1) {
48 : : Q_UNUSED(arg1)
49 : 32 : updateOkState();
50 : 32 : }
51 : :
52 : 93 : auto KeygenDialog::passphraseChosen() const -> bool {
53 : 93 : const QString passphrase = ui->passphrase1->text();
54 : 93 : const bool agreed = passphrase == ui->passphrase2->text();
55 [ + + + + : 186 : return agreed && (!passphrase.isEmpty() || ui->noPassphrase->isChecked());
+ + + ]
56 : : }
57 : :
58 : 79 : void KeygenDialog::updateOkState() {
59 : 79 : ui->buttonBox->setEnabled(passphraseChosen());
60 : 79 : }
61 : :
62 : 10 : void KeygenDialog::setNoPassphrase(bool checked) {
63 [ + + ]: 10 : if (checked) {
64 : 8 : ui->passphrase1->clear();
65 : 8 : ui->passphrase2->clear();
66 : : }
67 : 10 : ui->passphrase1->setEnabled(!checked);
68 : 10 : ui->passphrase2->setEnabled(!checked);
69 : 10 : updateOkState();
70 : 10 : }
71 : :
72 : 16 : void KeygenDialog::on_passphrase2_textChanged(const QString &arg1) {
73 : 16 : on_passphrase1_textChanged(arg1);
74 : 16 : }
75 : :
76 : 4 : void KeygenDialog::setExpertMode(bool checked) {
77 : 4 : ui->plainTextEdit->setReadOnly(!checked);
78 : 4 : ui->plainTextEdit->setEnabled(checked);
79 : 4 : ui->plainTextEdit->setVisible(checked);
80 : 4 : }
81 : :
82 : 18 : void KeygenDialog::on_email_textChanged(const QString &arg1) {
83 : 18 : replace("Name-Email", arg1);
84 : 18 : }
85 : :
86 : 25 : void KeygenDialog::on_name_textChanged(const QString &arg1) {
87 : 25 : replace("Name-Real", arg1);
88 : 25 : }
89 : :
90 : : /**
91 : : * @brief Cut a batch template into its non-empty lines at CR and LF.
92 : : *
93 : : * Plain character splitting, no regex: QRegularExpression matches nothing in
94 : : * text that is not valid UTF-16, so a lone surrogate anywhere left the whole
95 : : * batch one "line" and %no-protection was never found.
96 : : * @param batch The template text.
97 : : * @return Its lines, without the line breaks and without empty ones.
98 : : */
99 : 60 : static QStringList batchLines(QString batch) {
100 : 60 : batch.replace(QLatin1Char('\r'), QLatin1Char('\n'));
101 : 60 : return batch.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
102 : : }
103 : :
104 : 43 : void 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 [ + + ]: 43 : if (!isBatchValue(value)) {
109 : 11 : return;
110 : : }
111 : 32 : QStringList clear;
112 : 64 : const QStringList lines = batchLines(ui->plainTextEdit->toPlainText());
113 [ + + ]: 416 : for (QString line : lines) {
114 : 1152 : line.replace(QRegularExpression(key + ":.*"), key + ": " + value);
115 : : clear.append(line);
116 : : }
117 : 64 : ui->plainTextEdit->setPlainText(clear.join("\n"));
118 : : }
119 : :
120 : : /**
121 : : * @brief Whether a batch line is the control statement @p control.
122 : : *
123 : : * Matches the way gpg's read_parameter_file does: leading whitespace skipped,
124 : : * keyword ends at the first whitespace, case-insensitive.
125 : : * @param line One line of the batch template.
126 : : * @param control The statement to look for, e.g. `%no-protection`.
127 : : * @return true when the line is that statement, alone or followed by
128 : : * whitespace.
129 : : */
130 : 178 : static bool isControlStatement(const QString &line, const QString &control) {
131 : : const QString trimmed = line.trimmed();
132 [ + + + ]: 178 : if (!trimmed.startsWith(control, Qt::CaseInsensitive))
133 : : return false;
134 [ + + ]: 23 : 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.
141 : 28 : QString KeygenDialog::applyPassphrase(const QString &batch,
142 : : const QString &passphrase) {
143 : 31 : static const QString noProtection = QStringLiteral("%no-protection");
144 : 29 : static const QString commit = QStringLiteral("%commit");
145 : 29 : static const QString passphraseKey = QStringLiteral("Passphrase:");
146 : : const QString protection =
147 [ + + + ]: 28 : passphrase.isEmpty() ? noProtection : passphraseKey + " " + passphrase;
148 : :
149 : 28 : QStringList clear;
150 : : bool spliced = false;
151 : 56 : const QStringList lines = batchLines(batch);
152 [ + + ]: 196 : 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 [ + + ]: 168 : if (const qsizetype nul = line.indexOf(QChar::Null); nul >= 0) {
157 : 1 : line.truncate(nul);
158 : : }
159 [ + + + ]: 191 : if (isControlStatement(line, noProtection) ||
160 [ + + + - : 318 : line.trimmed().startsWith(passphraseKey, Qt::CaseInsensitive)) {
- ]
161 [ + + ]: 23 : if (!spliced) {
162 : : clear.append(protection);
163 : : spliced = true;
164 : : }
165 : : continue;
166 : : }
167 : : clear.append(line);
168 : : }
169 : :
170 [ + + + + ]: 28 : if (!spliced && !passphrase.isEmpty()) {
171 : : // Parameters must precede %commit; append when the template has none.
172 : : const auto commitLine =
173 : 5 : std::find_if(clear.cbegin(), clear.cend(), [](const QString &line) {
174 : 10 : return isControlStatement(line, commit);
175 : : });
176 : : clear.insert(commitLine - clear.cbegin(), protection);
177 : : }
178 : 84 : return clear.join("\n");
179 : : }
180 : :
181 : 77 : auto KeygenDialog::isBatchValue(const QString &value) -> bool {
182 [ + + + + ]: 77 : 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).
190 : 106 : auto KeygenDialog::hasBatchBreak(const QString &value) -> bool {
191 : 1288 : return std::any_of(value.cbegin(), value.cend(), [](QChar c) {
192 [ + + ]: 1288 : 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 : 1266 : default:
202 : 1266 : return false;
203 : : }
204 : 106 : });
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.
210 : 21 : auto KeygenDialog::isBatchPassphrase(const QString &passphrase) -> bool {
211 : : const auto blank = [](QChar c) {
212 [ + + + - : 21 : return c == QLatin1Char(' ') ||
+ + - + ]
213 [ + + + + ]: 17 : (c >= QLatin1Char('\t') && c <= QLatin1Char('\r'));
214 : : };
215 [ + + ]: 21 : return passphrase.isEmpty() ||
216 : 21 : (!blank(passphrase.front()) && !blank(passphrase.back()));
217 : : }
218 : :
219 : 18 : void KeygenDialog::done(int r) {
220 [ + + ]: 18 : 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 [ + + ]: 14 : if (!passphraseChosen()) {
225 : 2 : updateOkState();
226 : 2 : 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 [ + + + - : 24 : if (hasBatchBreak(ui->name->text()) ||
+ + ]
232 [ + + - - ]: 24 : hasBatchBreak(ui->passphrase1->text())) {
233 : 3 : QMessageBox::critical(this, tr("Invalid input"),
234 : 1 : tr("The name and the passphrase cannot contain "
235 : : "line breaks."));
236 : 1 : 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 [ + + + - : 33 : if (!isBatchValue(ui->name->text()) ||
+ + + + ]
243 [ + + - - ]: 22 : !isBatchValue(ui->passphrase1->text())) {
244 : 3 : QMessageBox::critical(this, tr("Invalid input"),
245 : 1 : tr("The name or the passphrase holds half of a "
246 : : "character, such as a broken emoji. Type it "
247 : : "again."));
248 : 1 : return;
249 : : }
250 : : // gpg would protect the key without the blanks, and then refuse the
251 : : // passphrase as typed.
252 [ + + + ]: 20 : if (!isBatchPassphrase(ui->passphrase1->text())) {
253 : 2 : QMessageBox::critical(
254 : 1 : this, tr("Invalid input"),
255 : 1 : tr("The passphrase cannot start or end with a space or a tab."));
256 : 1 : return;
257 : : }
258 [ - + ]: 18 : if (ui->name->text().length() < 5) {
259 : 0 : QMessageBox::critical(this, tr("Invalid name"),
260 : 0 : tr("Name must be at least 5 characters long."));
261 : 0 : return;
262 : : }
263 : :
264 : : static const QRegularExpression mailre(
265 : 1 : QRegularExpression::anchoredPattern(
266 : 2 : R"(\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b)"),
267 [ + + + - : 12 : QRegularExpression::CaseInsensitiveOption);
+ + ]
268 [ + + - + ]: 18 : if (!mailre.match(ui->email->text()).hasMatch()) {
269 : 0 : QMessageBox::critical(
270 : 0 : this, tr("Invalid email"),
271 : 0 : tr("The email address you typed is not a valid email address."));
272 : 0 : return;
273 : : }
274 : :
275 : 9 : ui->widget->setEnabled(false);
276 : 9 : ui->buttonBox->setEnabled(false);
277 : 9 : ui->checkBox->setEnabled(false);
278 : 9 : ui->plainTextEdit->setEnabled(false);
279 : :
280 [ + + ]: 9 : if (!m_progressIndicator) {
281 : 16 : m_progressIndicator = std::make_unique<QProgressIndicator>();
282 : 8 : m_progressIndicator->setParent(this);
283 : 8 : m_progressIndicator->setSizePolicy(QSizePolicy::Expanding,
284 : : QSizePolicy::Expanding);
285 : 8 : this->layout()->addWidget(m_progressIndicator.get());
286 : : }
287 : : // A retry after generationFailed() reuses the indicator it stopped and hid.
288 : 9 : m_progressIndicator->show();
289 : 9 : m_progressIndicator->startAnimation();
290 : :
291 : 9 : ui->frame->hide();
292 : 9 : ui->label->setText(
293 : 9 : 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 : 9 : this->show();
300 : 18 : startGeneration(applyPassphrase(ui->plainTextEdit->toPlainText(),
301 : 18 : ui->passphrase1->text()));
302 : : } else {
303 : 4 : QObject::disconnect(m_finished);
304 : 4 : QObject::disconnect(m_failed);
305 : 4 : QDialog::done(r);
306 : 4 : 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.
312 : 9 : void KeygenDialog::startGeneration(const QString &batch) {
313 [ - + ]: 9 : if (m_pass == nullptr) {
314 : 0 : generationFailed(tr("No password store backend available"));
315 : 0 : return;
316 : : }
317 : 9 : m_finished = connect(m_pass, &Pass::finishedGenerateGPGKeys, this,
318 : 9 : [this](const QString &, const QString &) {
319 : 2 : QObject::disconnect(m_finished);
320 : 2 : QObject::disconnect(m_failed);
321 : 2 : QDialog::done(QDialog::Accepted);
322 : 2 : });
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.
326 : 9 : m_failed = connect(m_pass, &Pass::generateGPGKeysFailed, this,
327 : 9 : [this](const QString &error) {
328 : 2 : QObject::disconnect(m_finished);
329 : 2 : QObject::disconnect(m_failed);
330 : 2 : generationFailed(error);
331 : 2 : });
332 : 18 : m_pass->GenerateGPGKeys(batch);
333 : : }
334 : :
335 : 2 : void KeygenDialog::generationFailed(const QString &error) {
336 [ + - ]: 2 : if (m_progressIndicator) {
337 : 2 : m_progressIndicator->stopAnimation();
338 : 2 : m_progressIndicator->hide();
339 : : }
340 : 2 : ui->frame->show();
341 : 2 : ui->widget->setEnabled(true);
342 : 2 : ui->checkBox->setEnabled(true);
343 : 2 : 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.
346 : 2 : updateOkState();
347 : 4 : ui->label->setText(
348 [ + + ]: 4 : tr("Key generation failed: %1").arg(error.toHtmlEscaped()));
349 : 2 : }
|