QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
filecontent.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2018 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
9#include "filecontent.h"
10#include "totp.h"
11#include <QRegularExpression>
12
13#include <QCoreApplication>
14#include <QStringTokenizer>
15
16#include <algorithm>
17#include <limits>
18
19#include <utility>
20
26static auto isOtpUri(const QString &value) -> bool {
27 return FileContent::isOtpUriValue(value);
28}
29
37static auto bareOtpUriOf(const QString &line) -> QString {
38 QString trimmed = line.trimmed();
39 if (isOtpUri(trimmed)) {
40 return trimmed;
41 }
42 static const QString scheme = QStringLiteral("otpauth:");
43 if (!trimmed.startsWith(scheme, Qt::CaseInsensitive)) {
44 return {};
45 }
46 qsizetype i = scheme.size();
47 while (i < trimmed.size() && trimmed.at(i).isSpace()) {
48 ++i;
49 }
50 if (trimmed.mid(i, 2) != QLatin1String("//")) {
51 return {};
52 }
53 return trimmed.left(scheme.size()) + trimmed.mid(i);
54}
55
63static auto isLineHidden(const QString &line) -> bool {
64 return FileContent::isOtpLine(line);
65}
66
79static auto isBase32Seed(const QString &value) -> bool {
80 qsizetype letters = 0;
81 for (const QChar c : value) {
82 const char16_t u = c.unicode();
83 // Grouping and padding, as seeds are written and pasted: spaces, tabs, a
84 // no-break space, dashes, dots, underscores, "=". Base32::sanitizeInput()
85 // drops them too, and Totp::parse() accepts them.
86 if (c.isSpace() || u == u'-' || u == u'.' || u == u'_' || u == u'=') {
87 continue;
88 }
89 if (!((u >= u'A' && u <= u'Z') || (u >= u'a' && u <= u'z') ||
90 (u >= u'2' && u <= u'7'))) {
91 return false;
92 }
93 ++letters;
94 }
95 constexpr qsizetype kMinSeedLetters = 16;
96 return letters >= kMinSeedLetters && Totp::isValid(value);
97}
98
104static auto afterFirstColon(const QString &line) -> QString {
105 const qsizetype colon = line.indexOf(u':');
106 return colon < 0 ? QString() : line.mid(colon + 1);
107}
108
117static auto holdsOtpConfig(const QString &line) -> bool {
118 if (!bareOtpUriOf(line).isEmpty()) {
119 return true;
120 }
121 const qsizetype colon = line.indexOf(u':');
122 if (colon < 0) {
123 return false;
124 }
125 const QString value = line.mid(colon + 1);
126 // Any field holding an otpauth URI is a shared secret; an OTP-named field
127 // only when what it holds would give a code: the line is the password
128 // otherwise, as the pass format has it.
129 return isOtpUri(value) ||
130 (FileContent::isOtpFieldName(line.left(colon)) && isBase32Seed(value));
131}
132
139static auto otpConfigOf(const QString &line) -> QString {
140 if (const QString uri = bareOtpUriOf(line); !uri.isEmpty()) {
141 return uri;
142 }
143 return line.mid(line.indexOf(u':') + 1).trimmed();
144}
145
146namespace {
147
152struct OtpCandidate {
153 QString first;
154 QString usable;
155
160 void offer(const QString &config) {
161 if (!usable.isEmpty()) {
162 return;
163 }
164 if (first.isEmpty()) {
165 first = config;
166 }
167 if (Totp::isValid(config)) {
168 usable = config;
169 }
170 }
171};
172
178struct OtpCandidates {
179 OtpCandidate field;
180 OtpCandidate bareLine;
181 OtpCandidate remainingField;
182
190 auto pick() const -> QString {
191 for (const OtpCandidate *kind : {&field, &bareLine, &remainingField}) {
192 if (!kind->usable.isEmpty()) {
193 return kind->usable;
194 }
195 }
196 for (const OtpCandidate *kind : {&field, &bareLine, &remainingField}) {
197 if (!kind->first.isEmpty()) {
198 return kind->first;
199 }
200 }
201 return {};
202 }
203};
204
217auto takeNamedValue(const QString &line, const QStringList &templateFields,
218 bool allFields,
219 const std::function<bool(const QString &)> &alsoField,
220 NamedValues &namedValues, OtpCandidates &otp) -> bool {
221 const qsizetype colon = line.indexOf(u':');
222 if (colon < 0) {
223 return false;
224 }
225 const QString name = line.left(colon);
226 const QString value = line.right(line.length() - colon - 1);
227 // A value starting with // means the colon is probably from a URL.
228 if (!templateFields.contains(name) &&
229 !(allFields && !value.startsWith(QStringLiteral("//"))) &&
230 !(alsoField && alsoField(name.trimmed()))) {
231 // An `OTP:` line the template did not promote to a field.
232 if (FileContent::isOtpFieldName(name)) {
233 otp.remainingField.offer(value.trimmed());
234 }
235 return false;
236 }
237 namedValues.append({name.trimmed(), value.trimmed(), line});
238 // Keyed on the value as well as the name: a field called anything at all
239 // whose value is an otpauth URI is still a shared secret.
241 otp.field.offer(value.trimmed());
242 }
243 return true;
244}
245
251auto moreLinesNotShown(qsizetype count) -> QString {
252 // The count in a variable of its own: lupdate up to 6.8 loses a
253 // translate() call with template arguments among its arguments and would
254 // mark the string vanished.
255 const int n = static_cast<int>(
256 std::min<qsizetype>(count, std::numeric_limits<int>::max()));
257 return QCoreApplication::translate("FileContent",
258 "… %n more line(s) not shown", nullptr, n);
259}
260
264struct RemainingText {
265 QString data;
266 QString display;
267 qsizetype lines = 0;
268 qsizetype displayed = 0;
269 qsizetype notShown = 0;
270
276 void add(const QString &line, bool shown) {
277 // Joined with "\n" as they go, as split() and join() did.
278 if (lines > 0) {
279 data += QLatin1Char('\n');
280 }
281 data += line;
282 ++lines;
283 if (!shown) {
284 return;
285 }
286 if (displayed == FileContent::kMaxDisplayLines) {
287 ++notShown;
288 return;
289 }
290 if (displayed > 0) {
291 display += QLatin1Char('\n');
292 }
293 display += line;
294 ++displayed;
295 }
296
302 [[nodiscard]] auto forDisplay() const -> QString {
303 if (notShown > 0) {
304 return display + QLatin1Char('\n') + moreLinesNotShown(notShown);
305 }
306 return display;
307 }
308};
309
310} // namespace
311
312auto FileContent::parse(const QString &fileContent,
313 const QStringList &templateFields, bool allFields,
314 const std::function<bool(const QString &)> &alsoField)
315 -> FileContent {
316 // Line by line over the text, never a list of every line: a compressed
317 // entry can expand into tens of millions of lines within the plaintext
318 // limit, and a QString each (empty ones too) would take gigabytes.
319 QStringTokenizer tokens = QStringView(fileContent).tokenize(u'\n');
320 auto it = tokens.begin();
321 QString password;
322 if (it != tokens.end()) {
323 password = passwordLine(*it);
324 ++it;
325 }
326 RemainingText remaining;
327 // Past kMaxNamedFields a line is still offered to takeNamedValue(), into
328 // this throwaway list, for what it notes about OTP: the line stays text.
329 NamedValues pastTheCap;
331 OtpCandidates otp;
332 // An entry from `pass otp insert` has the URI as its only (password) line,
333 // which the loop below never sees; an `OTP:`/`TOTP:` field written there by
334 // hand holding a usable secret is the same, and yields a code as it does
335 // further down. Read only from what is written as a configuration
336 // (holdsOtpConfig()); a first line with a URI elsewhere in it is kept off
337 // the screen all the same (isOtpPasswordLine()).
339 otp.bareLine.offer(otpConfigOf(password));
340 }
341 for (; it != tokens.end(); ++it) {
342 const QString line = it->toString();
343 bool secretPastTheCap = false;
344 // A line with an otpauth URI in it is never a field unless the URI is
345 // its value ("2fa: otpauth://..."), also not when the template lists
346 // "otpauth": split at a colon, the value would lose the scheme that
347 // marks it as a shared secret and be shown seed and all ("otpauth://...",
348 // "AWS: backup phone: otpauth://..."). Past kMaxNamedFields, lines stay
349 // text.
350 if (!carriesOtpUri(line) || isOtpUri(afterFirstColon(line))) {
351 if (namedValues.size() < kMaxNamedFields) {
352 if (takeNamedValue(line, templateFields, allFields, alsoField,
353 namedValues, otp)) {
354 continue;
355 }
356 } else {
357 takeNamedValue(line, templateFields, allFields, alsoField, pastTheCap,
358 otp);
359 // A secret past the cap stays text, but not on screen: the panel
360 // would have hidden it.
361 secretPastTheCap = !pastTheCap.isEmpty() && alsoField &&
362 alsoField(pastTheCap.first().name);
363 pastTheCap.clear();
364 }
365 }
366 remaining.add(line, !isLineHidden(line) && !secretPastTheCap);
367 // A bare otpauth:// line, the convention the pass-otp extension uses,
368 // or the split form older versions saved.
369 if (const QString uri = bareOtpUriOf(line); !uri.isEmpty()) {
370 otp.bareLine.offer(uri);
371 }
372 }
373 // The OTP value stays in namedValues/remainingData: the edit dialog reads it
374 // from there and PasswordDialog::getPassword() drops empty fields, so
375 // stripping it here would delete the secret on the next save. Suppression
376 // happens in getRemainingDataForDisplay() and PasswordDisplayPanel.
377 return {std::move(password), std::move(namedValues),
378 remaining.data, remaining.forDisplay(),
379 otp.pick(), remaining.lines};
380}
381
382auto FileContent::isOtpFieldName(const QString &name) -> bool {
383 const QString trimmed = name.trimmed();
384 return trimmed.compare(QStringLiteral("OTP"), Qt::CaseInsensitive) == 0 ||
385 trimmed.compare(QStringLiteral("TOTP"), Qt::CaseInsensitive) == 0;
386}
387
388auto FileContent::isSecretFieldName(const QString &name,
389 const QStringList &secrets) -> bool {
390 // One pattern for the whole list, compiled once per list: the panel asks
391 // for every field of every entry shown, and the list rarely changes.
392 thread_local QStringList cachedSecrets;
393 thread_local QStringList cachedWords;
394 thread_local QRegularExpression cachedPattern;
395 thread_local bool cachedYet = false;
396 constexpr auto options = QRegularExpression::CaseInsensitiveOption |
397 QRegularExpression::UseUnicodePropertiesOption;
398 if (!cachedYet || secrets != cachedSecrets) {
399 cachedWords.clear();
400 for (const QString &secret : secrets) {
401 const QString word = secret.trimmed();
402 if (word.isEmpty()) {
403 continue;
404 }
405 // A word counts when no letter touches it: digits and `_` end a word
406 // as a blank does ("PIN2", "api_key"), and a plural "s" may follow
407 // ("tokens", "Security answers"); "key" is still not in "keyboard".
408 // A word that starts or ends with a digit is not part of a longer
409 // number either ("tan1" not in "tan12").
410 const QString letters = QStringLiteral("\\p{L}\\p{M}");
411 const QString before =
412 word.front().isDigit() ? letters + QStringLiteral("\\d") : letters;
413 const QString after =
414 word.back().isDigit() ? letters + QStringLiteral("\\d") : letters;
415 cachedWords << QStringLiteral("(?<![%1])%2s?(?![%3])")
416 .arg(before, QRegularExpression::escape(word), after);
417 }
418 cachedSecrets = secrets;
419 cachedYet = true;
420 cachedPattern = QRegularExpression(
421 QStringLiteral("(?:%1)").arg(cachedWords.join(QLatin1Char('|'))),
422 options);
423 }
424 if (cachedWords.isEmpty()) {
425 return false;
426 }
427 // camelCase names its words with capitals, which a case-insensitive match
428 // does not see, so the name is also tried with a blank at each word start:
429 // "apiKey" as "api Key", "APIKey" as "API Key". The acronym rule cuts a
430 // capitals word that a lower-case letter follows ("cardPINs" as "card PI
431 // Ns"), so a split at lower-to-upper starts alone is tried too ("card
432 // PINs", "sim PINcode"), and the name as written ("PINcode").
433 static const QRegularExpression lowerThenUpper(
434 QStringLiteral("(?<=[\\p{Ll}\\d])(?=\\p{Lu})"),
435 QRegularExpression::UseUnicodePropertiesOption);
436 static const QRegularExpression acronymThenWord(
437 QStringLiteral("(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})"),
438 QRegularExpression::UseUnicodePropertiesOption);
439 QString camel = name;
440 camel.replace(lowerThenUpper, QStringLiteral(" "));
441 QString words = camel;
442 words.replace(acronymThenWord, QStringLiteral(" "));
443 const auto matches = [&](const QRegularExpression &pattern) {
444 return pattern.match(name).hasMatch() ||
445 (camel != name && pattern.match(camel).hasMatch()) ||
446 (words != camel && pattern.match(words).hasMatch());
447 };
448 if (cachedPattern.isValid()) {
449 return matches(cachedPattern);
450 }
451 // Too many words for one pattern (PCRE2's size limit): word by word,
452 // rather than every secret field shown in plain view.
453 return std::any_of(cachedWords.cbegin(), cachedWords.cend(),
454 [&matches, options](const QString &word) {
455 return matches(QRegularExpression(word, options));
456 });
457}
458
459auto FileContent::isOtpUriValue(const QString &value) -> bool {
460 return value.trimmed().startsWith(QStringLiteral("otpauth://"),
461 Qt::CaseInsensitive);
462}
463
464auto FileContent::carriesOtpUri(const QString &text) -> bool {
465 // Not only at the start: "- otpauth://", "\"otpauth://...\"", "old token
466 // otpauth://", "AWS: backup phone: otpauth://" and the split "otpauth:
467 // //totp/" all showed the seed, being neither a bare line nor the value
468 // after the first colon. By hand, not a regular expression: parse() asks
469 // this for every line of an entry, up to 64 MiB of them.
470 static const QString scheme = QStringLiteral("otpauth:");
471 for (qsizetype at = text.indexOf(scheme, 0, Qt::CaseInsensitive); at >= 0;
472 at = text.indexOf(scheme, at + 1, Qt::CaseInsensitive)) {
473 qsizetype i = at + scheme.size();
474 while (i < text.size() && text.at(i).isSpace()) {
475 ++i;
476 }
477 if (text.mid(i, 2) == QLatin1String("//")) {
478 return true;
479 }
480 }
481 return false;
482}
483
484auto FileContent::passwordLine(QStringView text) -> QString {
485 // left(-1) is the whole text when there is no line feed.
486 QStringView line = text.left(text.indexOf(u'\n'));
487 if (line.endsWith(u'\r')) {
488 line.chop(1);
489 }
490 return line.toString();
491}
492
493auto FileContent::isOtpLine(const QString &line) -> bool {
494 if (carriesOtpUri(line)) {
495 return true;
496 }
497 const qsizetype colon = line.indexOf(u':');
498 return colon >= 0 && isOtpFieldName(line.left(colon));
499}
500
501auto FileContent::isOtpPasswordLine(const QString &line) -> bool {
502 return carriesOtpUri(line) || holdsOtpConfig(line);
503}
504
505auto FileContent::getPassword() const -> QString { return this->password; }
506
507auto FileContent::getPasswordForDisplay() const -> QString {
508 return isOtpPasswordLine(this->password) ? QString() : this->password;
509}
510
512 return this->namedValues;
513}
514
515auto FileContent::getRemainingData() const -> QString {
516 return this->remainingData;
517}
518
520 return this->remainingDataDisplay;
521}
522
523auto FileContent::getOtpUri() const -> QString { return this->otpUri; }
524
532
533auto FileContent::boundedForDisplay(const QString &text) -> QString {
534 // Where the line after the last one shown starts, if there is one.
535 qsizetype end = -1;
536 for (int line = 0; line < kMaxDisplayLines; ++line) {
537 end = text.indexOf(QLatin1Char('\n'), end + 1);
538 if (end < 0) {
539 return text;
540 }
541 }
542 const qsizetype more =
543 text.count(QLatin1Char('\n'), Qt::CaseSensitive) - (kMaxDisplayLines - 1);
544 return text.left(end) + QLatin1Char('\n') + moreLinesNotShown(more);
545}
546
547auto FileContent::getRemainingLineCount() const -> qsizetype {
548 return remainingLines;
549}
550
551NamedValues::NamedValues() = default;
552
553NamedValues::NamedValues(std::initializer_list<NamedValue> values)
554 : QList(values) {}
555
556auto NamedValues::takeValue(const QString &name) -> QString {
557 return takeNamedValue(name).value;
558}
559
560auto NamedValues::takeNamedValue(const QString &name) -> NamedValue {
561 for (int i = 0; i < length(); ++i) {
562 if (at(i).name == name) {
563 return takeAt(i);
564 }
565 }
566 return {};
567}
static auto boundedForDisplay(const QString &text) -> QString
text cut to kMaxDisplayLines lines, as getRemainingDataForDisplay() is: for showing an entry as it is...
FileContent(QString password, NamedValues namedValues, QString remainingData, QString remainingDataDisplay, QString otpUri, qsizetype remainingLines)
Assemble a parsed entry; only parse() calls this.
qsizetype remainingLines
Number of lines in remainingData.
static auto passwordLine(QStringView text) -> QString
The password of an entry: its first line, without the carriage return of a CRLF line end.
QString remainingData
Body lines that are not fields, joined with newlines; complete.
auto getRemainingLineCount() const -> qsizetype
How many lines getRemainingData() holds.
QString password
The first line of the entry, without the "\r" of a CRLF line end (passwordLine()).
static auto isOtpFieldName(const QString &name) -> bool
Whether a field name designates the one-time password field.
QString otpUri
Raw OTP configuration (URI or bare base32), or empty.
static auto isOtpLine(const QString &line) -> bool
Whether line carries a TOTP shared secret: a bare otpauth:// line, an OTP:/TOTP: field,...
static constexpr int kMaxDisplayLines
Most lines of remaining text getRemainingDataForDisplay() gives.
auto getRemainingData() const -> QString
auto getNamedValues() const -> NamedValues
static constexpr int kMaxNamedFields
Most named fields parse() takes from one entry.
static auto parse(const QString &fileContent, const QStringList &templateFields, bool allFields, const std::function< bool(const QString &)> &alsoField={}) -> FileContent
parse parses the given fileContent in a FileContent object. The password is accessible through getPas...
static auto isSecretFieldName(const QString &name, const QStringList &secrets) -> bool
Whether a field name names a secret: one of secrets occurs in it as whole words, compared case-insens...
NamedValues namedValues
Fields in order of appearance, template fields first.
auto getRemainingDataForDisplay() const -> QString
Like getRemainingData but without data that should not be displayed (like a TOTP secret).
auto getPassword() const -> QString
The password: the first line, without the "\r" of a CRLF line end (passwordLine()).
auto getOtpUri() const -> QString
The entry's raw one-time password configuration, if it has one.
static auto isOtpPasswordLine(const QString &line) -> bool
Whether an entry's first line holds a TOTP shared secret rather than a password.
QString remainingDataDisplay
auto getPasswordForDisplay() const -> QString
Like getPassword but empty when the password line holds a TOTP shared secret (isOtpPasswordLine()).
static auto carriesOtpUri(const QString &text) -> bool
Whether text holds an otpauth URI anywhere: after a list dash, in quotes, behind other text or a seco...
static auto isOtpUriValue(const QString &value) -> bool
Whether a field value is an otpauth URI, and therefore a secret.
The NamedValues class is mostly a list of NamedValue but also has a method to take a specific NamedVa...
Definition filecontent.h:58
auto takeValue(const QString &name) -> QString
Remove and return the value for the named field.
auto takeNamedValue(const QString &name) -> NamedValue
Remove and return the named field, its original line included.
NamedValues()
Construct an empty list.
static auto isValid(const QString &config) -> bool
Convenience validity test, for UI feedback.
Definition totp.cpp:364
static auto otpConfigOf(const QString &line) -> QString
The OTP configuration an OTP line holds: the URI for a bare otpauth:// line (bareOtpUriOf()),...
static auto bareOtpUriOf(const QString &line) -> QString
The otpauth URI a line is written as: a bare otpauth:// line, or the split otpauth: //....
static auto isBase32Seed(const QString &value) -> bool
Whether value is written as a TOTP seed: base32 letters and the digits 2 to 7 only (either case; whit...
static auto isLineHidden(const QString &line) -> bool
Whether a body line must stay out of the parsed display because it carries a TOTP shared secret (File...
static auto afterFirstColon(const QString &line) -> QString
What follows a line's first colon; empty without one.
static auto isOtpUri(const QString &value) -> bool
Shorthand for the public FileContent::isOtpUriValue.
static auto holdsOtpConfig(const QString &line) -> bool
Whether a first line is written as an OTP configuration that otpConfigOf() can read: a bare otpauth U...
Parser for a decrypted password entry: password line, key: value fields, remaining text and the OTP c...
A name/value pair parsed from a password file field.
Definition filecontent.h:21
RFC 6238 TOTP: otpauth URI parsing, code generation and canonical re-serialisation.