Branch data Line data Source code
1 : : // SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2 : : // SPDX-License-Identifier: GPL-3.0-or-later
3 : : /**
4 : : * @file
5 : : * @brief Implements PasswordDisplayPanel; the value browser and
6 : : * open-in-browser button are built by file-local helpers.
7 : : */
8 : : #include "passworddisplaypanel.h"
9 : : #include "appsettings.h"
10 : : #include "otpcodewidget.h"
11 : : #include "qpushbuttonasqrcode.h"
12 : : #include "qpushbuttonshowpassword.h"
13 : : #include "qpushbuttonwithclipboard.h"
14 : : #include "secretlineedit.h"
15 : : #include "secrettextbrowser.h"
16 : : #include "totp.h"
17 : : #include "util.h"
18 : :
19 : : #include <QBoxLayout>
20 : : #include <QDesktopServices>
21 : : #include <QDrag>
22 : : #include <QFrame>
23 : : #include <QGridLayout>
24 : : #include <QHBoxLayout>
25 : : #include <QIcon>
26 : : #include <QLabel>
27 : : #include <QLayout>
28 : : #include <QLineEdit>
29 : : #include <QMouseEvent>
30 : : #include <QPalette>
31 : : #include <QPushButton>
32 : : #include <QTextBrowser>
33 : : #include <QUrl>
34 : :
35 : 258 : PasswordDisplayPanel::PasswordDisplayPanel(QGridLayout *grid,
36 : : QBoxLayout *container,
37 : : QWidget *widgetParent,
38 : 258 : QObject *parent)
39 : 258 : : QObject(parent), m_grid(grid), m_container(container),
40 : 258 : m_widgetParent(widgetParent) {}
41 : :
42 : 194 : void PasswordDisplayPanel::clear() {
43 [ + + ]: 294 : while (m_grid->count() > 0) {
44 : 100 : QLayoutItem *item = m_grid->takeAt(0);
45 [ + - ]: 100 : if (QWidget *widget = item->widget()) {
46 : : // A drag out of a field value runs QDrag::exec() inside the value
47 : : // widget's own mouse handler, and clear() can be reached from that
48 : : // nested event loop (a drop on the search box, the panel autoclear
49 : : // timer, a second "qtpass NAME"). Deleting the row then - even with
50 : : // deleteLater(), which the drag's loop would deliver - frees it under
51 : : // its own handler and crashes. A row that has a QDrag among its children
52 : : // is hidden now and deleted once that QDrag is gone, which Qt does after
53 : : // the drag ends; rows without a drag are deleted at once as before.
54 : 100 : const QList<QDrag *> drags = widget->findChildren<QDrag *>();
55 [ + + ]: 100 : if (drags.isEmpty()) {
56 : 99 : delete widget;
57 : : } else {
58 : 1 : widget->hide();
59 : 1 : connect(drags.last(), &QObject::destroyed, widget,
60 : 3 : [widget]() { widget->deleteLater(); });
61 : : }
62 : : }
63 : 100 : delete item;
64 : : }
65 : 194 : m_container->setSpacing(0);
66 : 194 : }
67 : :
68 : 13 : auto PasswordDisplayPanel::currentOtpCode() const -> QString {
69 : : // displayFields() renders at most one OTP row, so the first match is it.
70 [ + + ]: 37 : for (int i = 0; i < m_grid->count(); ++i) {
71 : 30 : QWidget *widget = m_grid->itemAt(i)->widget();
72 [ - + ]: 30 : if (widget == nullptr) {
73 : 0 : continue;
74 : : }
75 [ + + ]: 30 : if (auto *otp = widget->findChild<OtpCodeWidget *>()) {
76 : 6 : return otp->code();
77 : : }
78 : : }
79 : 7 : return {};
80 : : }
81 : :
82 : 94 : void PasswordDisplayPanel::displayFields(const QString &password,
83 : : const NamedValues &namedValues,
84 : : const AppSettings &s,
85 : : const QString &otpConfig) {
86 : : // Rows are numbered as they are added rather than assuming the password
87 : : // occupies row 0: an entry written by `pass otp insert` has no password row,
88 : : // and starting at 1 regardless left an empty grid row above the OTP row.
89 : : int position = 0;
90 : : // Defence in depth: getPasswordForDisplay() already blanks a password line
91 : : // that holds a shared secret (an otpauth URI from `pass otp insert`, or an
92 : : // OTP field holding a seed); refuse one here too.
93 [ + + + + ]: 94 : if (!password.isEmpty() && !FileContent::isOtpPasswordLine(password)) {
94 : : // The password is hidden in addField when needed.
95 : 182 : addField(position, QObject::tr("Password"), password, s);
96 : : ++position;
97 : : }
98 : : bool otpRendered = false;
99 [ + + ]: 174 : for (const NamedValue &nv : namedValues) {
100 : : // Keyed on the value too: a field called anything whose value is an otpauth
101 : : // URI is still a shared secret, and isLineHidden() hides it from the text
102 : : // browser, so suppressing only OTP/TOTP names leaked `2fa:` and friends.
103 [ + + + + ]: 145 : if (FileContent::isOtpFieldName(nv.name) ||
104 : 65 : FileContent::carriesOtpUri(nv.value)) {
105 : : // Never render an OTP field verbatim: addField() would display the
106 : : // shared secret and hand it to a copy button. Unconditional, so it stays
107 : : // hidden when OTP support is off and otpConfig is empty.
108 [ + + + + ]: 19 : if (!otpRendered && !otpConfig.isEmpty()) {
109 : 15 : addOtpField(position, otpConfig, s);
110 : 15 : ++position;
111 : : otpRendered = true;
112 : : }
113 : 19 : continue;
114 : : }
115 : 61 : addField(position, nv.name, nv.value, s);
116 : 61 : ++position;
117 : : }
118 : : // The configuration came from the entry body rather than from a field.
119 [ + + + + ]: 94 : if (!otpConfig.isEmpty() && !otpRendered) {
120 : 6 : addOtpField(position, otpConfig, s);
121 : : }
122 [ + + ]: 187 : m_container->setSpacing(m_grid->count() == 0 ? 0 : 6);
123 : 94 : }
124 : :
125 : : namespace {
126 : :
127 : : // Scope every rule to the widget type so the transparent background does not
128 : : // cascade into the field's standard context menu (a child QMenu), which would
129 : : // otherwise render transparent too.
130 : : constexpr const char *kButtonStyle =
131 : : "QPushButton { border-style: none; background: transparent; padding: 0; "
132 : : "margin: 0; icon-size: 16px; color: inherit; }";
133 : :
134 : : // 26px matches the action-button visual height for consistent alignment.
135 : : constexpr int kFieldHeight = 26;
136 : :
137 : : /// A read-only, one-line browser showing @p value. Only launchable http(s)
138 : : /// URLs become anchors (the open-in-browser button's predicate):
139 : : /// setOpenExternalLinks() would hand ssh://, ftp:// or user:pass@ URLs
140 : : /// straight to the OS URL handler on click. With @p links false nothing
141 : : /// does: a secret is shown, never opened.
142 : 133 : auto valueBrowser(const QString &field, const QString &value,
143 : : const QString &lineStyle, bool links) -> SecretTextBrowser * {
144 : 133 : auto *browser = new SecretTextBrowser();
145 : 133 : browser->setOpenExternalLinks(true);
146 : 133 : browser->setOpenLinks(true);
147 : 133 : browser->setMaximumHeight(kFieldHeight);
148 : 133 : browser->setMinimumHeight(kFieldHeight);
149 : 133 : browser->setSizePolicy(
150 : : QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
151 : 133 : browser->setObjectName(field);
152 : : // Both branches keep white space, which can hang Qt's layout on a run of
153 : : // 65536 spaces; the copy button still gets the value itself. One line:
154 : : // a carriage return or U+2029 in a value made a block each, millions of
155 : : // them for a crafted password line.
156 : : const QString shown =
157 : 266 : Util::boundSpaceRuns(Util::withoutOtherBlockBreaks(value));
158 : : // A value of hundreds of thousands of letters in a row (a crafted
159 : : // password line) wraps anywhere: at word boundaries Qt took minutes.
160 [ + + + ]: 133 : if (Util::hasLongUnbrokenRun(shown)) {
161 : 1 : browser->setWordWrapMode(QTextOption::WrapAnywhere);
162 : : }
163 : 133 : bool linked = false;
164 : : const QString linkedText =
165 [ + + + ]: 133 : links ? Util::linkifyUrls(shown, &linked) : QString();
166 [ + + ]: 133 : if (linked) {
167 : : // Always HTML here: the text is escaped and carries anchor tags, so do
168 : : // not leave the interpretation to setText()'s auto-detection. With its
169 : : // white space kept, as setPlainText() below keeps it.
170 : 57 : browser->setHtml(QStringLiteral("<span style=\"white-space: pre-wrap;\">") +
171 [ + + ]: 38 : linkedText + QStringLiteral("</span>"));
172 : : } else {
173 : : // Plain text: escaping plus setText() showed `a&b` as `a&b` unless
174 : : // the value happened to contain a '<'.
175 : 114 : browser->setPlainText(shown);
176 : : }
177 : 133 : browser->setReadOnly(true);
178 : 133 : browser->setStyleSheet(lineStyle);
179 : 133 : browser->setContentsMargins(0, 0, 0, 0);
180 : 133 : return browser;
181 : : }
182 : :
183 : : /// An "open in browser" button for @p url, already validated.
184 : 18 : auto urlButton(const QString &url, QWidget *parent) -> QPushButton * {
185 : 18 : auto *button = new QPushButton(parent);
186 : 36 : button->setIcon(QIcon::fromTheme(QStringLiteral("applications-internet"),
187 : 36 : QIcon(":/icons/open-url.svg")));
188 : : // Escape for the tooltip only; the launched URL stays the validated value.
189 : : // <qt> forces rich text: auto-detection would show `&` literally, and
190 : : // plain text misreads a URL containing `<`. Rich text wraps, breaking
191 : : // the URL at `/` and `?`; white-space:nowrap keeps it on one line (<nobr>
192 : : // is not enough: Qt only makes its spaces non-breaking).
193 : 36 : button->setToolTip(
194 : 18 : QStringLiteral("<qt style=\"white-space:nowrap\">%1</qt>")
195 [ + + + + ]: 36 : .arg(QObject::tr("Open %1 in browser").arg(url.toHtmlEscaped())));
196 : 18 : button->setStyleSheet(QString::fromLatin1(kButtonStyle));
197 : 18 : button->setCursor(Qt::PointingHandCursor);
198 : 18 : QObject::connect(button, &QPushButton::clicked, button, [url]() {
199 : : // Re-validate: never hand an unvalidated string to the OS URL handler.
200 [ # # ]: 0 : if (Util::isLaunchableWebUrl(url)) {
201 : 0 : QDesktopServices::openUrl(QUrl(url));
202 : : }
203 : 0 : });
204 : 18 : return button;
205 : : }
206 : :
207 : : } // namespace
208 : :
209 : 6 : void PasswordDisplayPanel::setMarkedSecrets(const QStringList &names) {
210 : : // Case-folded into a set once: isSecret() runs for every field line of an
211 : : // entry, and a store's .templates may mark thousands of names, so a scan
212 : : // of the list per line froze the window for minutes.
213 : : m_markedSecrets.clear();
214 [ + + ]: 10014 : for (const QString &name : names) {
215 : 20016 : m_markedSecrets.insert(name.toCaseFolded());
216 : : }
217 : 6 : }
218 : :
219 : 256 : auto PasswordDisplayPanel::hides(const QString &field,
220 : : const AppSettings &s) const -> bool {
221 [ + + ]: 256 : return s.hidePassword &&
222 [ + + + + : 154 : (s.hideAllFields || field == QObject::tr("Password") ||
+ + ]
223 : 299 : isSecret(field, s));
224 : : }
225 : :
226 : 50118 : auto PasswordDisplayPanel::isSecret(const QString &field,
227 : : const AppSettings &s) const -> bool {
228 [ + + ]: 50118 : if (!s.hidePassword) {
229 : : return false;
230 : : }
231 : 50104 : const bool marked = m_markedSecrets.contains(field.toCaseFolded());
232 [ + + + + : 50174 : return marked || (s.hideSecretFields &&
+ + ]
233 : 70 : FileContent::isSecretFieldName(field, s.secretFieldNames));
234 : : }
235 : :
236 : 154 : void PasswordDisplayPanel::addActionButtons(QLayout *layout,
237 : : const QString &field,
238 : : const QString &value,
239 : : const AppSettings &s) {
240 : 154 : const QString buttonStyle = QString::fromLatin1(kButtonStyle);
241 [ + + ]: 154 : if (s.clipBoardType != Enums::CLIPBOARD_NEVER) {
242 : 35 : auto *copy = new QPushButtonWithClipboard(value, m_widgetParent);
243 : 35 : connect(copy, &QPushButtonWithClipboard::textClicked, this,
244 : 35 : &PasswordDisplayPanel::copyRequested);
245 : 35 : copy->setStyleSheet(buttonStyle);
246 : 35 : layout->addWidget(copy);
247 : : }
248 [ + + ]: 154 : if (s.useQrencode) {
249 : 10 : auto *qr = new QPushButtonAsQRCode(value, m_widgetParent);
250 : 10 : connect(qr, &QPushButtonAsQRCode::textClicked, this,
251 : 10 : &PasswordDisplayPanel::qrRequested);
252 : 10 : qr->setStyleSheet(buttonStyle);
253 : 10 : layout->addWidget(qr);
254 : : }
255 : : // Never on the password field, nor on any field hidden like it: its value
256 : : // must not reach a tooltip or the browser. A field shown in plain view
257 : : // keeps its link.
258 [ + + + + : 360 : if (field != QObject::tr("Password") && !hides(field, s) &&
+ + + +
+ ]
259 : 52 : Util::isLaunchableWebUrl(value)) {
260 : 18 : layout->addWidget(urlButton(value, m_widgetParent));
261 : : }
262 : 154 : }
263 : :
264 : 21 : void PasswordDisplayPanel::addHiddenPassword(QLayout *layout,
265 : : const QString &field,
266 : : const QString &value,
267 : : const QString &lineStyle) {
268 : : // Shown with the eye button, the password can be selected and copied;
269 : : // SecretLineEdit marks that copy and reports it, as the value browsers do.
270 : 21 : auto *passwordLineEdit = new SecretLineEdit();
271 : 21 : connect(passwordLineEdit, &SecretLineEdit::copied, this,
272 : 21 : &PasswordDisplayPanel::textCopied);
273 : 21 : passwordLineEdit->setObjectName(field);
274 : : // As stored: the line-break filter is for input, and the eye button and a
275 : : // copy must show and copy the password the entry holds.
276 : 21 : passwordLineEdit->setStoredText(value);
277 : 21 : passwordLineEdit->setReadOnly(true);
278 : 21 : passwordLineEdit->setStyleSheet(lineStyle);
279 : 21 : passwordLineEdit->setContentsMargins(0, 0, 0, 0);
280 : 21 : passwordLineEdit->setEchoMode(QLineEdit::Password);
281 : : auto *showButton =
282 : 21 : new QPushButtonShowPassword(passwordLineEdit, m_widgetParent);
283 : 21 : showButton->setStyleSheet(QString::fromLatin1(kButtonStyle));
284 : 21 : showButton->setContentsMargins(0, 0, 0, 0);
285 : 21 : layout->addWidget(showButton);
286 : 21 : layout->addWidget(passwordLineEdit);
287 : 21 : }
288 : :
289 : 154 : void PasswordDisplayPanel::addField(int position, const QString &field,
290 : : const QString &value,
291 : : const AppSettings &s) {
292 : : const QString trimmedField = field.trimmed();
293 : : // The password row keeps its value exactly: a leading or trailing space is
294 : : // part of the password, so the copy button, QR code and revealed text must
295 : : // return what is stored, as Ctrl+C on the tree and the edit dialog do. The
296 : : // carriage return of a CRLF line end is gone already
297 : : // (FileContent::passwordLine()), and dropping another here would make this
298 : : // row disagree with Ctrl+C. Every other row is `name: value`, where the
299 : : // whitespace around the value is layout and is trimmed.
300 : : const QString displayValue =
301 [ + + ]: 154 : trimmedField == QObject::tr("Password") ? value : value.trimmed();
302 : 154 : QFrame *frame = createFieldFrame();
303 : 154 : addActionButtons(frame->layout(), trimmedField, displayValue, s);
304 : : const QString lineStyle =
305 : 154 : s.useMonospace
306 : : ? "QLineEdit, QTextBrowser { border-style: none; background: "
307 : : "transparent; font-family: monospace; }"
308 : : : "QLineEdit, QTextBrowser { border-style: none; background: "
309 : 308 : "transparent; }";
310 : : // The password, and with it the other secrets an entry holds (a PIN, a
311 : : // CVV, an API key, what a template marks): behind the eye button too.
312 [ + + + ]: 154 : if (hides(trimmedField, s)) {
313 : 21 : addHiddenPassword(frame->layout(), trimmedField, displayValue, lineStyle);
314 : : } else {
315 : : // A password or another secret is never a link, also when shown: a
316 : : // click on a URL-shaped one handed it to the browser, its history and
317 : : // the command line of the URL handler.
318 : 133 : AppSettings asHidden = s;
319 : 133 : asHidden.hidePassword = true;
320 : 133 : asHidden.hideSecretFields = true;
321 [ + + + + ]: 185 : const bool secret = trimmedField == QObject::tr("Password") ||
322 : 52 : isSecret(trimmedField, asHidden);
323 : : SecretTextBrowser *browser =
324 : 133 : valueBrowser(trimmedField, displayValue, lineStyle, !secret);
325 : 133 : connect(browser, &SecretTextBrowser::copied, this,
326 : 133 : &PasswordDisplayPanel::textCopied);
327 : 133 : frame->layout()->addWidget(browser);
328 : 133 : }
329 : : // Plain text before the name is set: a field name comes from the entry,
330 : : // and as rich text <img src="/dev/zero"> has Qt read that file without end.
331 : 154 : auto *label = new QLabel();
332 : 154 : label->setTextFormat(Qt::PlainText);
333 : : // Bounded: the label sizes the main window.
334 : 154 : label->setText(Util::shownName(trimmedField));
335 : 154 : addRow(position, label, frame);
336 : 154 : }
337 : :
338 : 173 : void PasswordDisplayPanel::addRow(int position, QLabel *label, QFrame *frame) {
339 : 173 : m_grid->addWidget(label, position, 0);
340 : 173 : m_grid->addWidget(frame, position, 1);
341 : 173 : label->installEventFilter(this);
342 : 173 : frame->installEventFilter(this);
343 : : // The value widgets swallow mouse events before the frame sees them.
344 [ + + + + ]: 1316 : for (QWidget *child : frame->findChildren<QWidget *>()) {
345 : 970 : child->installEventFilter(this);
346 : : }
347 : 173 : }
348 : :
349 : 1521 : auto PasswordDisplayPanel::eventFilter(QObject *watched, QEvent *event)
350 : : -> bool {
351 [ + + + - ]: 1521 : if (event->type() == QEvent::MouseButtonDblClick &&
352 : : static_cast<QMouseEvent *>(event)->button() == Qt::LeftButton) {
353 : 2 : emit editRequested();
354 : 2 : return true;
355 : : }
356 : 1519 : return QObject::eventFilter(watched, event);
357 : : }
358 : :
359 : : // The colour is baked into the stylesheet (a `palette(mid)` reference
360 : : // resolves once at polish time), so refreshPalette() re-runs this.
361 : 181 : void PasswordDisplayPanel::applyFrameStyle(QFrame *frame) const {
362 : : const QString borderColor =
363 : 362 : m_widgetParent->palette().color(QPalette::Mid).name();
364 : 362 : frame->setStyleSheet(QStringLiteral(".QFrame{border: 1px solid %1; "
365 : : "border-radius: 5px;}")
366 : 543 : .arg(borderColor));
367 : 181 : }
368 : :
369 : 10 : void PasswordDisplayPanel::refreshPalette() {
370 [ + + ]: 18 : for (int i = 0; i < m_grid->count(); ++i) {
371 [ + - ]: 16 : if (auto *frame = qobject_cast<QFrame *>(m_grid->itemAt(i)->widget())) {
372 : 8 : applyFrameStyle(frame);
373 : : }
374 : : }
375 : 10 : }
376 : :
377 : : // Shared by addField() and addOtpField() so they cannot drift apart on
378 : : // spacing or border colour.
379 : 173 : auto PasswordDisplayPanel::createFieldFrame() -> QFrame * {
380 : 173 : auto *frame = new QFrame();
381 : 173 : auto *frameLayout = new QHBoxLayout();
382 : 173 : frameLayout->setContentsMargins(5, 2, 2, 2);
383 : 173 : frameLayout->setSpacing(0);
384 : 173 : frame->setLayout(frameLayout);
385 : 173 : applyFrameStyle(frame);
386 : 173 : return frame;
387 : : }
388 : :
389 : : // One label plus one frame, like every row, so grid rows match
390 : : // displayFields()' position counter. hidePassword does not apply (the code
391 : : // expires in seconds, next to a visible countdown), and there is no QR
392 : : // button: a QR of the configuration would show the shared secret.
393 : 21 : void PasswordDisplayPanel::addOtpField(int position, const QString &otpConfig,
394 : : const AppSettings &s) {
395 : 21 : Totp::Refusal why = Totp::Refusal::None;
396 : 21 : const std::optional<Totp::Settings> settings = Totp::parse(otpConfig, &why);
397 [ + + ]: 21 : if (!settings.has_value()) {
398 : : // Report the problem without echoing what the user stored: the value is
399 : : // still a would-be secret, so it gets neither a copy nor a QR button.
400 : : // Why it gives no code (HOTP, an export, an unknown algorithm), where
401 : : // parse() can say.
402 : 2 : AppSettings inert = s;
403 : 2 : inert.clipBoardType = Enums::CLIPBOARD_NEVER;
404 : 2 : inert.useQrencode = false;
405 : 2 : inert.hidePassword = false; // a message, never behind the eye button
406 : 2 : const QString reason = Totp::describe(why);
407 : 4 : addField(position, QObject::tr("OTP code"),
408 : : reason.isEmpty()
409 [ - + ]: 4 : ? QObject::tr("No OTP code found in this password entry")
410 : : : reason,
411 : : inert);
412 : : return;
413 : 2 : }
414 : :
415 : 19 : auto *frame = createFieldFrame();
416 : : auto *otpWidget =
417 : 19 : new OtpCodeWidget(*settings, s.clipBoardType != Enums::CLIPBOARD_NEVER,
418 [ + + ]: 19 : s.useMonospace, frame);
419 : 19 : connect(otpWidget, &OtpCodeWidget::copyRequested, this,
420 : 19 : &PasswordDisplayPanel::copyRequested);
421 : 19 : frame->layout()->addWidget(otpWidget);
422 : :
423 : 38 : addRow(position, new QLabel(QObject::tr("OTP code")), frame);
424 : : }
|