Merge branch 'release/2.2.2' into develop

This commit is contained in:
Janek Bevendorff 2017-10-21 22:23:27 +02:00
commit b510243dd8
No known key found for this signature in database
GPG Key ID: 2FDEB0D40BCA5E11
15 changed files with 498 additions and 153 deletions

View File

@ -34,6 +34,7 @@ fi
APP="$1"
LOWERAPP="$(echo "$APP" | tr '[:upper:]' '[:lower:]')"
VERSION="$2"
export ARCH=x86_64
mkdir -p $APP.AppDir
wget -q https://github.com/AppImage/AppImages/raw/master/functions.sh -O ./functions.sh
@ -44,6 +45,8 @@ if [ -d ./usr/lib/x86_64-linux-gnu ]; then
LIB_DIR=./usr/lib/x86_64-linux-gnu
elif [ -d ./usr/lib/i386-linux-gnu ]; then
LIB_DIR=./usr/lib/i386-linux-gnu
elif [ -d ./usr/lib64 ]; then
LIB_DIR=./usr/lib64
fi
cd $APP.AppDir
@ -53,7 +56,7 @@ rm -R ./usr/local
rmdir ./opt 2> /dev/null
# bundle Qt platform plugins and themes
QXCB_PLUGIN="$(find /usr/lib -name 'libqxcb.so' 2> /dev/null)"
QXCB_PLUGIN="$(find /usr/lib* -name 'libqxcb.so' 2> /dev/null)"
if [ "$QXCB_PLUGIN" == "" ]; then
QXCB_PLUGIN="$(find /opt/qt*/plugins -name 'libqxcb.so' 2> /dev/null)"
fi
@ -73,18 +76,22 @@ get_desktop
get_icon
cat << EOF > ./usr/bin/keepassxc_env
#!/usr/bin/env bash
#export QT_QPA_PLATFORMTHEME=gtk2
export LD_LIBRARY_PATH="..$(dirname ${QT_PLUGIN_PATH})/lib:\${LD_LIBRARY_PATH}"
export QT_PLUGIN_PATH="..${QT_PLUGIN_PATH}:\${KPXC_QT_PLUGIN_PATH}"
# unset XDG_DATA_DIRS to make tray icon work in Ubuntu Unity
# see https://github.com/probonopd/AppImageKit/issues/351
# see https://github.com/AppImage/AppImageKit/issues/351
unset XDG_DATA_DIRS
exec keepassxc "\$@"
if [ "\${1}" == "cli" ]; then
shift
exec keepassxc-cli "\$@"
else
exec keepassxc "\$@"
fi
EOF
chmod +x ./usr/bin/keepassxc_env
sed -i 's/Exec=keepassxc/Exec=keepassxc_env/' keepassxc.desktop
sed -i 's/Exec=keepassxc/Exec=keepassxc_env/' org.keepassxc.desktop
get_desktopintegration $LOWERAPP
GLIBC_NEEDED=$(glibc_needed)
@ -93,5 +100,5 @@ cd ..
generate_type2_appimage
mv ../out/*.AppImage ..
mv ../out/*.AppImage ../KeePassXC-${VERSION}-${ARCH}.AppImage
rmdir ../out > /dev/null 2>&1

View File

@ -14,50 +14,68 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
FROM ubuntu:14.04
FROM centos:7
RUN set -x \
&& apt-get update \
&& apt-get install --yes software-properties-common
&& curl "https://copr.fedorainfracloud.org/coprs/bugzy/keepassxc/repo/epel-7/bugzy-keepassxc-epel-7.repo" \
> /etc/yum.repos.d/bugzy-keepassxc-epel-7.repo
RUN set -x \
&& add-apt-repository ppa:george-edison55/cmake-3.x
ENV QT_PPA=qt591
ENV QT_VERSION=qt59
&& curl "https://copr.fedorainfracloud.org/coprs/sic/backports/repo/epel-7/sic-backports-epel-7.repo" \
> /etc/yum.repos.d/sic-backports-epel-7.repo
RUN set -x \
&& add-apt-repository --yes ppa:beineri/opt-${QT_PPA}-trusty
&& yum clean -y all \
&& yum upgrade -y
# build and runtime dependencies
RUN set -x \
&& apt-get update \
&& apt-get install --yes \
g++ \
&& yum install -y \
make \
automake \
gcc-c++ \
cmake \
libgcrypt20-dev \
${QT_VERSION}base \
${QT_VERSION}tools \
${QT_VERSION}x11extras \
libxi-dev \
libxtst-dev \
zlib1g-dev \
libyubikey-dev \
libykpers-1-dev \
xvfb \
wget \
file \
fuse \
python
libgcrypt16-devel \
qt5-qtbase-devel \
qt5-linguist \
qt5-qttools \
zlib-devel \
qt5-qtx11extras \
qt5-qtx11extras-devel \
libXi-devel \
libXtst-devel
# AppImage dependencies
RUN set -x \
&& apt-get install --yes mesa-common-dev
&& yum install -y \
wget \
fuse-libs
# build libyubikey
ENV YUBIKEY_VERSION=1.13
RUN set -x && yum install -y libusb-devel
RUN set -x \
&& wget "https://developers.yubico.com/yubico-c/Releases/libyubikey-${YUBIKEY_VERSION}.tar.gz" \
&& tar xf libyubikey-${YUBIKEY_VERSION}.tar.gz \
&& cd libyubikey-${YUBIKEY_VERSION} \
&& ./configure --prefix=/usr --libdir=/usr/lib64 \
&& make \
&& make install \
&& cd .. \
&& rm -Rf libyubikey-${YUBIKEY_VERSION}*
# build libykpers-1
ENV YKPERS_VERSION=1.18.0
RUN set -x \
&& wget "https://developers.yubico.com/yubikey-personalization/Releases/ykpers-${YKPERS_VERSION}.tar.gz" \
&& tar xf ykpers-${YKPERS_VERSION}.tar.gz \
&& cd ykpers-${YKPERS_VERSION} \
&& ./configure --prefix=/usr --libdir=/usr/lib64 \
&& make \
&& make install \
&& cd .. \
&& rm -Rf ykpers-${YKPERS_VERSION}*
VOLUME /keepassxc/src
VOLUME /keepassxc/out
WORKDIR /keepassxc
ENV CMAKE_PREFIX_PATH=/opt/${QT_VERSION}/lib/cmake
ENV LD_LIBRARY_PATH=/opt/${QT_VERSION}/lib
RUN set -x \
&& echo /opt/${QT_VERSION}/lib > /etc/ld.so.conf.d/${QT_VERSION}.conf

View File

@ -121,6 +121,8 @@ Sign previously compiled release packages
Options:
-f, --files Files to sign (required)
-g, --gpg-key GPG key used to sign the files (default: '${GPG_KEY}')
--signtool Specify the signtool executable (default: 'signtool')
--signtool-key Provide a key to be used with signtool (for Windows EXE)
-h, --help Show this help
EOF
fi
@ -663,6 +665,8 @@ build() {
# -----------------------------------------------------------------------
sign() {
SIGN_FILES=()
SIGNTOOL="signtool"
SIGNTOOL_KEY=""
while [ $# -ge 1 ]; do
local arg="$1"
@ -677,6 +681,14 @@ sign() {
GPG_KEY="$2"
shift ;;
--signtool)
SIGNTOOL="$2"
shift ;;
--signtool-key)
SIGNTOOL_KEY="$2"
shift ;;
-h|--help)
printUsage "sign"
exit ;;
@ -695,12 +707,29 @@ sign() {
exit 1
fi
if [[ -n "$SIGNTOOL_KEY" && ! -f "$SIGNTOOL_KEY" ]]; then
exitError "Signtool Key was not found!"
elif [[ -f "$SIGNTOOL_KEY" && ! -x $(command -v "${SIGNTOOL}") ]]; then
exitError "signtool program not found on PATH!"
fi
for f in "${SIGN_FILES[@]}"; do
if [ ! -f "$f" ]; then
exitError "File '${f}' does not exist!"
fi
logInfo "Signing file '${f}'..."
if [[ -n "$SIGNTOOL_KEY" && ${f: -4} == '.exe' ]]; then
logInfo "Signing file '${f}' using signtool...\n"
read -s -p "Signtool Key Password: " password
echo
"${SIGNTOOL}" sign -f "${SIGNTOOL_KEY}" -p ${password} -v -t http://timestamp.comodoca.com/authenticode ${f}
if [ 0 -ne $? ]; then
exitError "Signing failed!"
fi
fi
logInfo "Signing file '${f}' using release key..."
gpg --output "${f}.sig" --armor --local-user "$GPG_KEY" --detach-sig "$f"
if [ 0 -ne $? ]; then

View File

@ -12,5 +12,5 @@ Icon=keepassxc
Terminal=false
Type=Application
Version=1.0
Categories=Utility;Security;Qt
Categories=Utility;Security;Qt;
MimeType=application/x-keepass2;

View File

@ -68,9 +68,8 @@ set(keepassx_SOURCES
core/Uuid.cpp
core/Base32.h
core/Base32.cpp
core/Optional.h
cli/Utils.cpp
cli/Utils.h
cli/PasswordInput.cpp
cli/PasswordInput.h
crypto/Crypto.cpp
crypto/CryptoHash.cpp
crypto/Random.cpp

View File

@ -15,7 +15,11 @@
* 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
/* 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"
@ -36,17 +40,19 @@ 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)
QVariant Base32::decode(const QByteArray& encodedData)
{
if (encodedData.size() <= 0)
return Optional<QByteArray>("");
if (encodedData.size() <= 0) {
return QVariant::fromValue(QByteArray(""));
}
if (encodedData.size() % 8 != 0)
return Optional<QByteArray>();
if (encodedData.size() % 8 != 0) {
return QVariant();
}
int nPads = 0;
for (int i = -1; i > -7; --i) {
if ('=' == encodedData[encodedData.size()+i])
if ('=' == encodedData[encodedData.size() + i])
++nPads;
}
@ -75,10 +81,9 @@ Optional<QByteArray> Base32::decode(const QByteArray& encodedData)
specialOffset = 0;
}
Q_ASSERT(encodedData.size() > 0);
const int nQuantums = encodedData.size() / 8;
const int nBytes = (nQuantums - 1) * 5 + nSpecialBytes;
const int nQuanta = encodedData.size() / 8;
const int nBytes = nSpecialBytes > 0 ? (nQuanta - 1) * 5 + nSpecialBytes : nQuanta * 5;
QByteArray data(nBytes, Qt::Uninitialized);
@ -89,19 +94,19 @@ Optional<QByteArray> Base32::decode(const QByteArray& encodedData)
quint64 quantum = 0;
int nQuantumBytes = 5;
for (int n = 0; n < 8; n++) {
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 (ch >= ASCII_2 && ch <= ASCII_7) {
if (ASCII_2 <= ch && ch <= ASCII_7) {
ch -= ASCII_2;
ch += ALPH_POS_2;
} else {
if (ASCII_EQ == ch) {
if(i == encodedData.size()) {
if (i == encodedData.size()) {
// finished with special quantum
quantum >>= specialOffset;
nQuantumBytes = nSpecialBytes;
@ -109,7 +114,7 @@ Optional<QByteArray> Base32::decode(const QByteArray& encodedData)
continue;
} else {
// illegal character
return Optional<QByteArray>();
return QVariant();
}
}
}
@ -120,25 +125,29 @@ Optional<QByteArray> Base32::decode(const QByteArray& encodedData)
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;
for (int n = offset; n >= 0 && o < nBytes; n -= 8) {
data[o++] = static_cast<char>((quantum & mask) >> n);
mask >>= 8;
}
}
return Optional<QByteArray>(data);
Q_ASSERT(encodedData.size() == i);
Q_ASSERT(nBytes == o);
return QVariant::fromValue(data);
}
QByteArray Base32::encode(const QByteArray& data)
{
if (data.size() < 1)
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 nQuantums = nBits / 40 + (rBits > 0 ? 1 : 0);
QByteArray encodedData(nQuantums * 8, Qt::Uninitialized);
const int nQuanta = nBits / 40 + (rBits > 0 ? 1 : 0);
const int nBytes = nQuanta * 8;
QByteArray encodedData(nQuanta * 8, Qt::Uninitialized);
int i = 0;
int o = 0;
@ -200,11 +209,82 @@ QByteArray Base32::encode(const QByteArray& data)
}
// add pad characters
while (o < encodedData.size())
while (o < encodedData.size()) {
encodedData[o++] = '=';
}
}
Q_ASSERT(encodedData.size() == o);
Q_ASSERT(data.size() == i);
Q_ASSERT(nBytes == 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);
}

View File

@ -15,22 +15,28 @@
* 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
/* 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 <QtCore/qglobal.h>
#include <QByteArray>
#include <QVariant>
#include <QtCore/qglobal.h>
class Base32
{
public:
Base32() =default;
Q_REQUIRED_RESULT static Optional<QByteArray> decode(const QByteArray&);
Base32() = default;
Q_REQUIRED_RESULT static QVariant 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
#endif // BASE32_H

View File

@ -148,9 +148,10 @@ QByteArray SymmetricCipherGcrypt::process(const QByteArray& data, bool* ok)
if (error != 0) {
setErrorString(error);
*ok = false;
} else {
*ok = true;
}
*ok = true;
return result;
}

View File

@ -162,7 +162,10 @@ void DatabaseOpenWidget::enterKey(const QString& pw, const QString& keyFile)
void DatabaseOpenWidget::openDatabase()
{
KeePass2Reader reader;
CompositeKey masterKey = databaseKey();
QSharedPointer<CompositeKey> masterKey = databaseKey();
if (masterKey.isNull()) {
return;
}
QFile file(m_filename);
if (!file.open(QIODevice::ReadOnly)) {
@ -174,7 +177,7 @@ void DatabaseOpenWidget::openDatabase()
delete m_db;
}
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
m_db = reader.readDatabase(&file, masterKey);
m_db = reader.readDatabase(&file, *masterKey);
QApplication::restoreOverrideCursor();
if (m_db) {
@ -182,20 +185,19 @@ void DatabaseOpenWidget::openDatabase()
m_ui->messageWidget->animatedHide();
}
emit editFinished(true);
}
else {
m_ui->messageWidget->showMessage(tr("Unable to open the database.")
.append("\n").append(reader.errorString()), MessageWidget::Error);
} else {
m_ui->messageWidget->showMessage(tr("Unable to open the database.").append("\n").append(reader.errorString()),
MessageWidget::Error);
m_ui->editPassword->clear();
}
}
CompositeKey DatabaseOpenWidget::databaseKey()
QSharedPointer<CompositeKey> DatabaseOpenWidget::databaseKey()
{
CompositeKey masterKey;
auto masterKey = QSharedPointer<CompositeKey>::create();
if (m_ui->checkPassword->isChecked()) {
masterKey.addKey(PasswordKey(m_ui->editPassword->text()));
masterKey->addKey(PasswordKey(m_ui->editPassword->text()));
}
QHash<QString, QVariant> lastKeyFiles = config()->get("LastKeyFiles").toHash();
@ -206,11 +208,11 @@ CompositeKey DatabaseOpenWidget::databaseKey()
QString keyFilename = m_ui->comboKeyFile->currentText();
QString errorMsg;
if (!key.load(keyFilename, &errorMsg)) {
m_ui->messageWidget->showMessage(tr("Can't open key file").append(":\n")
.append(errorMsg), MessageWidget::Error);
return CompositeKey();
m_ui->messageWidget->showMessage(tr("Can't open key file").append(":\n").append(errorMsg),
MessageWidget::Error);
return QSharedPointer<CompositeKey>();
}
masterKey.addKey(key);
masterKey->addKey(key);
lastKeyFiles[m_filename] = keyFilename;
} else {
lastKeyFiles.remove(m_filename);
@ -239,7 +241,7 @@ CompositeKey DatabaseOpenWidget::databaseKey()
bool blocking = comboPayload & 1;
int slot = comboPayload >> 1;
auto key = QSharedPointer<YkChallengeResponseKey>(new YkChallengeResponseKey(slot, blocking));
masterKey.addChallengeResponseKey(key);
masterKey->addChallengeResponseKey(key);
}
#endif

View File

@ -52,7 +52,7 @@ signals:
protected:
void showEvent(QShowEvent* event) override;
void hideEvent(QHideEvent* event) override;
CompositeKey databaseKey();
QSharedPointer<CompositeKey> databaseKey();
protected slots:
virtual void openDatabase();

View File

@ -18,15 +18,15 @@
#include "totp.h"
#include "core/Base32.h"
#include <cmath>
#include <QtEndian>
#include <QRegExp>
#include <QDateTime>
#include <QCryptographicHash>
#include <QDateTime>
#include <QMessageAuthenticationCode>
#include <QRegExp>
#include <QUrl>
#include <QUrlQuery>
#include <QVariant>
#include <QtEndian>
#include <cmath>
const quint8 QTotp::defaultStep = 30;
const quint8 QTotp::defaultDigits = 6;
@ -35,7 +35,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 +58,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 +92,59 @@ 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);
Optional<QByteArray> secret = Base32::decode(key);
if (!secret.hasValue()) {
QVariant secret = Base32::decode(Base32::sanitizeInput(key));
if (secret.isNull()) {
return "Invalid TOTP secret key";
}
QMessageAuthenticationCode code(QCryptographicHash::Sha1);
code.setKey(secret.valueOr(""));
code.setKey(secret.toByteArray());
code.addData(QByteArray(reinterpret_cast<char*>(&current), sizeof(current)));
QByteArray hmac = code.result();
int offset = (hmac[hmac.length() - 1] & 0xf);
// clang-format off
int binary =
((hmac[offset] & 0x7f) << 24)
| ((hmac[offset + 1] & 0xff) << 16)
| ((hmac[offset + 2] & 0xff) << 8)
| (hmac[offset + 3] & 0xff);
// clang-format on
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;
};

View File

@ -23,88 +23,136 @@ QTEST_GUILESS_MAIN(TestBase32)
void TestBase32::testDecode()
{
// 3 quantums, all upper case + padding
// 3 quanta, all upper case + padding
QByteArray encodedData = "JBSWY3DPEB3W64TMMQXC4LQ=";
auto data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("Hello world..."));
QVariant data = Base32::decode(encodedData);
QString expectedData = "Hello world...";
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
// 4 quantums, all upper case
// 4 quanta, all upper case
encodedData = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("12345678901234567890"));
expectedData = "12345678901234567890";
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
// 4 quantums, all lower case
// 4 quanta, all lower case
encodedData = "gezdgnbvgy3tqojqgezdgnbvgy3tqojq";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("12345678901234567890"));
expectedData = "12345678901234567890";
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
// 4 quantums, mixed upper and lower case
// 4 quanta, mixed upper and lower case
encodedData = "Gezdgnbvgy3tQojqgezdGnbvgy3tQojQ";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("12345678901234567890"));
expectedData = "12345678901234567890";
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
// 1 pad characters
encodedData = "ORSXG5A=";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("test"));
expectedData = "test";
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
// 3 pad characters
encodedData = "L5PV6===";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("___"));
expectedData = "___";
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
// 4 pad characters
encodedData = "MZXW6IDCMFZA====";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("foo bar"));
expectedData = "foo bar";
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
// six pad characters
encodedData = "MZXW6YTBOI======";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("foobar"));
expectedData = "foobar";
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
encodedData = "IA======";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("@"));
expectedData = "@";
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
// error: illegal character
encodedData = "1MZXW6YTBOI=====";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("ERROR"));
QVERIFY(data.isNull());
// error: missing pad character
encodedData = "MZXW6YTBOI=====";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("ERROR"));
QVERIFY(data.isNull());
// RFC 4648 test vectors
encodedData = "";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString(""));
expectedData = "";
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
encodedData = "MY======";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("f"));
expectedData = "f";
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
encodedData = "MZXQ====";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("fo"));
expectedData = "fo";
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
encodedData = "MZXW6===";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("foo"));
QVERIFY(!data.isNull());
expectedData = "foo";
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
encodedData = "MZXW6YQ=";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("foob"));
expectedData = "foob";
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
encodedData = "MZXW6YTB";
expectedData = "fooba";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("fooba"));
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
encodedData = "MZXW6YTBOI======";
data = Base32::decode(encodedData);
QCOMPARE(QString::fromLatin1(data.valueOr("ERROR")), QString("foobar"));
expectedData = "foobar";
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), expectedData);
QVERIFY(data.value<QByteArray>().size() == expectedData.size());
}
void TestBase32::testEncode()
@ -166,3 +214,117 @@ void TestBase32::testEncode()
encodedData = Base32::encode(data);
QCOMPARE(encodedData, QByteArray("MZXW6YTBOI======"));
}
void TestBase32::testAddPadding()
{
// Empty. Invalid, returns input.
QByteArray data = "";
QByteArray paddedData = Base32::addPadding(data);
QCOMPARE(paddedData, data);
// One byte of encoded data. Invalid, returns input.
data = "B";
paddedData = Base32::addPadding(data);
QCOMPARE(paddedData, data);
// Two bytes of encoded data.
data = "BB";
paddedData = Base32::addPadding(data);
QCOMPARE(paddedData, QByteArray("BB======"));
// Three bytes of encoded data. Invalid, returns input.
data = "BBB";
paddedData = Base32::addPadding(data);
QCOMPARE(paddedData, data);
// Four bytes of encoded data.
data = "BBBB";
paddedData = Base32::addPadding(data);
QCOMPARE(paddedData, QByteArray("BBBB===="));
// Five bytes of encoded data.
data = "BBBBB";
paddedData = Base32::addPadding(data);
QCOMPARE(paddedData, QByteArray("BBBBB==="));
// Six bytes of encoded data. Invalid, returns input.
data = "BBBBBB";
paddedData = Base32::addPadding(data);
QCOMPARE(paddedData, data);
// Seven bytes of encoded data.
data = "BBBBBBB";
paddedData = Base32::addPadding(data);
QCOMPARE(paddedData, QByteArray("BBBBBBB="));
// Eight bytes of encoded data. Valid, but returns same as input.
data = "BBBBBBBB";
paddedData = Base32::addPadding(data);
QCOMPARE(paddedData, data);
// More than eight bytes (8+5).
data = "AAAAAAAABBBBB";
paddedData = Base32::addPadding(data);
QCOMPARE(paddedData, QByteArray("AAAAAAAABBBBB==="));
}
void TestBase32::testRemovePadding()
{
QByteArray data = "";
QByteArray unpaddedData = Base32::removePadding(data);
QCOMPARE(unpaddedData, data);
data = "AAAAAAAABB======";
unpaddedData = Base32::removePadding(data);
QCOMPARE(unpaddedData, QByteArray("AAAAAAAABB"));
data = "BBBB====";
unpaddedData = Base32::removePadding(data);
QCOMPARE(unpaddedData, QByteArray("BBBB"));
data = "AAAAAAAABBBBB===";
unpaddedData = Base32::removePadding(data);
QCOMPARE(unpaddedData, QByteArray("AAAAAAAABBBBB"));
data = "BBBBBBB=";
unpaddedData = Base32::removePadding(data);
QCOMPARE(unpaddedData, QByteArray("BBBBBBB"));
// Invalid: 7 bytes of data. Returns same as input.
data = "IIIIIII";
unpaddedData = Base32::removePadding(data);
QCOMPARE(unpaddedData, data);
// Invalid: more padding than necessary. Returns same as input.
data = "AAAAAAAABBBB=====";
unpaddedData = Base32::removePadding(data);
QCOMPARE(unpaddedData, data);
}
void TestBase32::testSanitizeInput()
{
// sanitize input (white space + missing padding)
QByteArray encodedData = "JBSW Y3DP EB3W 64TM MQXC 4LQA";
auto data = Base32::decode(Base32::sanitizeInput(encodedData));
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), QString("Hello world..."));
// sanitize input (typo + missing padding)
encodedData = "J8SWY3DPE83W64TMMQXC4LQA";
data = Base32::decode(Base32::sanitizeInput(encodedData));
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), QString("Hello world..."));
// sanitize input (other illegal characters)
encodedData = "J8SWY3D[PE83W64TMMQ]XC!4LQA";
data = Base32::decode(Base32::sanitizeInput(encodedData));
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), QString("Hello world..."));
// sanitize input (NUL character)
encodedData = "J8SWY3DPE83W64TMMQXC4LQA";
encodedData.insert(3, '\0');
data = Base32::decode(Base32::sanitizeInput(encodedData));
QVERIFY(!data.isNull());
QCOMPARE(data.toString(), QString("Hello world..."));
}

View File

@ -29,6 +29,9 @@ class TestBase32 : public QObject
private slots:
void testEncode();
void testDecode();
void testAddPadding();
void testRemovePadding();
void testSanitizeInput();
};
#endif // KEEPASSX_TESTBASE32_H

View File

@ -18,11 +18,11 @@
#include "TestTotp.h"
#include <QTest>
#include <QTime>
#include <QDateTime>
#include <QtEndian>
#include <QTest>
#include <QTextCodec>
#include <QTime>
#include <QtEndian>
#include "crypto/Crypto.h"
#include "totp/totp.h"
@ -34,12 +34,13 @@ void TestTotp::initTestCase()
QVERIFY(Crypto::init());
}
void TestTotp::testParseSecret()
{
quint8 digits = 0;
quint8 step = 0;
QString secret = "otpauth://totp/ACME%20Co:john@example.com?secret=HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ&issuer=ACME%20Co&algorithm=SHA1&digits=6&period=30";
QString secret = "otpauth://totp/"
"ACME%20Co:john@example.com?secret=HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ&issuer=ACME%20Co&algorithm="
"SHA1&digits=6&period=30";
QCOMPARE(QTotp::parseOtpString(secret, digits, step), QString("HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ"));
QCOMPARE(digits, quint8(6));
QCOMPARE(step, quint8(30));