QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
totp.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2025 KeePassXC Team <team@keepassxc.org>
2// SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
3// SPDX-License-Identifier: GPL-3.0-or-later
4
13
14#include "totp.h"
15#include "base32.h"
16
17#include <QCoreApplication>
18#include <QCryptographicHash>
19#include <QDateTime>
20#include <QLatin1Char>
21#include <QMessageAuthenticationCode>
22#include <QStringList>
23#include <QUrl>
24#include <QUrlQuery>
25#include <QtEndian>
26#include <QtGlobal>
27#include <string_view>
28
29#include <algorithm>
30
31namespace {
32
34constexpr std::string_view kSteamAlphabet = "23456789BCDFGHJKMNPQRTVWXY";
36constexpr quint64 kSteamAlphabetSize = kSteamAlphabet.size();
38constexpr int kMinHmacSize = 20;
39
52auto algorithmByName(const QString &name) -> std::optional<Totp::Algorithm> {
53 QString compact = name.trimmed().toUpper();
54 compact.remove(QLatin1Char('-'));
55 compact.remove(QLatin1Char('_'));
56 if (compact.startsWith(QStringLiteral("HMAC"))) {
57 compact.remove(0, 4);
58 }
59 if (compact == QStringLiteral("SHA1")) {
61 }
62 if (compact == QStringLiteral("SHA256")) {
64 }
65 if (compact == QStringLiteral("SHA512")) {
67 }
68 return std::nullopt;
69}
70
76auto algorithmName(Totp::Algorithm algorithm) -> QString {
77 switch (algorithm) {
79 return QStringLiteral("SHA512");
81 return QStringLiteral("SHA256");
83 break;
84 }
85 return QStringLiteral("SHA1");
86}
87
93auto cryptoHash(Totp::Algorithm algorithm) -> QCryptographicHash::Algorithm {
94 switch (algorithm) {
96 return QCryptographicHash::Sha512;
98 return QCryptographicHash::Sha256;
100 break;
101 }
102 return QCryptographicHash::Sha1;
103}
104
106auto encodeLabel(const QString &value) -> QString {
107 return QString::fromLatin1(QUrl::toPercentEncoding(value, ":@"));
108}
109
116auto parsePositiveUInt(const QString &value, uint fallback) -> uint {
117 bool ok = false;
118 const uint parsed = value.toUInt(&ok);
119 return (ok && parsed > 0) ? parsed : fallback;
120}
121
123using QueryItems = QList<QPair<QString, QString>>;
124
137auto firstParam(const QueryItems &items, QLatin1StringView name)
138 -> std::optional<QString> {
139 for (const QPair<QString, QString> &item : items) {
140 if (item.first.compare(name, Qt::CaseInsensitive) == 0) {
141 return item.second;
142 }
143 }
144 return std::nullopt;
145}
146
152auto unmodelledParams(const QueryItems &items) -> QueryItems {
153 // Anything we do not model is kept verbatim so toUri() can put it back;
154 // dropping it silently mutated URIs carrying e.g. `image=`.
155 static const QStringList known = {
156 QStringLiteral("secret"), QStringLiteral("issuer"),
157 QStringLiteral("digits"), QStringLiteral("period"),
158 QStringLiteral("algorithm"), QStringLiteral("encoder")};
159 QueryItems extra;
160 for (const QPair<QString, QString> &item : items) {
161 if (!known.contains(item.first, Qt::CaseInsensitive)) {
162 extra.append(item);
163 }
164 }
165 return extra;
166}
167
176auto readOtpauthUri(const QUrl &url, const QString &trimmed,
177 Totp::Settings &settings, QString &rawSecret)
178 -> Totp::Refusal {
179 // Counter-based HOTP cannot be generated from a clock; refuse rather than
180 // return a wrong code that looks right.
181 if (url.host().compare(QStringLiteral("totp"), Qt::CaseInsensitive) != 0) {
182 return url.host().compare(QStringLiteral("hotp"), Qt::CaseInsensitive) == 0
185 }
186
187 const QUrlQuery query(url);
188 // FullyDecoded, because toUri() percent-encodes these again: the default
189 // PrettyDecoded leaves escapes in place and the round trip double-encodes.
190 const QueryItems items = query.queryItems(QUrl::FullyDecoded);
191 const auto param = [&items](QLatin1StringView name) {
192 return firstParam(items, name);
193 };
194 rawSecret = param(QLatin1StringView("secret")).value_or(QString());
195 settings.issuer = param(QLatin1StringView("issuer")).value_or(QString());
196 // Not part of the OTP configuration, but the user's text: kept as written,
197 // from the input itself (QUrl splits at the first '#' as well, but its
198 // view would re-encode '%' and '`' and decode escapes).
199 if (url.hasFragment()) {
200 settings.fragment = trimmed.mid(trimmed.indexOf(QLatin1Char('#')) + 1);
201 }
202 // The label is everything after the host, e.g. "/Example:alice".
203 settings.label = url.path();
204 if (settings.label.startsWith(QLatin1Char('/'))) {
205 settings.label.remove(0, 1);
206 }
207 // toUInt() returns 0 with no error signal for anything non-numeric, and the
208 // clamp below would turn that into digits=1 / step=1 — a one-character code
209 // rotating every second, which normalize() would then persist. Keep the RFC
210 // default unless the value really is a usable number.
211 settings.digits =
212 parsePositiveUInt(param(QLatin1StringView("digits")).value_or(QString()),
214 settings.step =
215 parsePositiveUInt(param(QLatin1StringView("period")).value_or(QString()),
217 // An empty value is the default, as an absent one is. An unknown hash
218 // function is refused, as HOTP is: its code cannot be made here.
219 if (const std::optional<QString> algorithm =
220 param(QLatin1StringView("algorithm"));
221 algorithm.has_value() && !algorithm->trimmed().isEmpty()) {
222 const std::optional<Totp::Algorithm> known = algorithmByName(*algorithm);
223 if (!known.has_value()) {
225 }
226 settings.algorithm = *known;
227 }
228 if (param(QLatin1StringView("encoder"))
229 .value_or(QString())
230 .compare(QStringLiteral("steam"), Qt::CaseInsensitive) == 0) {
231 settings.encoder = Totp::Encoder::Steam;
232 }
233 settings.extraParams.append(unmodelledParams(items));
234 return Totp::Refusal::None;
235}
236
253auto isWrittenAsSecret(const QString &text) -> bool {
254 return std::all_of(text.cbegin(), text.cend(), [](QChar c) {
255 const char16_t u = c.unicode();
256 return c.isSpace() || u == u'-' || u == u'=' || u == u'.' || u == u'_' ||
257 (u >= u'A' && u <= u'Z') || (u >= u'a' && u <= u'z') ||
258 (u >= u'0' && u <= u'8');
259 });
260}
261
262} // namespace
263
264auto Totp::parse(const QString &config, Refusal *why)
265 -> std::optional<Settings> {
266 const auto refuse = [why](Refusal reason) -> std::optional<Settings> {
267 if (why != nullptr) {
268 *why = reason;
269 }
270 return std::nullopt;
271 };
272 if (why != nullptr) {
273 *why = Refusal::None;
274 }
275 // Checked before anything else sees it (trimmed() copies it, QUrl and
276 // QUrlQuery would make a crafted URI of tens of MiB tens of millions of
277 // query items on the GUI thread); padding counts too.
278 if (config.size() > MAX_CONFIG_LENGTH) {
279 return refuse(Refusal::TooLong);
280 }
281 const QString trimmed = config.trimmed();
282 if (trimmed.isEmpty()) {
283 return refuse(Refusal::Empty);
284 }
285
286 Settings settings;
287 QString rawSecret;
288
289 const QUrl url(trimmed);
290 if (url.isValid() && url.scheme().compare(QStringLiteral("otpauth"),
291 Qt::CaseInsensitive) == 0) {
292 const Refusal unread = readOtpauthUri(url, trimmed, settings, rawSecret);
293 if (unread != Refusal::None) {
294 return refuse(unread);
295 }
296 } else if (trimmed.startsWith(QStringLiteral("otpauth:"),
297 Qt::CaseInsensitive)) {
298 // Claims to be an otpauth URI but QUrl could not parse it. Falling through
299 // to the bare-secret branch would hand the whole string to
300 // Base32::sanitizeInput(), which strips the punctuation and leaves
301 // decodable base32 — producing a confidently wrong code. Refuse instead.
302 return refuse(Refusal::UnreadableUri);
303 } else {
304 // Not an otpauth URI: a bare base32 secret.
305 if (!isWrittenAsSecret(trimmed)) {
306 return refuse(Refusal::NotASecret);
307 }
308 rawSecret = trimmed;
309 }
310
311 const QByteArray sanitized = Base32::sanitizeInput(rawSecret.toLatin1());
312 settings.key = Base32::decode(sanitized);
313 if (settings.key.isEmpty()) {
314 return refuse(Refusal::NoSecret);
315 }
316 settings.base32Key = QString::fromLatin1(sanitized);
317
318 if (settings.encoder == Encoder::Steam) {
319 settings.digits = STEAM_DIGITS;
320 }
321 // Clamp on every path: an out-of-range `digits` would otherwise overflow the
322 // modulus, and a zero `step` would divide by zero.
323 settings.digits = qBound(MIN_DIGITS, settings.digits, MAX_DIGITS);
324 settings.step = qBound(1U, settings.step, MAX_STEP);
325
326 return settings;
327}
328
329auto Totp::describe(Refusal why) -> QString {
330 switch (why) {
331 case Refusal::TooLong:
332 //: OTP is a one-time password (a two-factor code).
333 return QCoreApplication::translate("Totp",
334 "The OTP configuration is too long.");
335 case Refusal::Hotp:
336 //: Keep HOTP and TOTP as written: they are the names of the two kinds.
337 return QCoreApplication::translate(
338 "Totp", "This is a counter-based (HOTP) configuration. QtPass makes "
339 "time-based (TOTP) codes only.");
341 //: Keep otpauth://, SHA1, SHA256 and SHA512 as written.
342 return QCoreApplication::translate(
343 "Totp", "The algorithm in this otpauth:// link is not supported. "
344 "QtPass supports SHA1, SHA256 and SHA512.");
346 //: Keep otpauth:// as written: it is the name of the link format.
347 return QCoreApplication::translate("Totp",
348 "This otpauth:// link cannot be read.");
350 //: Keep TOTP and otpauth://totp/ as written.
351 return QCoreApplication::translate(
352 "Totp", "This is not a TOTP secret or an otpauth://totp/ link.");
354 //: The secret is the shared key of the one-time password; keep base32.
355 return QCoreApplication::translate(
356 "Totp", "The secret is missing or is not valid base32.");
357 case Refusal::None:
358 case Refusal::Empty:
359 break;
360 }
361 return {};
362}
363
364auto Totp::isValid(const QString &config) -> bool {
365 return parse(config).has_value();
366}
367
368auto Totp::counter(const Settings &settings, quint64 unixTime) -> quint64 {
369 return unixTime / settings.step;
370}
371
372auto Totp::secondsRemaining(const Settings &settings, quint64 unixTime)
373 -> uint {
374 return settings.step - static_cast<uint>(unixTime % settings.step);
375}
376
377auto Totp::generate(const Settings &settings, quint64 unixTime) -> QString {
378 const quint64 bigEndianCounter = qToBigEndian(counter(settings, unixTime));
379 const QByteArray message(reinterpret_cast<const char *>(&bigEndianCounter),
380 sizeof(bigEndianCounter));
381
382 const QByteArray hmac = QMessageAuthenticationCode::hash(
383 message, settings.key, cryptoHash(settings.algorithm));
384 if (hmac.size() < kMinHmacSize) {
385 return {};
386 }
387
388 // RFC 4226 dynamic truncation. QByteArray elements are signed char, so every
389 // byte is widened through quint8: without that, any byte >= 0x80
390 // sign-extends and corrupts the assembled 31-bit value.
391 const int offset =
392 static_cast<quint8>(hmac.at(hmac.size() - 1)) & 0x0F; // NOLINT
393 const quint32 binary =
394 (static_cast<quint32>(static_cast<quint8>(hmac.at(offset)) & 0x7F)
395 << 24) |
396 (static_cast<quint32>(static_cast<quint8>(hmac.at(offset + 1))) << 16) |
397 (static_cast<quint32>(static_cast<quint8>(hmac.at(offset + 2))) << 8) |
398 static_cast<quint32>(static_cast<quint8>(hmac.at(offset + 3)));
399
400 if (settings.encoder == Encoder::Steam) {
401 // Steam emits the least significant symbol first.
402 quint64 value = binary;
403 QString code;
404 code.reserve(static_cast<int>(STEAM_DIGITS));
405 for (uint i = 0; i < STEAM_DIGITS; ++i) {
406 code.append(QLatin1Char(kSteamAlphabet[value % kSteamAlphabetSize]));
407 value /= kSteamAlphabetSize;
408 }
409 return code;
410 }
411
412 // Integer exponentiation into a quint64: pow() into a quint32 (as KeePassXC
413 // did) overflows at ten digits.
414 quint64 modulus = 1;
415 for (uint i = 0; i < settings.digits; ++i) {
416 modulus *= 10;
417 }
418 return QString::number(binary % modulus)
419 .rightJustified(static_cast<int>(settings.digits), QLatin1Char('0'));
420}
421
422auto Totp::generateNow(const Settings &settings) -> QString {
423 return generate(settings, currentUnixTime());
424}
425
426auto Totp::toUri(const Settings &settings) -> QString {
427 const QString label =
428 settings.label.isEmpty() ? QStringLiteral("QtPass") : settings.label;
429 // The Key-Uri-Format spec says the secret's base32 padding is omitted, and
430 // third-party importers reject or truncate `secret=...======`.
431 // sanitizeInput() re-adds padding when reading, so this round-trips.
432 const QString secret =
433 QString::fromLatin1(Base32::removePadding(settings.base32Key.toLatin1()));
434 QString uri = QStringLiteral("otpauth://totp/%1?secret=%2")
435 .arg(encodeLabel(label), secret);
436 if (!settings.issuer.isEmpty()) {
437 uri += QStringLiteral("&issuer=%1").arg(encodeLabel(settings.issuer));
438 }
439 if (settings.algorithm != Algorithm::Sha1) {
440 uri +=
441 QStringLiteral("&algorithm=%1").arg(algorithmName(settings.algorithm));
442 }
443 uri += QStringLiteral("&digits=%1&period=%2")
444 .arg(settings.digits)
445 .arg(settings.step);
446 if (settings.encoder == Encoder::Steam) {
447 uri += QStringLiteral("&encoder=steam");
448 }
449 // Re-emit anything the parser did not model, so canonicalising an existing
450 // URI does not quietly discard parameters other authenticators honour.
451 for (const QPair<QString, QString> &item : settings.extraParams) {
452 uri += QStringLiteral("&%1=%2").arg(
453 QString::fromLatin1(QUrl::toPercentEncoding(item.first)),
454 QString::fromLatin1(QUrl::toPercentEncoding(item.second)));
455 }
456 if (!settings.fragment.isEmpty()) {
457 uri += QLatin1Char('#') + settings.fragment;
458 }
459 return uri;
460}
461
462auto Totp::normalize(const QString &config, const QString &label,
463 const QString &issuer) -> QString {
464 const std::optional<Settings> settings = parse(config);
465 if (!settings.has_value()) {
466 return {};
467 }
468 Settings canonical = *settings;
469 if (canonical.label.isEmpty()) {
470 canonical.label = label;
471 }
472 if (canonical.issuer.isEmpty()) {
473 canonical.issuer = issuer;
474 }
475 // Percent-encoding and the added fields can take a value near the length
476 // cap past it; a URI parse() refuses would store an OTP that makes no code.
477 QString uri = toUri(canonical);
478 if (uri.size() > MAX_CONFIG_LENGTH) {
479 return {};
480 }
481 return uri;
482}
483
484auto Totp::currentUnixTime() -> quint64 {
485 return static_cast<quint64>(QDateTime::currentSecsSinceEpoch());
486}
Strict RFC 4648 base32 codec plus the input sanitizer that makes human-typed TOTP secrets decodable.
static auto sanitizeInput(const QByteArray &encodedData) -> QByteArray
Make human-entered base32 text decodable.
Definition base32.cpp:306
static auto decode(const QByteArray &encodedData) -> QByteArray
Decode strict RFC 4648 base32 data.
Definition base32.cpp:129
static auto removePadding(const QByteArray &encodedData) -> QByteArray
Strip trailing '=' padding.
Definition base32.cpp:295
Algorithm
HMAC hash function, selected by the algorithm URI parameter.
Definition totp.h:41
@ Sha256
HMAC-SHA-256.
Definition totp.h:43
@ Sha1
HMAC-SHA-1, the RFC 6238 default.
Definition totp.h:42
@ Sha512
HMAC-SHA-512.
Definition totp.h:44
static constexpr uint MAX_STEP
Definition totp.h:97
static constexpr uint MIN_DIGITS
Lower clamp for digits.
Definition totp.h:95
static constexpr uint DEFAULT_STEP
RFC 6238 default period.
Definition totp.h:93
static auto counter(const Settings &settings, quint64 unixTime) -> quint64
Time-step counter for a point in time.
Definition totp.cpp:368
static auto generateNow(const Settings &settings) -> QString
Generate the code for the current wall-clock time.
Definition totp.cpp:422
static auto parse(const QString &config, Refusal *why=nullptr) -> std::optional< Settings >
Parse an OTP configuration string.
Definition totp.cpp:264
static constexpr uint DEFAULT_DIGITS
RFC 6238 default code length.
Definition totp.h:92
static constexpr qsizetype MAX_CONFIG_LENGTH
Definition totp.h:101
static constexpr uint STEAM_DIGITS
Steam codes are always 5 chars.
Definition totp.h:94
static auto currentUnixTime() -> quint64
Current wall-clock time.
Definition totp.cpp:484
static auto toUri(const Settings &settings) -> QString
Serialise settings as a canonical otpauth URI.
Definition totp.cpp:426
static auto normalize(const QString &config, const QString &label={}, const QString &issuer={}) -> QString
Normalise a user-entered value to a canonical otpauth URI.
Definition totp.cpp:462
static auto generate(const Settings &settings, quint64 unixTime) -> QString
Generate the code for a given point in time.
Definition totp.cpp:377
static auto describe(Refusal why) -> QString
One sentence for the user on why a configuration gives no code.
Definition totp.cpp:329
@ Steam
Steam Guard's five-character alphabet.
Definition totp.h:52
Refusal
Why parse() gave no settings, so the user can be told more than "invalid".
Definition totp.h:59
@ TooLong
Longer than MAX_CONFIG_LENGTH.
Definition totp.h:62
@ None
Parsed: there was nothing to refuse.
Definition totp.h:60
@ UnknownAlgorithm
An algorithm other than SHA-1, -256 or -512.
Definition totp.h:64
@ Hotp
An otpauth://hotp/ URI: counter-based.
Definition totp.h:63
@ NotASecret
Neither an otpauth URI nor written as a secret.
Definition totp.h:66
@ UnreadableUri
otpauth: but no URI QUrl reads, or no totp.
Definition totp.h:65
@ NoSecret
No secret, or one that is not valid base32.
Definition totp.h:67
@ Empty
Nothing but white space.
Definition totp.h:61
static constexpr uint MAX_DIGITS
Upper clamp for digits.
Definition totp.h:96
static auto isValid(const QString &config) -> bool
Convenience validity test, for UI feedback.
Definition totp.cpp:364
static auto secondsRemaining(const Settings &settings, quint64 unixTime) -> uint
Seconds until the code for unixTime expires.
Definition totp.cpp:372
Validated TOTP parameters. Only Totp::parse() produces one.
Definition totp.h:74
QString label
otpauth label; may be empty.
Definition totp.h:81
QString issuer
Definition totp.h:82
uint digits
Code length, MIN_DIGITS..MAX_DIGITS.
Definition totp.h:79
QByteArray key
Decoded shared secret; never empty.
Definition totp.h:75
QString base32Key
Sanitized base32 secret, for re-serialisation.
Definition totp.h:76
uint step
Period in seconds, 1..MAX_STEP.
Definition totp.h:80
Encoder encoder
Digit encoding.
Definition totp.h:78
RFC 6238 TOTP: otpauth URI parsing, code generation and canonical re-serialisation.