diff --git a/AppImage-Recipe.sh b/AppImage-Recipe.sh index 16024d22..cdf66470 100755 --- a/AppImage-Recipe.sh +++ b/AppImage-Recipe.sh @@ -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 diff --git a/Dockerfile b/Dockerfile index 60ba4ff5..6f7ace34 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,50 +14,68 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -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 diff --git a/release-tool b/release-tool index a1d23b40..10c6a14c 100755 --- a/release-tool +++ b/release-tool @@ -119,9 +119,11 @@ EOF 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}') - -h, --help Show this help + -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 } @@ -546,10 +548,10 @@ build() { checkWorkingTreeClean OUTPUT_DIR="$(realpath "$OUTPUT_DIR")" - + logInfo "Checking out release tag '${TAG_NAME}'..." git checkout "$TAG_NAME" - + logInfo "Creating output directory..." mkdir -p "$OUTPUT_DIR" @@ -663,6 +665,8 @@ build() { # ----------------------------------------------------------------------- sign() { SIGN_FILES=() + SIGNTOOL="signtool" + SIGNTOOL_KEY="" while [ $# -ge 1 ]; do local arg="$1" @@ -676,6 +680,14 @@ sign() { -g|--gpg-key) GPG_KEY="$2" shift ;; + + --signtool) + SIGNTOOL="$2" + shift ;; + + --signtool-key) + SIGNTOOL_KEY="$2" + shift ;; -h|--help) printUsage "sign" @@ -694,13 +706,30 @@ sign() { printUsage "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 + + 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}'..." + logInfo "Signing file '${f}' using release key..." gpg --output "${f}.sig" --armor --local-user "$GPG_KEY" --detach-sig "$f" if [ 0 -ne $? ]; then diff --git a/share/linux/org.keepassxc.desktop b/share/linux/org.keepassxc.desktop index fd94fdcd..d3b007bd 100644 --- a/share/linux/org.keepassxc.desktop +++ b/share/linux/org.keepassxc.desktop @@ -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; diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 3d5e7bf4..cd256511 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -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 diff --git a/src/core/Base32.cpp b/src/core/Base32.cpp index a58f2e42..13228a37 100644 --- a/src/core/Base32.cpp +++ b/src/core/Base32.cpp @@ -15,7 +15,11 @@ * along with this program. If not, see . */ -// 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('a'); constexpr quint8 ASCII_z = static_cast('z'); constexpr quint8 ASCII_EQ = static_cast('='); -Optional Base32::decode(const QByteArray& encodedData) +QVariant Base32::decode(const QByteArray& encodedData) { - if (encodedData.size() <= 0) - return Optional(""); + if (encodedData.size() <= 0) { + return QVariant::fromValue(QByteArray("")); + } - if (encodedData.size() % 8 != 0) - return Optional(); + 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 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 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(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 Base32::decode(const QByteArray& encodedData) continue; } else { // illegal character - return Optional(); + return QVariant(); } } } @@ -120,26 +125,30 @@ Optional 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((quantum & mask) >> n); - data[o++] = c; - mask >>= 8; + for (int n = offset; n >= 0 && o < nBytes; n -= 8) { + data[o++] = static_cast((quantum & mask) >> n); + mask >>= 8; } } - return Optional(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; int n; @@ -170,7 +179,7 @@ QByteArray Base32::encode(const QByteArray& data) quantum |= static_cast(data[i++]) << n; switch (rBits) { - case 8: // expand to 10 bits + case 8: // expand to 10 bits quantum <<= 2; mask = MASK_10BIT; n = 5; @@ -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); +} diff --git a/src/core/Base32.h b/src/core/Base32.h index 701eb7ab..204368c5 100644 --- a/src/core/Base32.h +++ b/src/core/Base32.h @@ -15,22 +15,28 @@ * along with this program. If not, see . */ -// 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 #include +#include +#include class Base32 { public: - Base32() =default; - Q_REQUIRED_RESULT static Optional 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 diff --git a/src/crypto/SymmetricCipherGcrypt.cpp b/src/crypto/SymmetricCipherGcrypt.cpp index cd432406..e600a7ed 100644 --- a/src/crypto/SymmetricCipherGcrypt.cpp +++ b/src/crypto/SymmetricCipherGcrypt.cpp @@ -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; } diff --git a/src/gui/DatabaseOpenWidget.cpp b/src/gui/DatabaseOpenWidget.cpp index b8f8feb1..ee0e9de2 100644 --- a/src/gui/DatabaseOpenWidget.cpp +++ b/src/gui/DatabaseOpenWidget.cpp @@ -162,7 +162,10 @@ void DatabaseOpenWidget::enterKey(const QString& pw, const QString& keyFile) void DatabaseOpenWidget::openDatabase() { KeePass2Reader reader; - CompositeKey masterKey = databaseKey(); + QSharedPointer 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 DatabaseOpenWidget::databaseKey() { - CompositeKey masterKey; + auto masterKey = QSharedPointer::create(); if (m_ui->checkPassword->isChecked()) { - masterKey.addKey(PasswordKey(m_ui->editPassword->text())); + masterKey->addKey(PasswordKey(m_ui->editPassword->text())); } QHash 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(); } - masterKey.addKey(key); + masterKey->addKey(key); lastKeyFiles[m_filename] = keyFilename; } else { lastKeyFiles.remove(m_filename); @@ -237,9 +239,9 @@ CompositeKey DatabaseOpenWidget::databaseKey() // read blocking mode from LSB and slot index number from second LSB bool blocking = comboPayload & 1; - int slot = comboPayload >> 1; - auto key = QSharedPointer(new YkChallengeResponseKey(slot, blocking)); - masterKey.addChallengeResponseKey(key); + int slot = comboPayload >> 1; + auto key = QSharedPointer(new YkChallengeResponseKey(slot, blocking)); + masterKey->addChallengeResponseKey(key); } #endif diff --git a/src/gui/DatabaseOpenWidget.h b/src/gui/DatabaseOpenWidget.h index d4b47364..a7691a91 100644 --- a/src/gui/DatabaseOpenWidget.h +++ b/src/gui/DatabaseOpenWidget.h @@ -52,7 +52,7 @@ signals: protected: void showEvent(QShowEvent* event) override; void hideEvent(QHideEvent* event) override; - CompositeKey databaseKey(); + QSharedPointer databaseKey(); protected slots: virtual void openDatabase(); diff --git a/src/totp/totp.cpp b/src/totp/totp.cpp index 26716c09..7a584def 100644 --- a/src/totp/totp.cpp +++ b/src/totp/totp.cpp @@ -18,15 +18,15 @@ #include "totp.h" #include "core/Base32.h" -#include -#include -#include -#include #include +#include #include +#include #include #include - +#include +#include +#include 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 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(¤t), 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; +} diff --git a/src/totp/totp.h b/src/totp/totp.h index 642b4f9a..d5d8aa67 100644 --- a/src/totp/totp.h +++ b/src/totp/totp.h @@ -21,12 +21,21 @@ #include +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; }; diff --git a/tests/TestBase32.cpp b/tests/TestBase32.cpp index 7268e927..1d30e781 100644 --- a/tests/TestBase32.cpp +++ b/tests/TestBase32.cpp @@ -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().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().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().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().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().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().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().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().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().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().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().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().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().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().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().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().size() == expectedData.size()); } void TestBase32::testEncode() @@ -115,7 +163,7 @@ void TestBase32::testEncode() data = "12345678901234567890"; encodedData = Base32::encode(data); - QCOMPARE(encodedData, QByteArray("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")); + QCOMPARE(encodedData, QByteArray("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")); data = "012345678901234567890"; encodedData = Base32::encode(data); @@ -123,46 +171,160 @@ void TestBase32::testEncode() data = "test"; encodedData = Base32::encode(data); - QCOMPARE(encodedData, QByteArray("ORSXG5A=")); + QCOMPARE(encodedData, QByteArray("ORSXG5A=")); data = "___"; encodedData = Base32::encode(data); - QCOMPARE(encodedData, QByteArray("L5PV6===")); + QCOMPARE(encodedData, QByteArray("L5PV6===")); data = "foo bar"; encodedData = Base32::encode(data); - QCOMPARE(encodedData, QByteArray("MZXW6IDCMFZA====")); + QCOMPARE(encodedData, QByteArray("MZXW6IDCMFZA====")); data = "@"; encodedData = Base32::encode(data); - QCOMPARE(encodedData, QByteArray("IA======")); + QCOMPARE(encodedData, QByteArray("IA======")); // RFC 4648 test vectors data = ""; encodedData = Base32::encode(data); - QCOMPARE(encodedData, QByteArray("")); + QCOMPARE(encodedData, QByteArray("")); data = "f"; encodedData = Base32::encode(data); - QCOMPARE(encodedData, QByteArray("MY======")); + QCOMPARE(encodedData, QByteArray("MY======")); data = "fo"; encodedData = Base32::encode(data); - QCOMPARE(encodedData, QByteArray("MZXQ====")); + QCOMPARE(encodedData, QByteArray("MZXQ====")); data = "foo"; encodedData = Base32::encode(data); QCOMPARE(encodedData, QByteArray("MZXW6===")); - + data = "foob"; encodedData = Base32::encode(data); - QCOMPARE(encodedData, QByteArray("MZXW6YQ=")); + QCOMPARE(encodedData, QByteArray("MZXW6YQ=")); data = "fooba"; encodedData = Base32::encode(data); - QCOMPARE(encodedData, QByteArray("MZXW6YTB")); + QCOMPARE(encodedData, QByteArray("MZXW6YTB")); data = "foobar"; encodedData = Base32::encode(data); - QCOMPARE(encodedData, QByteArray("MZXW6YTBOI======")); + 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...")); } diff --git a/tests/TestBase32.h b/tests/TestBase32.h index 6d4de34a..cf7cf092 100644 --- a/tests/TestBase32.h +++ b/tests/TestBase32.h @@ -29,6 +29,9 @@ class TestBase32 : public QObject private slots: void testEncode(); void testDecode(); + void testAddPadding(); + void testRemovePadding(); + void testSanitizeInput(); }; #endif // KEEPASSX_TESTBASE32_H diff --git a/tests/TestTotp.cpp b/tests/TestTotp.cpp index 7a3b2e3c..48ff8814 100644 --- a/tests/TestTotp.cpp +++ b/tests/TestTotp.cpp @@ -18,11 +18,11 @@ #include "TestTotp.h" -#include -#include #include -#include +#include #include +#include +#include #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));