17#include <QCoreApplication>
18#include <QCryptographicHash>
21#include <QMessageAuthenticationCode>
34constexpr std::string_view kSteamAlphabet =
"23456789BCDFGHJKMNPQRTVWXY";
36constexpr quint64 kSteamAlphabetSize = kSteamAlphabet.size();
38constexpr int kMinHmacSize = 20;
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"))) {
59 if (compact == QStringLiteral(
"SHA1")) {
62 if (compact == QStringLiteral(
"SHA256")) {
65 if (compact == QStringLiteral(
"SHA512")) {
79 return QStringLiteral(
"SHA512");
81 return QStringLiteral(
"SHA256");
85 return QStringLiteral(
"SHA1");
93auto cryptoHash(
Totp::Algorithm algorithm) -> QCryptographicHash::Algorithm {
96 return QCryptographicHash::Sha512;
98 return QCryptographicHash::Sha256;
102 return QCryptographicHash::Sha1;
106auto encodeLabel(
const QString &value) -> QString {
107 return QString::fromLatin1(QUrl::toPercentEncoding(value,
":@"));
116auto parsePositiveUInt(
const QString &value, uint fallback) -> uint {
118 const uint parsed = value.toUInt(&ok);
119 return (ok && parsed > 0) ? parsed : fallback;
123using QueryItems = QList<QPair<QString, QString>>;
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) {
152auto unmodelledParams(
const QueryItems &items) -> QueryItems {
155 static const QStringList known = {
156 QStringLiteral(
"secret"), QStringLiteral(
"issuer"),
157 QStringLiteral(
"digits"), QStringLiteral(
"period"),
158 QStringLiteral(
"algorithm"), QStringLiteral(
"encoder")};
160 for (
const QPair<QString, QString> &item : items) {
161 if (!known.contains(item.first, Qt::CaseInsensitive)) {
176auto readOtpauthUri(
const QUrl &url,
const QString &trimmed,
181 if (url.host().compare(QStringLiteral(
"totp"), Qt::CaseInsensitive) != 0) {
182 return url.host().compare(QStringLiteral(
"hotp"), Qt::CaseInsensitive) == 0
187 const QUrlQuery query(url);
190 const QueryItems items = query.queryItems(QUrl::FullyDecoded);
191 const auto param = [&items](QLatin1StringView name) {
192 return firstParam(items, name);
194 rawSecret = param(QLatin1StringView(
"secret")).value_or(QString());
195 settings.issuer = param(QLatin1StringView(
"issuer")).value_or(QString());
199 if (url.hasFragment()) {
200 settings.fragment = trimmed.mid(trimmed.indexOf(QLatin1Char(
'#')) + 1);
203 settings.label = url.path();
204 if (settings.label.startsWith(QLatin1Char(
'/'))) {
205 settings.label.remove(0, 1);
212 parsePositiveUInt(param(QLatin1StringView(
"digits")).value_or(QString()),
215 parsePositiveUInt(param(QLatin1StringView(
"period")).value_or(QString()),
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()) {
226 settings.algorithm = *known;
228 if (param(QLatin1StringView(
"encoder"))
230 .compare(QStringLiteral(
"steam"), Qt::CaseInsensitive) == 0) {
233 settings.extraParams.append(unmodelledParams(items));
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');
265 -> std::optional<Settings> {
266 const auto refuse = [why](
Refusal reason) -> std::optional<Settings> {
267 if (why !=
nullptr) {
272 if (why !=
nullptr) {
281 const QString trimmed = config.trimmed();
282 if (trimmed.isEmpty()) {
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);
294 return refuse(unread);
296 }
else if (trimmed.startsWith(QStringLiteral(
"otpauth:"),
297 Qt::CaseInsensitive)) {
305 if (!isWrittenAsSecret(trimmed)) {
313 if (settings.
key.isEmpty()) {
316 settings.
base32Key = QString::fromLatin1(sanitized);
333 return QCoreApplication::translate(
"Totp",
334 "The OTP configuration is too long.");
337 return QCoreApplication::translate(
338 "Totp",
"This is a counter-based (HOTP) configuration. QtPass makes "
339 "time-based (TOTP) codes only.");
342 return QCoreApplication::translate(
343 "Totp",
"The algorithm in this otpauth:// link is not supported. "
344 "QtPass supports SHA1, SHA256 and SHA512.");
347 return QCoreApplication::translate(
"Totp",
348 "This otpauth:// link cannot be read.");
351 return QCoreApplication::translate(
352 "Totp",
"This is not a TOTP secret or an otpauth://totp/ link.");
355 return QCoreApplication::translate(
356 "Totp",
"The secret is missing or is not valid base32.");
365 return parse(config).has_value();
369 return unixTime / settings.step;
374 return settings.step -
static_cast<uint
>(unixTime % settings.step);
378 const quint64 bigEndianCounter = qToBigEndian(
counter(settings, unixTime));
379 const QByteArray message(
reinterpret_cast<const char *
>(&bigEndianCounter),
380 sizeof(bigEndianCounter));
382 const QByteArray hmac = QMessageAuthenticationCode::hash(
383 message, settings.key, cryptoHash(settings.algorithm));
384 if (hmac.size() < kMinHmacSize) {
392 static_cast<quint8
>(hmac.at(hmac.size() - 1)) & 0x0F;
393 const quint32 binary =
394 (
static_cast<quint32
>(
static_cast<quint8
>(hmac.at(offset)) & 0x7F)
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)));
402 quint64 value = binary;
406 code.append(QLatin1Char(kSteamAlphabet[value % kSteamAlphabetSize]));
407 value /= kSteamAlphabetSize;
415 for (uint i = 0; i < settings.digits; ++i) {
418 return QString::number(binary % modulus)
419 .rightJustified(
static_cast<int>(settings.digits), QLatin1Char(
'0'));
427 const QString label =
428 settings.label.isEmpty() ? QStringLiteral(
"QtPass") : settings.label;
432 const QString secret =
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));
441 QStringLiteral(
"&algorithm=%1").arg(algorithmName(settings.algorithm));
443 uri += QStringLiteral(
"&digits=%1&period=%2")
444 .arg(settings.digits)
447 uri += QStringLiteral(
"&encoder=steam");
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)));
456 if (!settings.fragment.isEmpty()) {
457 uri += QLatin1Char(
'#') + settings.fragment;
463 const QString &issuer) -> QString {
464 const std::optional<Settings> settings =
parse(config);
465 if (!settings.has_value()) {
469 if (canonical.
label.isEmpty()) {
470 canonical.
label = label;
472 if (canonical.
issuer.isEmpty()) {
473 canonical.
issuer = issuer;
477 QString uri =
toUri(canonical);
485 return static_cast<quint64
>(QDateTime::currentSecsSinceEpoch());
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.
static auto decode(const QByteArray &encodedData) -> QByteArray
Decode strict RFC 4648 base32 data.
static auto removePadding(const QByteArray &encodedData) -> QByteArray
Strip trailing '=' padding.
Algorithm
HMAC hash function, selected by the algorithm URI parameter.
@ Sha1
HMAC-SHA-1, the RFC 6238 default.
static constexpr uint MAX_STEP
static constexpr uint MIN_DIGITS
Lower clamp for digits.
static constexpr uint DEFAULT_STEP
RFC 6238 default period.
static auto counter(const Settings &settings, quint64 unixTime) -> quint64
Time-step counter for a point in time.
static auto generateNow(const Settings &settings) -> QString
Generate the code for the current wall-clock time.
static auto parse(const QString &config, Refusal *why=nullptr) -> std::optional< Settings >
Parse an OTP configuration string.
static constexpr uint DEFAULT_DIGITS
RFC 6238 default code length.
static constexpr qsizetype MAX_CONFIG_LENGTH
static constexpr uint STEAM_DIGITS
Steam codes are always 5 chars.
static auto currentUnixTime() -> quint64
Current wall-clock time.
static auto toUri(const Settings &settings) -> QString
Serialise settings as a canonical otpauth URI.
static auto normalize(const QString &config, const QString &label={}, const QString &issuer={}) -> QString
Normalise a user-entered value to a canonical otpauth URI.
static auto generate(const Settings &settings, quint64 unixTime) -> QString
Generate the code for a given point in time.
static auto describe(Refusal why) -> QString
One sentence for the user on why a configuration gives no code.
@ Steam
Steam Guard's five-character alphabet.
Refusal
Why parse() gave no settings, so the user can be told more than "invalid".
@ TooLong
Longer than MAX_CONFIG_LENGTH.
@ None
Parsed: there was nothing to refuse.
@ UnknownAlgorithm
An algorithm other than SHA-1, -256 or -512.
@ Hotp
An otpauth://hotp/ URI: counter-based.
@ NotASecret
Neither an otpauth URI nor written as a secret.
@ UnreadableUri
otpauth: but no URI QUrl reads, or no totp.
@ NoSecret
No secret, or one that is not valid base32.
@ Empty
Nothing but white space.
static constexpr uint MAX_DIGITS
Upper clamp for digits.
static auto isValid(const QString &config) -> bool
Convenience validity test, for UI feedback.
static auto secondsRemaining(const Settings &settings, quint64 unixTime) -> uint
Seconds until the code for unixTime expires.
Validated TOTP parameters. Only Totp::parse() produces one.
QString label
otpauth label; may be empty.
uint digits
Code length, MIN_DIGITS..MAX_DIGITS.
QByteArray key
Decoded shared secret; never empty.
QString base32Key
Sanitized base32 secret, for re-serialisation.
uint step
Period in seconds, 1..MAX_STEP.
Encoder encoder
Digit encoding.
RFC 6238 TOTP: otpauth URI parsing, code generation and canonical re-serialisation.