keepassxc/src/format/KdbxReader.cpp

256 lines
6.3 KiB
C++
Raw Normal View History

/*
* Copyright (C) 2018 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/>.
*/
#include "KdbxReader.h"
#include "core/Database.h"
#include "core/Endian.h"
2021-07-12 02:10:29 +00:00
#include "crypto/SymmetricCipher.h"
#include "streams/StoreDataStream.h"
2018-03-23 10:18:06 +00:00
#define UUID_LENGTH 16
2018-03-22 21:56:05 +00:00
/**
* Read KDBX magic header numbers from a device.
*
* @param device input device
* @param sig1 KDBX signature 1
* @param sig2 KDBX signature 2
* @param version KDBX version
* @return true if magic numbers were read successfully
*/
bool KdbxReader::readMagicNumbers(QIODevice* device, quint32& sig1, quint32& sig2, quint32& version)
{
bool ok;
sig1 = Endian::readSizedInt<quint32>(device, KeePass2::BYTEORDER, &ok);
if (!ok) {
return false;
}
sig2 = Endian::readSizedInt<quint32>(device, KeePass2::BYTEORDER, &ok);
if (!ok) {
return false;
}
version = Endian::readSizedInt<quint32>(device, KeePass2::BYTEORDER, &ok);
return ok;
}
/**
* Read KDBX stream from device.
* The device will automatically be reset to 0 before reading.
*
* @param device input device
* @param key database encryption composite key
* @param db database to read into
* @return true on success
*/
bool KdbxReader::readDatabase(QIODevice* device, QSharedPointer<const CompositeKey> key, Database* db)
{
device->seek(0);
m_db = db;
m_masterSeed.clear();
m_encryptionIV.clear();
m_streamStartBytes.clear();
m_protectedStreamKey.clear();
StoreDataStream headerStream(device);
headerStream.open(QIODevice::ReadOnly);
// read KDBX magic numbers
quint32 sig1, sig2, version;
if (!readMagicNumbers(&headerStream, sig1, sig2, version)) {
return false;
}
m_kdbxSignature = qMakePair(sig1, sig2);
m_db->setFormatVersion(version);
// read header fields
while (readHeaderField(headerStream, m_db) && !hasError()) {
}
headerStream.close();
if (hasError()) {
return false;
}
// read payload
return readDatabaseImpl(device, headerStream.storedData(), std::move(key), db);
}
bool KdbxReader::hasError() const
{
return m_error;
}
QString KdbxReader::errorString() const
{
return m_errorStr;
}
KeePass2::ProtectedStreamAlgo KdbxReader::protectedStreamAlgo() const
{
return m_irsAlgo;
}
/**
* @param data stream cipher UUID as bytes
*/
void KdbxReader::setCipher(const QByteArray& data)
{
2018-03-23 10:18:06 +00:00
if (data.size() != UUID_LENGTH) {
2018-03-22 21:56:05 +00:00
raiseError(tr("Invalid cipher uuid length: %1 (length=%2)").arg(QString(data)).arg(data.size()));
return;
}
2018-03-22 21:56:05 +00:00
QUuid uuid = QUuid::fromRfc4122(data);
if (uuid.isNull()) {
raiseError(tr("Unable to parse UUID: %1").arg(QString(data)));
return;
}
Replace all crypto libraries with Botan Selected the [Botan crypto library](https://github.com/randombit/botan) due to its feature list, maintainer support, availability across all deployment platforms, and ease of use. Also evaluated Crypto++ as a viable candidate, but the additional features of Botan (PKCS#11, TPM, etc) won out. The random number generator received a backend upgrade. Botan prefers hardware-based RNG's and will provide one if available. This is transparent to KeePassXC and a significant improvement over gcrypt. Replaced Argon2 library with built-in Botan implementation that supports i, d, and id. This requires Botan 2.11.0 or higher. Also simplified the parameter test across KDF's. Aligned SymmetricCipher parameters with available modes. All encrypt and decrypt operations are done in-place instead of returning new objects. This allows use of secure vectors in the future with no additional overhead. Took this opportunity to decouple KeeShare from SSH Agent. Removed leftover code from OpenSSHKey and consolidated the SSH Agent code into the same directory. Removed bcrypt and blowfish inserts since they are provided by Botan. Additionally simplified KeeShare settings interface by removing raw certificate byte data from the user interface. KeeShare will be further refactored in a future PR. NOTE: This PR breaks backwards compatibility with KeeShare certificates due to different RSA key storage with Botan. As a result, new "own" certificates will need to be generated and trust re-established. Removed YKChallengeResponseKeyCLI in favor of just using the original implementation with signal/slots. Removed TestRandom stub since it was just faking random numbers and not actually using the backend. TestRandomGenerator now uses the actual RNG. Greatly simplified Secret Service plugin's use of crypto functions with Botan.
2021-04-04 12:56:00 +00:00
if (SymmetricCipher::cipherUuidToMode(uuid) == SymmetricCipher::InvalidMode) {
raiseError(tr("Unsupported cipher"));
return;
}
m_db->setCipher(uuid);
}
/**
* @param data compression flags as bytes
*/
void KdbxReader::setCompressionFlags(const QByteArray& data)
{
if (data.size() != 4) {
raiseError(tr("Invalid compression flags length"));
return;
}
auto id = Endian::bytesToSizedInt<quint32>(data, KeePass2::BYTEORDER);
if (id > Database::CompressionAlgorithmMax) {
raiseError(tr("Unsupported compression algorithm"));
return;
}
m_db->setCompressionAlgorithm(static_cast<Database::CompressionAlgorithm>(id));
}
/**
* @param data master seed as bytes
*/
void KdbxReader::setMasterSeed(const QByteArray& data)
{
if (data.size() != 32) {
raiseError(tr("Invalid master seed size"));
return;
}
m_masterSeed = data;
}
/**
* @param data KDF seed as bytes
*/
void KdbxReader::setTransformSeed(const QByteArray& data)
{
if (data.size() != 32) {
raiseError(tr("Invalid transform seed size"));
return;
}
auto kdf = m_db->kdf();
if (!kdf.isNull()) {
kdf->setSeed(data);
}
}
/**
* @param data KDF transform rounds as bytes
*/
void KdbxReader::setTransformRounds(const QByteArray& data)
{
if (data.size() != 8) {
raiseError(tr("Invalid transform rounds size"));
return;
}
auto rounds = Endian::bytesToSizedInt<quint64>(data, KeePass2::BYTEORDER);
auto kdf = m_db->kdf();
if (!kdf.isNull()) {
kdf->setRounds(static_cast<int>(rounds));
}
}
/**
* @param data cipher stream IV as bytes
*/
void KdbxReader::setEncryptionIV(const QByteArray& data)
{
m_encryptionIV = data;
}
/**
* @param data key for random (inner) stream as bytes
*/
void KdbxReader::setProtectedStreamKey(const QByteArray& data)
{
m_protectedStreamKey = data;
}
/**
* @param data start bytes for cipher stream
*/
void KdbxReader::setStreamStartBytes(const QByteArray& data)
{
if (data.size() != 32) {
raiseError(tr("Invalid start bytes size"));
return;
}
m_streamStartBytes = data;
}
/**
* @param data id of inner cipher stream algorithm
*/
void KdbxReader::setInnerRandomStreamID(const QByteArray& data)
{
if (data.size() != 4) {
raiseError(tr("Invalid random stream id size"));
return;
}
auto id = Endian::bytesToSizedInt<quint32>(data, KeePass2::BYTEORDER);
KeePass2::ProtectedStreamAlgo irsAlgo = KeePass2::idToProtectedStreamAlgo(id);
2018-03-31 20:01:30 +00:00
if (irsAlgo == KeePass2::ProtectedStreamAlgo::InvalidProtectedStreamAlgo
|| irsAlgo == KeePass2::ProtectedStreamAlgo::ArcFourVariant) {
raiseError(tr("Invalid inner random stream cipher"));
return;
}
m_irsAlgo = irsAlgo;
}
/**
* Raise an error. Use in case of an unexpected read error.
*
* @param errorMessage error message
*/
void KdbxReader::raiseError(const QString& errorMessage)
{
m_error = true;
m_errorStr = errorMessage;
}