Add new Base32 implementation

This commit is contained in:
Adolfo E. García 2017-10-14 22:54:20 -06:00 committed by Janek Bevendorff
parent 85f652290b
commit 19eb6a8a60
15 changed files with 789 additions and 359 deletions

View file

@ -59,6 +59,9 @@ set(keepassx_SOURCES
core/Tools.cpp
core/Translator.cpp
core/Uuid.cpp
core/Base32.h
core/Base32.cpp
core/Optional.h
cli/PasswordInput.cpp
cli/PasswordInput.h
crypto/Crypto.cpp
@ -138,8 +141,6 @@ set(keepassx_SOURCES
streams/qtiocompressor.cpp
streams/StoreDataStream.cpp
streams/SymmetricCipherStream.cpp
totp/base32.h
totp/base32.cpp
totp/totp.h
totp/totp.cpp
)

285
src/core/Base32.cpp Normal file
View file

@ -0,0 +1,285 @@
/*
* Copyright (C) 2017 KeePassXC Team <team@keepassxc.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 or (at your option)
* version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Conforms to RFC 4648. For details, see: https://tools.ietf.org/html/rfc4648
* Use the functions Base32::addPadding/1, Base32::removePadding/1 or
* Base32::sanitizeInput/1 to fix input or output for a particular
* applications (e.g. to use with Google Authenticator).
*/
#include "Base32.h"
constexpr quint64 MASK_40BIT = quint64(0xF8) << 32;
constexpr quint64 MASK_35BIT = quint64(0x7C0000000);
constexpr quint64 MASK_25BIT = quint64(0x1F00000);
constexpr quint64 MASK_20BIT = quint64(0xF8000);
constexpr quint64 MASK_10BIT = quint64(0x3E0);
constexpr char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
constexpr quint8 ALPH_POS_2 = 26;
constexpr quint8 ASCII_2 = static_cast<quint8>('2');
constexpr quint8 ASCII_7 = static_cast<quint8>('7');
constexpr quint8 ASCII_A = static_cast<quint8>('A');
constexpr quint8 ASCII_Z = static_cast<quint8>('Z');
constexpr quint8 ASCII_a = static_cast<quint8>('a');
constexpr quint8 ASCII_z = static_cast<quint8>('z');
constexpr quint8 ASCII_EQ = static_cast<quint8>('=');
Optional<QByteArray> Base32::decode(const QByteArray& encodedData)
{
if (encodedData.size() <= 0) {
return Optional<QByteArray>("");
}
if (encodedData.size() % 8 != 0) {
return Optional<QByteArray>();
}
int nPads = 0;
for (int i = -1; i > -7; --i) {
if ('=' == encodedData[encodedData.size() + i])
++nPads;
}
int specialOffset;
int nSpecialBytes;
switch (nPads) { // in {0, 1, 3, 4, 6}
case 1:
nSpecialBytes = 4;
specialOffset = 3;
break;
case 3:
nSpecialBytes = 3;
specialOffset = 1;
break;
case 4:
nSpecialBytes = 2;
specialOffset = 4;
break;
case 6:
nSpecialBytes = 1;
specialOffset = 2;
break;
default:
nSpecialBytes = 0;
specialOffset = 0;
}
Q_ASSERT(encodedData.size() > 0);
const int nQuanta = encodedData.size() / 8;
const int nBytes = (nQuanta - 1) * 5 + nSpecialBytes;
QByteArray data(nBytes, Qt::Uninitialized);
int i = 0;
int o = 0;
while (i < encodedData.size()) {
quint64 quantum = 0;
int nQuantumBytes = 5;
for (int n = 0; n < 8; n++) {
quint8 ch = static_cast<quint8>(encodedData[i++]);
if ((ASCII_A <= ch && ch <= ASCII_Z) || (ASCII_a <= ch && ch <= ASCII_z)) {
ch -= ASCII_A;
if (ch >= ALPH_POS_2)
ch -= ASCII_a - ASCII_A;
} else {
if (ASCII_2 <= ch && ch <= ASCII_7) {
ch -= ASCII_2;
ch += ALPH_POS_2;
} else {
if (ASCII_EQ == ch) {
if (i == encodedData.size()) {
// finished with special quantum
quantum >>= specialOffset;
nQuantumBytes = nSpecialBytes;
}
continue;
} else {
// illegal character
return Optional<QByteArray>();
}
}
}
quantum <<= 5;
quantum |= ch;
}
const int offset = (nQuantumBytes - 1) * 8;
quint64 mask = quint64(0xFF) << offset;
for (int n = offset; n >= 0; n -= 8) {
char c = static_cast<char>((quantum & mask) >> n);
data[o++] = c;
mask >>= 8;
}
}
return Optional<QByteArray>(data);
}
QByteArray Base32::encode(const QByteArray& data)
{
if (data.size() < 1) {
return QByteArray();
}
const int nBits = data.size() * 8;
const int rBits = nBits % 40; // in {0, 8, 16, 24, 32}
const int nQuanta = nBits / 40 + (rBits > 0 ? 1 : 0);
QByteArray encodedData(nQuanta * 8, Qt::Uninitialized);
int i = 0;
int o = 0;
int n;
quint64 mask;
quint64 quantum;
// 40-bits of input per input group
while (i + 5 <= data.size()) {
quantum = 0;
for (n = 32; n >= 0; n -= 8) {
quantum |= (static_cast<quint64>(data[i++]) << n);
}
mask = MASK_40BIT;
int index;
for (n = 35; n >= 0; n -= 5) {
index = (quantum & mask) >> n;
encodedData[o++] = alphabet[index];
mask >>= 5;
}
}
// < 40-bits of input at final input group
if (i < data.size()) {
Q_ASSERT(rBits > 0);
quantum = 0;
for (n = rBits - 8; n >= 0; n -= 8)
quantum |= static_cast<quint64>(data[i++]) << n;
switch (rBits) {
case 8: // expand to 10 bits
quantum <<= 2;
mask = MASK_10BIT;
n = 5;
break;
case 16: // expand to 20 bits
quantum <<= 4;
mask = MASK_20BIT;
n = 15;
break;
case 24: // expand to 25 bits
quantum <<= 1;
mask = MASK_25BIT;
n = 20;
break;
default: // expand to 35 bits
Q_ASSERT(rBits == 32);
quantum <<= 3;
mask = MASK_35BIT;
n = 30;
}
while (n >= 0) {
int index = (quantum & mask) >> n;
encodedData[o++] = alphabet[index];
mask >>= 5;
n -= 5;
}
// add pad characters
while (o < encodedData.size())
encodedData[o++] = '=';
}
Q_ASSERT(encodedData.size() == o);
return encodedData;
}
QByteArray Base32::addPadding(const QByteArray& encodedData)
{
if (encodedData.size() <= 0 || encodedData.size() % 8 == 0) {
return encodedData;
}
const int rBytes = encodedData.size() % 8;
// rBytes must be a member of {2, 4, 5, 7}
if (1 == rBytes || 3 == rBytes || 6 == rBytes) {
return encodedData;
}
QByteArray newEncodedData(encodedData);
for (int nPads = 8 - rBytes; nPads > 0; --nPads) {
newEncodedData.append('=');
}
return newEncodedData;
}
QByteArray Base32::removePadding(const QByteArray& encodedData)
{
if (encodedData.size() <= 0 || encodedData.size() % 8 != 0) {
return encodedData; // return same bad input
}
int nPads = 0;
for (int i = -1; i > -7; --i) {
if ('=' == encodedData[encodedData.size() + i]) {
++nPads;
}
}
QByteArray newEncodedData(encodedData);
newEncodedData.remove(encodedData.size() - nPads, nPads);
newEncodedData.resize(encodedData.size() - nPads);
return newEncodedData;
}
QByteArray Base32::sanitizeInput(const QByteArray& encodedData)
{
if (encodedData.size() <= 0) {
return encodedData;
}
QByteArray newEncodedData(encodedData.size(), Qt::Uninitialized);
int i = 0;
for (auto ch : encodedData) {
switch (ch) {
case '0':
newEncodedData[i++] = 'O';
break;
case '1':
newEncodedData[i++] = 'L';
break;
case '8':
newEncodedData[i++] = 'B';
break;
default:
if (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z') || ('2' <= ch && ch <= '7')) {
newEncodedData[i++] = ch;
}
}
}
newEncodedData.resize(i);
return addPadding(newEncodedData);
}

42
src/core/Base32.h Normal file
View file

@ -0,0 +1,42 @@
/*
* Copyright (C) 2017 KeePassXC Team <team@keepassxc.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 or (at your option)
* version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Conforms to RFC 4648. For details, see: https://tools.ietf.org/html/rfc4648
* Use the functions Base32::addPadding/1, Base32::removePadding/1 or
* Base32::sanitizeInput/1 to fix input or output for a particular
* applications (e.g. to use with Google Authenticator).
*/
#ifndef BASE32_H
#define BASE32_H
#include "Optional.h"
#include <QByteArray>
#include <QtCore/qglobal.h>
class Base32
{
public:
Base32() = default;
Q_REQUIRED_RESULT static Optional<QByteArray> decode(const QByteArray&);
Q_REQUIRED_RESULT static QByteArray encode(const QByteArray&);
Q_REQUIRED_RESULT static QByteArray addPadding(const QByteArray&);
Q_REQUIRED_RESULT static QByteArray removePadding(const QByteArray&);
Q_REQUIRED_RESULT static QByteArray sanitizeInput(const QByteArray&);
};
#endif // BASE32_H

86
src/core/Optional.h Normal file
View file

@ -0,0 +1,86 @@
/*
* Copyright (C) 2017 KeePassXC Team <team@keepassxc.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 or (at your option)
* version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPTIONAL_H
#define OPTIONAL_H
/*
* This utility class is for providing basic support for an option type.
* It can be replaced by std::optional (C++17) or
* std::experimental::optional (C++11) when they become fully supported
* by all the main compiler toolchains.
*/
template <typename T> class Optional
{
public:
// None
Optional()
: m_hasValue(false)
, m_value(){};
// Some T
Optional(const T& value)
: m_hasValue(true)
, m_value(value){};
// Copy
Optional(const Optional& other)
: m_hasValue(other.m_hasValue)
, m_value(other.m_value){};
const Optional& operator=(const Optional& other)
{
m_hasValue = other.m_hasValue;
m_value = other.m_value;
return *this;
}
bool operator==(const Optional& other) const
{
if (m_hasValue)
return other.m_hasValue && m_value == other.m_value;
else
return !other.m_hasValue;
}
bool operator!=(const Optional& other) const
{
return !(*this == other);
}
bool hasValue() const
{
return m_hasValue;
}
T valueOr(const T& other) const
{
return m_hasValue ? m_value : other;
}
Optional static makeOptional(const T& value)
{
return Optional(value);
}
private:
bool m_hasValue;
T m_value;
};
#endif // OPTIONAL_H

View file

@ -1,68 +0,0 @@
// Base32 implementation
// Source: https://github.com/google/google-authenticator-libpam/blob/master/src/base32.c
//
// Copyright 2010 Google Inc.
// Author: Markus Gutschke
// Modifications Copyright 2017 KeePassXC team <team@keepassxc.org>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "base32.h"
Base32::Base32()
{
}
QByteArray Base32::base32_decode(const QByteArray encoded)
{
QByteArray result;
int buffer = 0;
int bitsLeft = 0;
for (char ch : encoded) {
if (ch == 0 || ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-' || ch == '=') {
continue;
}
buffer <<= 5;
// Deal with commonly mistyped characters
if (ch == '0') {
ch = 'O';
} else if (ch == '1') {
ch = 'L';
} else if (ch == '8') {
ch = 'B';
}
// Look up one base32 digit
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
ch = (ch & 0x1F) - 1;
} else if (ch >= '2' && ch <= '7') {
ch -= '2' - 26;
} else {
return QByteArray();
}
buffer |= ch;
bitsLeft += 5;
if (bitsLeft >= 8) {
result.append(static_cast<char> (buffer >> (bitsLeft - 8)));
bitsLeft -= 8;
}
}
return result;
}

View file

@ -1,34 +0,0 @@
// Base32 implementation
// Source: https://github.com/google/google-authenticator-libpam/blob/master/src/base32.h
//
// Copyright 2010 Google Inc.
// Author: Markus Gutschke
// Modifications Copyright 2017 KeePassXC team <team@keepassxc.org>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef BASE32_H
#define BASE32_H
#include <QtCore/qglobal.h>
#include <QByteArray>
class Base32
{
public:
Base32();
static QByteArray base32_decode(const QByteArray encoded);
};
#endif //BASE32_H

View file

@ -17,16 +17,15 @@
*/
#include "totp.h"
#include "base32.h"
#include <cmath>
#include <QtEndian>
#include <QRegExp>
#include <QDateTime>
#include "core/Base32.h"
#include <QCryptographicHash>
#include <QDateTime>
#include <QMessageAuthenticationCode>
#include <QRegExp>
#include <QUrl>
#include <QUrlQuery>
#include <QtEndian>
#include <cmath>
const quint8 QTotp::defaultStep = 30;
const quint8 QTotp::defaultDigits = 6;
@ -35,7 +34,7 @@ QTotp::QTotp()
{
}
QString QTotp::parseOtpString(QString key, quint8 &digits, quint8 &step)
QString QTotp::parseOtpString(QString key, quint8& digits, quint8& step)
{
QUrl url(key);
@ -58,7 +57,6 @@ QString QTotp::parseOtpString(QString key, quint8 &digits, quint8 &step)
step = q_step;
}
} else {
// Compatibility with "KeeOtp" plugin string format
QRegExp rx("key=(.+)", Qt::CaseInsensitive, QRegExp::RegExp);
@ -93,30 +91,53 @@ QString QTotp::parseOtpString(QString key, quint8 &digits, quint8 &step)
return seed;
}
QString QTotp::generateTotp(const QByteArray key, quint64 time,
const quint8 numDigits = defaultDigits, const quint8 step = defaultStep)
QString QTotp::generateTotp(const QByteArray key,
quint64 time,
const quint8 numDigits = defaultDigits,
const quint8 step = defaultStep)
{
quint64 current = qToBigEndian(time / step);
QByteArray secret = Base32::base32_decode(key);
if (secret.isEmpty()) {
Optional<QByteArray> secret = Base32::decode(Base32::sanitizeInput(key));
if (!secret.hasValue()) {
return "Invalid TOTP secret key";
}
QMessageAuthenticationCode code(QCryptographicHash::Sha1);
code.setKey(secret);
code.setKey(secret.valueOr(""));
code.addData(QByteArray(reinterpret_cast<char*>(&current), sizeof(current)));
QByteArray hmac = code.result();
int offset = (hmac[hmac.length() - 1] & 0xf);
int binary =
((hmac[offset] & 0x7f) << 24)
| ((hmac[offset + 1] & 0xff) << 16)
| ((hmac[offset + 2] & 0xff) << 8)
| (hmac[offset + 3] & 0xff);
int binary = ((hmac[offset] & 0x7f) << 24) | ((hmac[offset + 1] & 0xff) << 16) | ((hmac[offset + 2] & 0xff) << 8) |
(hmac[offset + 3] & 0xff);
quint32 digitsPower = pow(10, numDigits);
quint64 password = binary % digitsPower;
return QString("%1").arg(password, numDigits, 10, QChar('0'));
}
// See: https://github.com/google/google-authenticator/wiki/Key-Uri-Format
QUrl QTotp::generateOtpString(const QString& secret,
const QString& type,
const QString& issuer,
const QString& username,
const QString& algorithm,
const quint8& digits,
const quint8& step)
{
QUrl keyUri;
keyUri.setScheme("otpauth");
keyUri.setHost(type);
keyUri.setPath(QString("/%1:%2").arg(issuer).arg(username));
QUrlQuery parameters;
parameters.addQueryItem("secret", secret);
parameters.addQueryItem("issuer", issuer);
parameters.addQueryItem("algorithm", algorithm);
parameters.addQueryItem("digits", QString::number(digits));
parameters.addQueryItem("period", QString::number(step));
keyUri.setQuery(parameters);
return keyUri;
}

View file

@ -21,12 +21,21 @@
#include <QtCore/qglobal.h>
class QUrl;
class QTotp
{
public:
QTotp();
static QString parseOtpString(QString rawSecret, quint8 &digits, quint8 &step);
static QString parseOtpString(QString rawSecret, quint8& digits, quint8& step);
static QString generateTotp(const QByteArray key, quint64 time, const quint8 numDigits, const quint8 step);
static QUrl generateOtpString(const QString& secret,
const QString& type,
const QString& issuer,
const QString& username,
const QString& algorithm,
const quint8& digits,
const quint8& step);
static const quint8 defaultStep;
static const quint8 defaultDigits;
};