Introduce CryKeyProvider to have an abstraction layer that allows plugging in non-password-based key providers

This commit is contained in:
Sebastian Messmer 2018-10-21 19:31:08 -07:00
parent 954d6662f6
commit 74cd8abf05
33 changed files with 494 additions and 201 deletions

View File

@ -11,8 +11,13 @@ namespace cpputils {
public:
virtual ~PasswordBasedKDF() = default;
virtual EncryptionKey deriveKey(size_t keySize, const std::string &password) = 0;
virtual const Data &kdfParameters() const = 0;
struct KeyResult final {
cpputils::EncryptionKey key;
cpputils::Data kdfParameters;
};
virtual EncryptionKey deriveExistingKey(size_t keySize, const std::string& password, const Data& kdfParameters) = 0;
virtual KeyResult deriveNewKey(size_t keySize, const std::string& password) = 0;
};
}

View File

@ -52,7 +52,6 @@ namespace cpputils {
}
cpputils::Data serialize() const;
static SCryptParameters deserialize(const cpputils::Data &data);
#ifndef CRYFS_NO_COMPATIBILITY

View File

@ -5,49 +5,48 @@ using std::string;
namespace cpputils {
constexpr SCryptSettings SCrypt::ParanoidSettings;
constexpr SCryptSettings SCrypt::DefaultSettings;
constexpr SCryptSettings SCrypt::TestSettings;
constexpr SCryptSettings SCrypt::ParanoidSettings;
constexpr SCryptSettings SCrypt::DefaultSettings;
constexpr SCryptSettings SCrypt::TestSettings;
unique_ref<SCrypt> SCrypt::forNewKey(const SCryptSettings &settings) {
SCryptParameters kdfParameters(Random::PseudoRandom().get(settings.SALT_LEN), settings.N, settings.r, settings.p);
return make_unique_ref<SCrypt>(std::move(kdfParameters));
namespace {
EncryptionKey _derive(size_t keySize, const std::string& password, const SCryptParameters& kdfParameters) {
auto result = EncryptionKey::Null(keySize);
size_t status = CryptoPP::Scrypt().DeriveKey(
static_cast<uint8_t*>(result.data()), result.binaryLength(),
reinterpret_cast<const uint8_t*>(password.c_str()), password.size(),
static_cast<const uint8_t*>(kdfParameters.salt().data()), kdfParameters.salt().size(),
kdfParameters.N(), kdfParameters.r(), kdfParameters.p()
);
if (status != 1) {
throw std::runtime_error("Error running scrypt key derivation. Error code: "+std::to_string(status));
}
unique_ref<SCrypt> SCrypt::forExistingKey(const Data &parameters) {
return make_unique_ref<SCrypt>(SCryptParameters::deserialize(parameters));
}
return result;
}
SCrypt::SCrypt(SCryptParameters config)
:_config(std::move(config)), _serializedConfig(_config.serialize()), _wasGeneratedBefore(false) {
}
SCryptParameters _createNewSCryptParameters(const SCryptSettings& settings) {
return SCryptParameters(Random::PseudoRandom().get(settings.SALT_LEN), settings.N, settings.r, settings.p);
}
}
EncryptionKey SCrypt::deriveKey(size_t keySize, const std::string &password) {
_checkCallOnlyOnce();
SCrypt::SCrypt(const SCryptSettings& settingsForNewKeys)
:_settingsForNewKeys(settingsForNewKeys) {
}
auto result = EncryptionKey::Null(keySize);
EncryptionKey SCrypt::deriveExistingKey(size_t keySize, const std::string& password, const Data& kdfParameters) {
SCryptParameters parameters = SCryptParameters::deserialize(kdfParameters);
auto key = _derive(keySize, password, parameters);
return key;
}
size_t status = CryptoPP::Scrypt().DeriveKey(
static_cast<uint8_t*>(result.data()), result.binaryLength(),
reinterpret_cast<const uint8_t*>(password.c_str()), password.size(),
static_cast<const uint8_t*>(_config.salt().data()), _config.salt().size(),
_config.N(), _config.r(), _config.p()
);
if (status != 1) {
throw std::runtime_error("Error running scrypt key derivation. Error code: "+std::to_string(status));
}
return result;
}
const Data &SCrypt::kdfParameters() const {
return _serializedConfig;
}
void SCrypt::_checkCallOnlyOnce() {
if (_wasGeneratedBefore) {
throw std::runtime_error("An SCrypt instance can only generate exactly one key. Generating multiple keys would be insecure because we would use the same salt.");
}
_wasGeneratedBefore = true;
}
}
SCrypt::KeyResult SCrypt::deriveNewKey(size_t keySize, const std::string& password) {
SCryptParameters kdfParameters = _createNewSCryptParameters(_settingsForNewKeys);
auto key = _derive(keySize, password, kdfParameters);
return SCrypt::KeyResult {
key,
kdfParameters.serialize()
};
}
}

View File

@ -25,21 +25,13 @@ namespace cpputils {
static constexpr SCryptSettings DefaultSettings = SCryptSettings {32, 1048576, 4, 8};
static constexpr SCryptSettings TestSettings = SCryptSettings {32, 1024, 1, 1};
static unique_ref<SCrypt> forNewKey(const SCryptSettings &settings);
static unique_ref<SCrypt> forExistingKey(const Data &parameters);
explicit SCrypt(const SCryptSettings& settingsForNewKeys);
const Data &kdfParameters() const override;
SCrypt(SCryptParameters config);
EncryptionKey deriveKey(size_t keySize, const std::string &password) override;
EncryptionKey deriveExistingKey(size_t keySize, const std::string& password, const Data& kdfParameters) override;
KeyResult deriveNewKey(size_t keySize, const std::string& password) override;
private:
void _checkCallOnlyOnce();
SCryptParameters _config;
Data _serializedConfig;
bool _wasGeneratedBefore;
SCryptSettings _settingsForNewKeys;
DISALLOW_COPY_AND_ASSIGN(SCrypt);
};

View File

@ -12,6 +12,7 @@
#include <cpp-utils/io/DontEchoStdinToStdoutRAII.h>
#include <cryfs/filesystem/CryDevice.h>
#include <cryfs/config/CryConfigLoader.h>
#include <cryfs/config/CryPasswordBasedKeyProvider.h>
#include "program_options/Parser.h"
#include <boost/filesystem.hpp>
@ -41,6 +42,7 @@ using cpputils::NoninteractiveConsole;
using cpputils::TempFile;
using cpputils::RandomGenerator;
using cpputils::unique_ref;
using cpputils::SCrypt;
using cpputils::SCryptSettings;
using cpputils::Console;
using cpputils::HttpClient;
@ -65,7 +67,7 @@ using gitversion::VersionCompare;
namespace cryfs {
Cli::Cli(RandomGenerator &keyGenerator, const SCryptSettings &scryptSettings, shared_ptr<Console> console):
Cli::Cli(RandomGenerator &keyGenerator, const SCryptSettings& scryptSettings, shared_ptr<Console> console):
_keyGenerator(keyGenerator), _scryptSettings(scryptSettings), _console(), _noninteractive(false) {
_noninteractive = Environment::isNoninteractive();
if (_noninteractive) {
@ -133,6 +135,7 @@ namespace cryfs {
};
function<string()> Cli::_askPasswordForNewFilesystem(std::shared_ptr<cpputils::Console> console) {
//TODO Ask confirmation if using insecure password (<8 characters)
return [console] () {
string password;
bool again = false;
@ -204,17 +207,16 @@ namespace cryfs {
}
optional<CryConfigLoader::ConfigLoadResult> Cli::_loadOrCreateConfigFile(bf::path configFilePath, LocalStateDir localStateDir, const optional<string> &cipher, const optional<uint32_t> &blocksizeBytes, bool allowFilesystemUpgrade, const optional<bool> &missingBlockIsIntegrityViolation, bool allowReplacedFilesystem) {
if (_noninteractive) {
return CryConfigLoader(_console, _keyGenerator, std::move(localStateDir), _scryptSettings,
Cli::_askPasswordNoninteractive(_console),
Cli::_askPasswordNoninteractive(_console),
cipher, blocksizeBytes, missingBlockIsIntegrityViolation).loadOrCreate(std::move(configFilePath), allowFilesystemUpgrade, allowReplacedFilesystem);
} else {
return CryConfigLoader(_console, _keyGenerator, std::move(localStateDir), _scryptSettings,
Cli::_askPasswordForExistingFilesystem(_console),
Cli::_askPasswordForNewFilesystem(_console),
cipher, blocksizeBytes, missingBlockIsIntegrityViolation).loadOrCreate(std::move(configFilePath), allowFilesystemUpgrade, allowReplacedFilesystem);
}
// TODO Instead of passing in _askPasswordXXX functions to KeyProvider, only pass in console and move logic to the key provider,
// for example by having a separate CryPasswordBasedKeyProvider / CryNoninteractivePasswordBasedKeyProvider.
auto keyProvider = make_unique_ref<CryPasswordBasedKeyProvider>(
_console,
_noninteractive ? Cli::_askPasswordNoninteractive(_console) : Cli::_askPasswordForExistingFilesystem(_console),
_noninteractive ? Cli::_askPasswordNoninteractive(_console) : Cli::_askPasswordForNewFilesystem(_console),
make_unique_ref<SCrypt>(_scryptSettings)
);
return CryConfigLoader(_console, _keyGenerator, std::move(keyProvider), std::move(localStateDir),
cipher, blocksizeBytes, missingBlockIsIntegrityViolation).loadOrCreate(std::move(configFilePath), allowFilesystemUpgrade, allowReplacedFilesystem);
}
void Cli::_runFilesystem(const ProgramOptions &options) {

View File

@ -17,7 +17,7 @@
namespace cryfs {
class Cli final {
public:
Cli(cpputils::RandomGenerator &keyGenerator, const cpputils::SCryptSettings &scryptSettings, std::shared_ptr<cpputils::Console> console);
Cli(cpputils::RandomGenerator &keyGenerator, const cpputils::SCryptSettings& scryptSettings, std::shared_ptr<cpputils::Console> console);
int main(int argc, const char *argv[], cpputils::unique_ref<cpputils::HttpClient> httpClient);
private:

View File

@ -1,6 +1,5 @@
#include "Cli.h"
#include <cpp-utils/random/Random.h>
#include <cpp-utils/crypto/kdf/Scrypt.h>
#include <cpp-utils/io/IOStreamConsole.h>
#include <cryfs/CryfsException.h>
@ -22,9 +21,9 @@ int main(int argc, const char *argv[]) {
try {
auto &keyGenerator = Random::OSRandom();
#if defined(_MSC_VER)
auto httpClient = make_unique_ref<cpputils::WinHttpClient>();
auto httpClient = make_unique_ref<cpputils::WinHttpClient>();
#else
auto httpClient = make_unique_ref<cpputils::CurlHttpClient>();
auto httpClient = make_unique_ref<cpputils::CurlHttpClient>();
#endif
return Cli(keyGenerator, SCrypt::DefaultSettings, make_shared<IOStreamConsole>())
.main(argc, argv, std::move(httpClient));

View File

@ -16,6 +16,8 @@ set(LIB_SOURCES
config/CryConfigFile.cpp
config/CryCipher.cpp
config/CryConfigCreator.cpp
config/CryKeyProvider.cpp
config/CryPasswordBasedKeyProvider.cpp
filesystem/CryOpenFile.cpp
filesystem/fsblobstore/utils/DirEntry.cpp
filesystem/fsblobstore/utils/DirEntryList.cpp

View File

@ -73,7 +73,7 @@ namespace cryfs {
}
string CryConfigCreator::_generateEncKey(const std::string &cipher) {
_console->print("\nGenerating secure encryption key. This might take some time..");
_console->print("\nGenerating secure encryption key. This can take some time...");
auto key = CryCiphers::find(cipher).createKey(_encryptionKeyGenerator);
_console->print("done\n");
return key;

View File

@ -15,7 +15,6 @@ using std::stringstream;
using std::istream;
using cpputils::Data;
using cpputils::unique_ref;
using cpputils::SCryptSettings;
namespace bf = boost::filesystem;
using namespace cpputils::logging;
@ -25,13 +24,13 @@ CryConfigFile::~CryConfigFile() {
//We do not call save() here, because we do not want the config file to be re-encrypted on each filesystem run
}
optional<CryConfigFile> CryConfigFile::load(bf::path path, const string &password) {
optional<CryConfigFile> CryConfigFile::load(bf::path path, CryKeyProvider* keyProvider) {
auto encryptedConfigData = Data::LoadFromFile(path);
if (encryptedConfigData == none) {
LOG(ERR, "Config file not found");
return none;
}
auto encryptor = CryConfigEncryptorFactory::loadKey(*encryptedConfigData, password);
auto encryptor = CryConfigEncryptorFactory::loadExistingKey(*encryptedConfigData, keyProvider);
if (encryptor == none) {
return none;
}
@ -53,11 +52,11 @@ optional<CryConfigFile> CryConfigFile::load(bf::path path, const string &passwor
return std::move(configFile);
}
CryConfigFile CryConfigFile::create(bf::path path, CryConfig config, const string &password, const SCryptSettings &scryptSettings) {
CryConfigFile CryConfigFile::create(bf::path path, CryConfig config, CryKeyProvider* keyProvider) {
if (bf::exists(path)) {
throw std::runtime_error("Config file exists already.");
}
auto result = CryConfigFile(std::move(path), std::move(config), CryConfigEncryptorFactory::deriveKey(password, scryptSettings));
auto result = CryConfigFile(std::move(path), std::move(config), CryConfigEncryptorFactory::deriveNewKey(keyProvider));
result.save();
return result;
}

View File

@ -14,8 +14,8 @@ namespace cryfs {
CryConfigFile(CryConfigFile &&rhs) = default;
~CryConfigFile();
static CryConfigFile create(boost::filesystem::path path, CryConfig config, const std::string &password, const cpputils::SCryptSettings &scryptSettings);
static boost::optional<CryConfigFile> load(boost::filesystem::path path, const std::string &password);
static CryConfigFile create(boost::filesystem::path path, CryConfig config, CryKeyProvider* keyProvider);
static boost::optional<CryConfigFile> load(boost::filesystem::path path, CryKeyProvider* keyProvider);
void save() const;
CryConfig *config();

View File

@ -13,34 +13,29 @@
namespace bf = boost::filesystem;
using cpputils::Console;
using cpputils::RandomGenerator;
using cpputils::SCryptSettings;
using cpputils::unique_ref;
using boost::optional;
using boost::none;
using std::shared_ptr;
using std::string;
using std::function;
using std::shared_ptr;
using gitversion::VersionCompare;
using namespace cpputils::logging;
namespace cryfs {
CryConfigLoader::CryConfigLoader(shared_ptr<Console> console, RandomGenerator &keyGenerator, LocalStateDir localStateDir, const SCryptSettings &scryptSettings, function<string()> askPasswordForExistingFilesystem, function<string()> askPasswordForNewFilesystem, const optional<string> &cipherFromCommandLine, const boost::optional<uint32_t> &blocksizeBytesFromCommandLine, const boost::optional<bool> &missingBlockIsIntegrityViolationFromCommandLine)
: _console(console), _creator(std::move(console), keyGenerator, localStateDir), _scryptSettings(scryptSettings),
_askPasswordForExistingFilesystem(askPasswordForExistingFilesystem), _askPasswordForNewFilesystem(askPasswordForNewFilesystem),
CryConfigLoader::CryConfigLoader(shared_ptr<Console> console, RandomGenerator &keyGenerator, unique_ref<CryKeyProvider> keyProvider, LocalStateDir localStateDir, const optional<string> &cipherFromCommandLine, const boost::optional<uint32_t> &blocksizeBytesFromCommandLine, const boost::optional<bool> &missingBlockIsIntegrityViolationFromCommandLine)
: _console(console), _creator(std::move(console), keyGenerator, localStateDir), _keyProvider(std::move(keyProvider)),
_cipherFromCommandLine(cipherFromCommandLine), _blocksizeBytesFromCommandLine(blocksizeBytesFromCommandLine),
_missingBlockIsIntegrityViolationFromCommandLine(missingBlockIsIntegrityViolationFromCommandLine),
_localStateDir(std::move(localStateDir)) {
}
optional<CryConfigLoader::ConfigLoadResult> CryConfigLoader::_loadConfig(bf::path filename, bool allowFilesystemUpgrade, bool allowReplacedFilesystem) {
string password = _askPasswordForExistingFilesystem();
std::cout << "Loading config file (this can take some time)..." << std::flush;
auto config = CryConfigFile::load(std::move(filename), password);
auto config = CryConfigFile::load(std::move(filename), _keyProvider.get());
if (config == none) {
return none;
}
std::cout << "done" << std::endl;
#ifndef CRYFS_NO_COMPATIBILITY
//Since 0.9.7 and 0.9.8 set their own version to cryfs.version instead of the filesystem format version (which is 0.9.6), overwrite it
if (config->config()->Version() == "0.9.7" || config->config()->Version() == "0.9.8") {
@ -117,11 +112,7 @@ optional<CryConfigLoader::ConfigLoadResult> CryConfigLoader::loadOrCreate(bf::pa
CryConfigLoader::ConfigLoadResult CryConfigLoader::_createConfig(bf::path filename, bool allowReplacedFilesystem) {
auto config = _creator.create(_cipherFromCommandLine, _blocksizeBytesFromCommandLine, _missingBlockIsIntegrityViolationFromCommandLine, allowReplacedFilesystem);
//TODO Ask confirmation if using insecure password (<8 characters)
string password = _askPasswordForNewFilesystem();
std::cout << "Creating config file (this can take some time)..." << std::flush;
auto result = CryConfigFile::create(std::move(filename), std::move(config.config), password, _scryptSettings);
std::cout << "done" << std::endl;
auto result = CryConfigFile::create(std::move(filename), std::move(config.config), _keyProvider.get());
return ConfigLoadResult {std::move(result), config.myClientId};
}

View File

@ -7,13 +7,14 @@
#include "CryConfigFile.h"
#include "CryCipher.h"
#include "CryConfigCreator.h"
#include <cpp-utils/crypto/kdf/Scrypt.h>
#include "CryKeyProvider.h"
namespace cryfs {
class CryConfigLoader final {
public:
CryConfigLoader(std::shared_ptr<cpputils::Console> console, cpputils::RandomGenerator &keyGenerator, LocalStateDir localStateDir, const cpputils::SCryptSettings &scryptSettings, std::function<std::string()> askPasswordForExistingFilesystem, std::function<std::string()> askPasswordForNewFilesystem, const boost::optional<std::string> &cipherFromCommandLine, const boost::optional<uint32_t> &blocksizeBytesFromCommandLine, const boost::optional<bool> &missingBlockIsIntegrityViolationFromCommandLine);
// note: keyGenerator generates the inner (i.e. file system) key. keyProvider asks for the password and generates the outer (i.e. config file) key.
CryConfigLoader(std::shared_ptr<cpputils::Console> console, cpputils::RandomGenerator &keyGenerator, cpputils::unique_ref<CryKeyProvider> keyProvider, LocalStateDir localStateDir, const boost::optional<std::string> &cipherFromCommandLine, const boost::optional<uint32_t> &blocksizeBytesFromCommandLine, const boost::optional<bool> &missingBlockIsIntegrityViolationFromCommandLine);
CryConfigLoader(CryConfigLoader &&rhs) = default;
struct ConfigLoadResult {
@ -32,9 +33,7 @@ private:
std::shared_ptr<cpputils::Console> _console;
CryConfigCreator _creator;
cpputils::SCryptSettings _scryptSettings;
std::function<std::string()> _askPasswordForExistingFilesystem;
std::function<std::string()> _askPasswordForNewFilesystem;
cpputils::unique_ref<CryKeyProvider> _keyProvider;
boost::optional<std::string> _cipherFromCommandLine;
boost::optional<uint32_t> _blocksizeBytesFromCommandLine;
boost::optional<bool> _missingBlockIsIntegrityViolationFromCommandLine;

View File

@ -0,0 +1 @@
#include "CryKeyProvider.h"

View File

@ -0,0 +1,24 @@
#pragma once
#ifndef CRYFS_CRYKEYPROVIDER_H
#define CRYFS_CRYKEYPROVIDER_H
#include <cpp-utils/crypto/symmetric/EncryptionKey.h>
namespace cryfs {
class CryKeyProvider {
public:
virtual ~CryKeyProvider() = default;
struct KeyResult final {
cpputils::EncryptionKey key;
cpputils::Data kdfParameters;
};
virtual cpputils::EncryptionKey requestKeyForExistingFilesystem(size_t keySize, const cpputils::Data& kdfParameters) = 0;
virtual KeyResult requestKeyForNewFilesystem(size_t keySize) = 0;
};
}
#endif

View File

@ -0,0 +1,31 @@
#include "CryPasswordBasedKeyProvider.h"
using std::shared_ptr;
using cpputils::Console;
using cpputils::unique_ref;
using cpputils::EncryptionKey;
using cpputils::unique_ref;
using cpputils::PasswordBasedKDF;
namespace cryfs {
CryPasswordBasedKeyProvider::CryPasswordBasedKeyProvider(shared_ptr<Console> console, std::function<std::string()> askPasswordForExistingFilesystem, std::function<std::string()> askPasswordForNewFilesystem, unique_ref<PasswordBasedKDF> kdf)
: _console(std::move(console)), _askPasswordForExistingFilesystem(std::move(askPasswordForExistingFilesystem)), _askPasswordForNewFilesystem(std::move(askPasswordForNewFilesystem)), _kdf(std::move(kdf)) {}
EncryptionKey CryPasswordBasedKeyProvider::requestKeyForExistingFilesystem(size_t keySize, const cpputils::Data& kdfParameters) {
auto password = _askPasswordForExistingFilesystem();
_console->print("Deriving encryption key (this can take some time)...");
auto key = _kdf->deriveExistingKey(keySize, password, kdfParameters);
_console->print("done\n");
return key;
}
CryKeyProvider::KeyResult CryPasswordBasedKeyProvider::requestKeyForNewFilesystem(size_t keySize) {
auto password = _askPasswordForNewFilesystem();
_console->print("Deriving encryption key (this can take some time)...");
auto keyResult = _kdf->deriveNewKey(keySize, password);
_console->print("done\n");
return {std::move(keyResult.key), std::move(keyResult.kdfParameters)};
}
}

View File

@ -0,0 +1,31 @@
#pragma once
#ifndef CRYFS_CRYPASSWORDFROMCONSOLEKEYPROVIDER_H
#define CRYFS_CRYPASSWORDFROMCONSOLEKEYPROVIDER_H
#include "CryKeyProvider.h"
#include <functional>
#include <cpp-utils/crypto/kdf/Scrypt.h>
#include <cpp-utils/io/Console.h>
namespace cryfs {
class CryPasswordBasedKeyProvider final : public CryKeyProvider {
public:
// TODO Pass in KDF as dependency (needs changes in the KDF interface because of the static functions ::forNewKey and ::forExistingKey)
explicit CryPasswordBasedKeyProvider(std::shared_ptr<cpputils::Console> console, std::function<std::string()> askPasswordForExistingFilesystem, std::function<std::string()> askPasswordForNewFilesystem, cpputils::unique_ref<cpputils::PasswordBasedKDF> kdf);
cpputils::EncryptionKey requestKeyForExistingFilesystem(size_t keySize, const cpputils::Data& kdfParameters) override;
KeyResult requestKeyForNewFilesystem(size_t keySize) override;
private:
std::shared_ptr<cpputils::Console> _console;
std::function<std::string()> _askPasswordForExistingFilesystem;
std::function<std::string()> _askPasswordForNewFilesystem;
cpputils::unique_ref<cpputils::PasswordBasedKDF> _kdf;
DISALLOW_COPY_AND_ASSIGN(CryPasswordBasedKeyProvider);
};
}
#endif

View File

@ -1,6 +1,7 @@
#include "CryConfigEncryptorFactory.h"
#include <cpp-utils/crypto/symmetric/ciphers.h>
#include "outer/OuterConfig.h"
#include "cryfs/config/CryKeyProvider.h"
using namespace cpputils::logging;
using boost::optional;
@ -8,32 +9,27 @@ using boost::none;
using cpputils::unique_ref;
using cpputils::make_unique_ref;
using cpputils::Data;
using cpputils::SCrypt;
using cpputils::SCryptSettings;
using std::string;
//TODO It would be better, not to generate a MaxTotalKeySize key here, but to generate the outer key first, and then
// (once we know which inner cipher was used) only generate as many key bytes as we need for the inner cipher.
// This would need a change in the scrypt interface though, because right now we can't continue past key computations.
//TODO I might be able to know the actual key size here (at runtime) and switch the SCrypt deriveKey() interface to getting a dynamic size.
namespace cryfs {
optional<unique_ref<CryConfigEncryptor>> CryConfigEncryptorFactory::loadKey(const Data &data,
const string &password) {
optional<unique_ref<CryConfigEncryptor>> CryConfigEncryptorFactory::loadExistingKey(const Data &data,
CryKeyProvider *keyProvider) {
auto outerConfig = OuterConfig::deserialize(data);
if (outerConfig == none) {
return none;
}
return _deriveKey(SCrypt::forExistingKey(outerConfig->kdfParameters), password);
auto key = keyProvider->requestKeyForExistingFilesystem(CryConfigEncryptor::MaxTotalKeySize, outerConfig->kdfParameters);
return make_unique_ref<CryConfigEncryptor>(key, std::move(outerConfig->kdfParameters));
}
unique_ref<CryConfigEncryptor> CryConfigEncryptorFactory::deriveKey(const string &password, const SCryptSettings &scryptSettings) {
return _deriveKey(SCrypt::forNewKey(scryptSettings), password);
}
unique_ref<CryConfigEncryptor>
CryConfigEncryptorFactory::_deriveKey(cpputils::unique_ref<SCrypt> kdf, const string &password) {
//TODO It would be better, not to generate a MaxTotalKeySize key here, but to generate the outer key first, and then
// (once we know which inner cipher was used) only generate as many key bytes as we need for the inner cipher.
// This would need a change in the scrypt interface though, because right now we can't continue past key computations.
//TODO I might be able to know the actual key size here (at runtime) and switch the SCrypt deriveKey() interface to getting a dynamic size.
auto key = kdf->deriveKey(CryConfigEncryptor::MaxTotalKeySize, password);
return make_unique_ref<CryConfigEncryptor>(key, kdf->kdfParameters().copy());
unique_ref<CryConfigEncryptor> CryConfigEncryptorFactory::deriveNewKey(CryKeyProvider *keyProvider) {
auto keyResult = keyProvider->requestKeyForNewFilesystem(CryConfigEncryptor::MaxTotalKeySize);
return make_unique_ref<CryConfigEncryptor>(std::move(keyResult.key), std::move(keyResult.kdfParameters));
}
}

View File

@ -9,16 +9,14 @@
#include "../CryCipher.h"
namespace cryfs {
class CryKeyProvider;
class CryConfigEncryptorFactory final {
public:
static cpputils::unique_ref<CryConfigEncryptor> deriveKey(const std::string &password, const cpputils::SCryptSettings &scryptSettings);
static cpputils::unique_ref<CryConfigEncryptor> deriveNewKey(CryKeyProvider *keyProvider);
static boost::optional<cpputils::unique_ref<CryConfigEncryptor>> loadKey(const cpputils::Data &ciphertext,
const std::string &password);
private:
static cpputils::unique_ref<CryConfigEncryptor> _deriveKey(cpputils::unique_ref<cpputils::SCrypt> kdf, const std::string &password);
static boost::optional<cpputils::unique_ref<CryConfigEncryptor>> loadExistingKey(const cpputils::Data &ciphertext,
CryKeyProvider *keyProvider);
};
}

View File

@ -1,6 +1,7 @@
#include <iostream>
#include <boost/filesystem.hpp>
#include <cryfs/config/CryConfigFile.h>
#include <cryfs/config/CryPasswordBasedKeyProvider.h>
#include <blockstore/implementations/ondisk/OnDiskBlockStore2.h>
#include <blockstore/implementations/low2highlevel/LowToHighLevelBlockStore.h>
#include <blobstore/implementations/onblocks/datanodestore/DataNodeStore.h>
@ -11,6 +12,7 @@
#include <cryfs/filesystem/fsblobstore/FsBlobStore.h>
#include <cryfs/filesystem/fsblobstore/DirBlob.h>
#include <cryfs/filesystem/CryDevice.h>
#include <cpp-utils/io/IOStreamConsole.h>
#include <set>
@ -112,11 +114,19 @@ set<BlockId> _getBlocksReferencedByDirEntries(const CryConfig &config) {
int main() {
cout << "Password: ";
string password;
getline(cin, password);
cout << "Loading config" << endl;
auto config = CryConfigFile::load("/home/heinzi/basedir/cryfs.config", password);
auto console = std::make_shared<cpputils::IOStreamConsole>();
console->print("Loading config\n");
auto askPassword = [console] () {
return console->askPassword("Password: ");
};
auto keyProvider = make_unique_ref<CryPasswordBasedKeyProvider>(
console,
askPassword,
askPassword,
make_unique_ref<SCrypt>(SCrypt::DefaultSettings)
);
auto config = CryConfigFile::load("/home/heinzi/basedir/cryfs.config", keyProvider.get());
set<BlockId> unaccountedBlocks = _getBlockstoreUnaccountedBlocks(*config->config());
//Remove all blocks that are referenced by a directory entry from unaccountedBlocks
set<BlockId> blocksReferencedByDirEntries = _getBlocksReferencedByDirEntries(*config->config());
@ -124,7 +134,7 @@ int main() {
unaccountedBlocks.erase(blockId);
}
cout << "\nCalculate statistics" << endl;
console->print("Calculate statistics\n");
auto onDiskBlockStore = make_unique_ref<OnDiskBlockStore2>("/home/heinzi/basedir");
auto encryptedBlockStore = CryCiphers::find(config->config()->Cipher()).createEncryptedBlockstore(std::move(onDiskBlockStore), config->config()->EncryptionKey());
@ -134,9 +144,9 @@ int main() {
uint32_t numUnaccountedBlocks = unaccountedBlocks.size();
uint32_t numLeaves = 0;
uint32_t numInner = 0;
cout << "\nUnaccounted blocks: " << unaccountedBlocks.size() << endl;
console->print("Unaccounted blocks: " + std::to_string(unaccountedBlocks.size()) + "\n");
for (const auto &blockId : unaccountedBlocks) {
std::cout << "\r" << (numLeaves+numInner) << "/" << numUnaccountedBlocks << flush;
console->print("\r" + std::to_string(numLeaves+numInner) + "/" + std::to_string(numUnaccountedBlocks));
auto node = nodeStore->load(blockId);
auto innerNode = dynamic_pointer_move<DataInnerNode>(*node);
if (innerNode != none) {
@ -149,5 +159,5 @@ int main() {
printNode(std::move(*leafNode));
}
}
cout << "\n" << numLeaves << " leaves and " << numInner << " inner nodes" << endl;
console->print("\n" + std::to_string(numLeaves) + " leaves and " + std::to_string(numInner) + " inner nodes\n");
}

View File

@ -6,14 +6,6 @@ using std::string;
class SCryptTest : public ::testing::Test {
public:
unique_ref<SCrypt> scryptForNewKey = SCrypt::forNewKey(SCrypt::TestSettings);
unique_ref<SCrypt> scryptForExistingKey = SCrypt::forExistingKey(scryptForNewKey->kdfParameters());
SCryptParameters kdfParameters(const SCrypt &scrypt) {
SCryptParameters result = SCryptParameters::deserialize(scrypt.kdfParameters());
return result;
}
bool keyEquals(const EncryptionKey& lhs, const EncryptionKey& rhs) {
ASSERT(lhs.binaryLength() == rhs.binaryLength(), "Keys must have equal size to be comparable");
return 0 == std::memcmp(lhs.data(), rhs.data(), lhs.binaryLength());
@ -21,38 +13,44 @@ public:
};
TEST_F(SCryptTest, GeneratedKeyIsReproductible_448) {
auto derivedKey = scryptForNewKey->deriveKey(56, "mypassword");
auto rederivedKey = scryptForExistingKey->deriveKey(56, "mypassword");
EXPECT_TRUE(keyEquals(derivedKey, rederivedKey));
SCrypt scrypt(SCrypt::TestSettings);
auto derivedKey = scrypt.deriveNewKey(56, "mypassword");
auto rederivedKey = scrypt.deriveExistingKey(56, "mypassword", derivedKey.kdfParameters);
EXPECT_TRUE(keyEquals(derivedKey.key, rederivedKey));
}
TEST_F(SCryptTest, GeneratedKeyIsReproductible_256) {
auto derivedKey = scryptForNewKey->deriveKey(32, "mypassword");
auto rederivedKey = scryptForExistingKey->deriveKey(32, "mypassword");
EXPECT_TRUE(keyEquals(derivedKey, rederivedKey));
SCrypt scrypt(SCrypt::TestSettings);
auto derivedKey = scrypt.deriveNewKey(32, "mypassword");
auto rederivedKey = scrypt.deriveExistingKey(32, "mypassword", derivedKey.kdfParameters);
EXPECT_TRUE(keyEquals(derivedKey.key, rederivedKey));
}
TEST_F(SCryptTest, GeneratedKeyIsReproductible_128) {
auto derivedKey = scryptForNewKey->deriveKey(16, "mypassword");
auto rederivedKey = scryptForExistingKey->deriveKey(16, "mypassword");
EXPECT_TRUE(keyEquals(derivedKey, rederivedKey));
SCrypt scrypt(SCrypt::TestSettings);
auto derivedKey = scrypt.deriveNewKey(16, "mypassword");
auto rederivedKey = scrypt.deriveExistingKey(16, "mypassword", derivedKey.kdfParameters);
EXPECT_TRUE(keyEquals(derivedKey.key, rederivedKey));
}
TEST_F(SCryptTest, GeneratedKeyIsReproductible_DefaultSettings) {
auto derivedKey = scryptForNewKey->deriveKey(16, "mypassword");
auto rederivedKey = scryptForExistingKey->deriveKey(16, "mypassword");
EXPECT_TRUE(keyEquals(derivedKey, rederivedKey));
SCrypt scrypt(SCrypt::TestSettings);
auto derivedKey = scrypt.deriveNewKey(16, "mypassword");
auto rederivedKey = scrypt.deriveExistingKey(16, "mypassword", derivedKey.kdfParameters);
EXPECT_TRUE(keyEquals(derivedKey.key, rederivedKey));
}
TEST_F(SCryptTest, DifferentPasswordResultsInDifferentKey) {
auto derivedKey = scryptForNewKey->deriveKey(16, "mypassword");
auto rederivedKey = scryptForExistingKey->deriveKey(16, "mypassword2");
EXPECT_FALSE(keyEquals(derivedKey, rederivedKey));
SCrypt scrypt(SCrypt::TestSettings);
auto derivedKey = scrypt.deriveNewKey(16, "mypassword");
auto rederivedKey = scrypt.deriveExistingKey(16, "mypassword2", derivedKey.kdfParameters);
EXPECT_FALSE(keyEquals(derivedKey.key, rederivedKey));
}
TEST_F(SCryptTest, UsesCorrectSettings) {
auto scrypt = SCrypt::forNewKey(SCrypt::TestSettings);
SCryptParameters parameters = kdfParameters(*scrypt);
SCrypt scrypt(SCrypt::TestSettings);
auto derivedKey = scrypt.deriveNewKey(16, "mypassword");
auto parameters = SCryptParameters::deserialize(derivedKey.kdfParameters);
EXPECT_EQ(SCrypt::TestSettings.SALT_LEN, parameters.salt().size());
EXPECT_EQ(SCrypt::TestSettings.N, parameters.N());
EXPECT_EQ(SCrypt::TestSettings.r, parameters.r());
@ -60,8 +58,9 @@ TEST_F(SCryptTest, UsesCorrectSettings) {
}
TEST_F(SCryptTest, UsesCorrectDefaultSettings) {
auto scrypt = SCrypt::forNewKey(SCrypt::DefaultSettings);
SCryptParameters parameters = kdfParameters(*scrypt);
SCrypt scrypt(SCrypt::DefaultSettings);
auto derivedKey = scrypt.deriveNewKey(16, "mypassword");
auto parameters = SCryptParameters::deserialize(derivedKey.kdfParameters);
EXPECT_EQ(SCrypt::DefaultSettings.SALT_LEN, parameters.salt().size());
EXPECT_EQ(SCrypt::DefaultSettings.N, parameters.N());
EXPECT_EQ(SCrypt::DefaultSettings.r, parameters.r());

View File

@ -1,23 +1,45 @@
#include "testutils/CliTest.h"
#include <cryfs/config/CryConfigFile.h>
#include <cryfs/ErrorCodes.h>
#include <cpp-utils/crypto/kdf/Scrypt.h>
#include <cpp-utils/data/DataFixture.h>
using std::vector;
using std::string;
using cryfs::CryConfig;
using cryfs::CryConfigFile;
using cryfs::ErrorCode;
using cryfs::CryKeyProvider;
using cpputils::Data;
using cpputils::EncryptionKey;
using cpputils::SCrypt;
class FakeCryKeyProvider final : public CryKeyProvider {
EncryptionKey requestKeyForExistingFilesystem(size_t keySize, const Data& kdfParameters) override {
return SCrypt(SCrypt::TestSettings).deriveExistingKey(keySize, "pass", kdfParameters);
}
KeyResult requestKeyForNewFilesystem(size_t keySize) override {
auto derived = SCrypt(SCrypt::TestSettings).deriveNewKey(keySize, "pass");
return {
std::move(derived.key),
std::move(derived.kdfParameters)
};
}
};
class CliTest_IntegrityCheck: public CliTest {
public:
void modifyFilesystemId() {
auto configFile = CryConfigFile::load(basedir / "cryfs.config", "pass").value();
FakeCryKeyProvider keyProvider;
auto configFile = CryConfigFile::load(basedir / "cryfs.config", &keyProvider).value();
configFile.config()->SetFilesystemId(CryConfig::FilesystemID::FromString("0123456789ABCDEF0123456789ABCDEF"));
configFile.save();
}
void modifyFilesystemKey() {
auto configFile = CryConfigFile::load(basedir / "cryfs.config", "pass").value();
FakeCryKeyProvider keyProvider;
auto configFile = CryConfigFile::load(basedir / "cryfs.config", &keyProvider).value();
configFile.config()->SetEncryptionKey("0123456789ABCDEF0123456789ABCDEF");
configFile.save();
}

View File

@ -14,6 +14,7 @@ set(SOURCES
config/CryCipherTest.cpp
config/CryConfigLoaderTest.cpp
config/CryConfigConsoleTest.cpp
config/CryPasswordBasedKeyProviderTest.cpp
filesystem/CryFsTest.cpp
filesystem/CryNodeTest.cpp
filesystem/FileSystemTest.cpp

View File

@ -7,11 +7,16 @@
#include <cpp-utils/crypto/symmetric/ciphers.h>
#include <cpp-utils/tempfile/TempFile.h>
#include <cryfs/config/CryConfigFile.h>
#include <cryfs/config/CryPasswordBasedKeyProvider.h>
#include "../testutils/MockConsole.h"
using cpputils::Data;
using cpputils::AES256_GCM;
using cpputils::Serpent128_CFB;
using cpputils::TempFile;
using cpputils::make_unique_ref;
using cpputils::SCrypt;
using std::make_shared;
using namespace cryfs;
// Test that config files created with (old) versions of cryfs are still loadable.
@ -23,7 +28,13 @@ public:
CryConfigFile loadConfigFromHex(const string &configFileContentHex) {
storeHexToFile(configFileContentHex);
return CryConfigFile::load(file.path(), "mypassword").value();
CryPasswordBasedKeyProvider keyProvider(
make_shared<MockConsole>(),
[] () {return "mypassword"; },
[] () {return "mypassword"; },
make_unique_ref<SCrypt>(SCrypt::DefaultSettings)
);
return CryConfigFile::load(file.path(), &keyProvider).value();
}
private:

View File

@ -1,13 +1,13 @@
#include <gtest/gtest.h>
#include <cryfs/config/CryConfigFile.h>
#include <cpp-utils/tempfile/TempFile.h>
#include "../testutils/FakeCryKeyProvider.h"
using namespace cryfs;
using cpputils::TempFile;
using std::string;
using boost::optional;
using boost::none;
using cpputils::SCrypt;
using cpputils::Data;
namespace bf = boost::filesystem;
@ -33,17 +33,19 @@ public:
return result;
}
CryConfigFile CreateAndLoadEmpty(const string &password = "mypassword") {
Create(Config(), password);
CryConfigFile CreateAndLoadEmpty(unsigned char keySeed = 0) {
Create(Config(), keySeed);
return Load().value();
}
void Create(CryConfig cfg, const string &password = "mypassword") {
CryConfigFile::create(file.path(), std::move(cfg), password, SCrypt::TestSettings);
void Create(CryConfig cfg, unsigned int keySeed = 0) {
FakeCryKeyProvider keyProvider(keySeed);
CryConfigFile::create(file.path(), std::move(cfg), &keyProvider);
}
optional<CryConfigFile> Load(const string &password = "mypassword") {
return CryConfigFile::load(file.path(), password);
optional<CryConfigFile> Load(unsigned int keySeed = 0) {
FakeCryKeyProvider keyProvider(keySeed);
return CryConfigFile::load(file.path(), &keyProvider);
}
void CreateWithCipher(const string &cipher) {
@ -53,13 +55,16 @@ public:
void CreateWithCipher(const string &cipher, const TempFile &tempFile) {
CryConfig cfg;
cfg.SetCipher(cipher);
CryConfigFile::create(tempFile.path(), std::move(cfg), "mypassword", SCrypt::TestSettings);
FakeCryKeyProvider keyProvider(0);
CryConfigFile::create(tempFile.path(), std::move(cfg), &keyProvider);
}
};
TEST_F(CryConfigFileTest, DoesntLoadIfWrongPassword) {
Create(Config(), "mypassword");
auto loaded = Load("mypassword2");
const unsigned char pw1 = 0;
const unsigned char pw2 = 1;
Create(Config(), pw1);
auto loaded = Load(pw2);
EXPECT_EQ(none, loaded);
}
@ -190,11 +195,13 @@ TEST_F(CryConfigFileTest, CanSaveAndLoadModififedCipher) {
}
TEST_F(CryConfigFileTest, FailsIfConfigFileIsEncryptedWithACipherDifferentToTheOneSpecifiedByTheUser) {
auto encryptor = CryConfigEncryptorFactory::deriveKey("mypassword", SCrypt::TestSettings);
constexpr unsigned char keySeed = 0;
FakeCryKeyProvider keyProvider(keySeed);
auto encryptor = CryConfigEncryptorFactory::deriveNewKey(&keyProvider);
auto config = Config();
config.SetCipher("aes-256-gcm");
Data encrypted = encryptor->encrypt(config.save(), "aes-256-cfb");
encrypted.StoreToFile(file.path());
auto loaded = Load("mypassword");
auto loaded = Load(keySeed);
EXPECT_EQ(none, loaded);
}

View File

@ -1,5 +1,6 @@
#include <gtest/gtest.h>
#include <cryfs/config/CryConfigLoader.h>
#include <cryfs/config/CryPasswordBasedKeyProvider.h>
#include "../testutils/MockConsole.h"
#include "../testutils/TestWithFakeHomeDirectory.h"
#include <cpp-utils/tempfile/TempFile.h>
@ -16,10 +17,15 @@ using cpputils::SCrypt;
using cpputils::DataFixture;
using cpputils::Data;
using cpputils::NoninteractiveConsole;
using cpputils::make_unique_ref;
using cpputils::Console;
using cpputils::unique_ref;
using cryfs::CryPasswordBasedKeyProvider;
using boost::optional;
using boost::none;
using std::string;
using std::ostream;
using std::shared_ptr;
using std::make_shared;
using ::testing::Return;
using ::testing::HasSubstr;
@ -56,19 +62,23 @@ private:
class CryConfigLoaderTest: public ::testing::Test, public TestWithMockConsole, TestWithFakeHomeDirectory {
public:
unique_ref<CryKeyProvider> keyProvider(const string& password) {
auto askPassword = [password] { return password;};
return make_unique_ref<CryPasswordBasedKeyProvider>(
console,
askPassword,
askPassword,
make_unique_ref<SCrypt>(SCrypt::TestSettings)
);
}
CryConfigLoaderTest(): file(false), tempLocalStateDir(), localStateDir(tempLocalStateDir.path()) {
console = mockConsole();
}
CryConfigLoader loader(const string &password, bool noninteractive, const optional<string> &cipher = none) {
auto askPassword = [password] { return password;};
if(noninteractive) {
return CryConfigLoader(make_shared<NoninteractiveConsole>(console), cpputils::Random::PseudoRandom(), localStateDir, SCrypt::TestSettings, askPassword,
askPassword, cipher, none, none);
} else {
return CryConfigLoader(console, cpputils::Random::PseudoRandom(), localStateDir, SCrypt::TestSettings, askPassword,
askPassword, cipher, none, none);
}
auto _console = noninteractive ? shared_ptr<Console>(make_shared<NoninteractiveConsole>(console)) : shared_ptr<Console>(console);
return CryConfigLoader(_console, cpputils::Random::PseudoRandom(), keyProvider(password), localStateDir, cipher, none, none);
}
CryConfigFile Create(const string &password = "mypassword", const optional<string> &cipher = none, bool noninteractive = false) {
@ -98,15 +108,13 @@ public:
}
void CreateWithEncryptionKey(const string &encKey, const string &password = "mypassword") {
auto askPassword = [password] { return password;};
FakeRandomGenerator generator(Data::FromString(encKey));
auto loader = CryConfigLoader(console, generator, localStateDir, SCrypt::TestSettings, askPassword,
askPassword, none, none, none);
auto loader = CryConfigLoader(console, generator, keyProvider(password), localStateDir, none, none, none);
ASSERT_NE(boost::none, loader.loadOrCreate(file.path(), false, false));
}
void ChangeEncryptionKey(const string &encKey, const string& password = "mypassword") {
auto cfg = CryConfigFile::load(file.path(), password).value();
auto cfg = CryConfigFile::load(file.path(), keyProvider(password).get()).value();
cfg.config()->SetEncryptionKey(encKey);
cfg.save();
}
@ -126,7 +134,7 @@ public:
}
void ChangeFilesystemID(const CryConfig::FilesystemID &filesystemId, const string& password = "mypassword") {
auto cfg = CryConfigFile::load(file.path(), password).value();
auto cfg = CryConfigFile::load(file.path(), keyProvider(password).get()).value();
cfg.config()->SetFilesystemId(filesystemId);
cfg.save();
}
@ -258,7 +266,7 @@ TEST_F(CryConfigLoaderTest, Version_Load) {
TEST_F(CryConfigLoaderTest, Version_Load_IsStoredAndNotOnlyOverwrittenInMemoryOnLoad) {
CreateWithVersion("0.9.2", "0.9.2", "mypassword");
Load().value();
auto configFile = CryConfigFile::load(file.path(), "mypassword").value();
auto configFile = CryConfigFile::load(file.path(), keyProvider("mypassword").get()).value();
EXPECT_EQ(CryConfig::FilesystemFormatVersion, configFile.config()->Version());
EXPECT_EQ(gitversion::VersionString(), configFile.config()->LastOpenedWithVersion());
EXPECT_EQ("0.9.2", configFile.config()->CreatedWithVersion());

View File

@ -0,0 +1,85 @@
#include <cryfs/config/CryPasswordBasedKeyProvider.h>
#include <gmock/gmock.h>
#include "../testutils/MockConsole.h"
#include <cpp-utils/data/DataFixture.h>
using cpputils::unique_ref;
using cpputils::make_unique_ref;
using cpputils::EncryptionKey;
using cpputils::PasswordBasedKDF;
using cpputils::Data;
using cpputils::DataFixture;
using std::shared_ptr;
using std::make_shared;
using std::string;
using cryfs::CryPasswordBasedKeyProvider;
using testing::Return;
using testing::Invoke;
using testing::Eq;
using testing::StrEq;
using testing::NiceMock;
using testing::_;
class MockCallable {
public:
MOCK_METHOD0(call, std::string());
};
class MockKDF : public PasswordBasedKDF {
public:
MOCK_METHOD3(deriveExistingKey, EncryptionKey(size_t keySize, const string& password, const Data& kdfParameters));
MOCK_METHOD2(deriveNewKey, KeyResult(size_t keySize, const string& password));
};
class CryPasswordBasedKeyProviderTest : public ::testing::Test {
public:
CryPasswordBasedKeyProviderTest()
: mockConsole(make_shared<NiceMock<MockConsole>>())
, askPasswordForNewFilesystem()
, askPasswordForExistingFilesystem()
, kdf_(make_unique_ref<MockKDF>())
, kdf(kdf_.get())
, keyProvider(mockConsole, [this] () {return askPasswordForExistingFilesystem.call();}, [this] () {return askPasswordForNewFilesystem.call(); }, std::move(kdf_)) {}
shared_ptr<NiceMock<MockConsole>> mockConsole;
MockCallable askPasswordForNewFilesystem;
MockCallable askPasswordForExistingFilesystem;
unique_ref<MockKDF> kdf_;
MockKDF* kdf;
CryPasswordBasedKeyProvider keyProvider;
};
TEST_F(CryPasswordBasedKeyProviderTest, requestKeyForNewFilesystem) {
constexpr size_t keySize = 512;
constexpr const char* password = "mypassword";
const EncryptionKey key = EncryptionKey::FromString(DataFixture::generate(keySize).ToString());
const Data kdfParameters = DataFixture::generate(100);
EXPECT_CALL(askPasswordForNewFilesystem, call()).Times(1).WillOnce(Return(password));
EXPECT_CALL(askPasswordForExistingFilesystem, call()).Times(0);
EXPECT_CALL(*kdf, deriveNewKey(Eq(keySize), StrEq(password))).Times(1).WillOnce(Invoke([&] (auto, auto) {return PasswordBasedKDF::KeyResult{key, kdfParameters.copy()};}));
auto returned_key = keyProvider.requestKeyForNewFilesystem(keySize);
EXPECT_EQ(key.ToString(), returned_key.key.ToString());
EXPECT_EQ(kdfParameters, returned_key.kdfParameters);
}
TEST_F(CryPasswordBasedKeyProviderTest, requestKeyForExistingFilesystem) {
constexpr size_t keySize = 512;
constexpr const char* password = "mypassword";
const EncryptionKey key = EncryptionKey::FromString(DataFixture::generate(keySize).ToString());
const Data kdfParameters = DataFixture::generate(100);
EXPECT_CALL(askPasswordForNewFilesystem, call()).Times(0);
EXPECT_CALL(askPasswordForExistingFilesystem, call()).Times(1).WillOnce(Return(password));
EXPECT_CALL(*kdf, deriveExistingKey(Eq(keySize), StrEq(password), _)).Times(1).WillOnce(Invoke([&] (auto, auto, const auto& kdfParams) {
EXPECT_EQ(kdfParameters, kdfParams);
return key;
}));
EncryptionKey returned_key = keyProvider.requestKeyForExistingFilesystem(keySize, kdfParameters);
EXPECT_EQ(key.ToString(), returned_key.ToString());
}

View File

@ -2,8 +2,8 @@
#include <cryfs/config/crypto/CryConfigEncryptorFactory.h>
#include <cpp-utils/crypto/symmetric/ciphers.h>
#include <cpp-utils/data/DataFixture.h>
#include "../../testutils/FakeCryKeyProvider.h"
using cpputils::SCrypt;
using cpputils::AES256_GCM;
using cpputils::Data;
using cpputils::DataFixture;
@ -24,40 +24,48 @@ public:
};
TEST_F(CryConfigEncryptorFactoryTest, EncryptAndDecrypt_SameEncryptor) {
auto encryptor = CryConfigEncryptorFactory::deriveKey("mypassword", SCrypt::TestSettings);
FakeCryKeyProvider keyProvider;
auto encryptor = CryConfigEncryptorFactory::deriveNewKey(&keyProvider);
Data encrypted = encryptor->encrypt(DataFixture::generate(400), AES256_GCM::NAME);
auto decrypted = encryptor->decrypt(encrypted).value();
EXPECT_EQ(DataFixture::generate(400), decrypted.data);
}
TEST_F(CryConfigEncryptorFactoryTest, EncryptAndDecrypt_NewEncryptor) {
auto encryptor = CryConfigEncryptorFactory::deriveKey("mypassword", SCrypt::TestSettings);
FakeCryKeyProvider keyProvider1(1);
auto encryptor = CryConfigEncryptorFactory::deriveNewKey(&keyProvider1);
Data encrypted = encryptor->encrypt(DataFixture::generate(400), AES256_GCM::NAME);
auto loadedEncryptor = CryConfigEncryptorFactory::loadKey(encrypted, "mypassword").value();
FakeCryKeyProvider keyProvider2(1);
auto loadedEncryptor = CryConfigEncryptorFactory::loadExistingKey(encrypted, &keyProvider2).value();
auto decrypted = loadedEncryptor->decrypt(encrypted).value();
EXPECT_EQ(DataFixture::generate(400), decrypted.data);
}
TEST_F(CryConfigEncryptorFactoryTest, DoesntDecryptWithWrongPassword) {
auto encryptor = CryConfigEncryptorFactory::deriveKey("mypassword", SCrypt::TestSettings);
TEST_F(CryConfigEncryptorFactoryTest, DoesntDecryptWithWrongKey) {
FakeCryKeyProvider keyProvider1(1);
auto encryptor = CryConfigEncryptorFactory::deriveNewKey(&keyProvider1);
Data encrypted = encryptor->encrypt(DataFixture::generate(400), AES256_GCM::NAME);
auto loadedEncryptor = CryConfigEncryptorFactory::loadKey(encrypted, "wrongpassword").value();
FakeCryKeyProvider keyProvider2(2);
auto loadedEncryptor = CryConfigEncryptorFactory::loadExistingKey(encrypted, &keyProvider2).value();
auto decrypted = loadedEncryptor->decrypt(encrypted);
EXPECT_EQ(none, decrypted);
}
TEST_F(CryConfigEncryptorFactoryTest, DoesntDecryptWithWrongPassword_EmptyData) {
auto encryptor = CryConfigEncryptorFactory::deriveKey("mypassword", SCrypt::TestSettings);
TEST_F(CryConfigEncryptorFactoryTest, DoesntDecryptWithWrongKey_EmptyData) {
FakeCryKeyProvider keyProvider1(1);
auto encryptor = CryConfigEncryptorFactory::deriveNewKey(&keyProvider1);
Data encrypted = encryptor->encrypt(Data(0), AES256_GCM::NAME);
auto loadedEncryptor = CryConfigEncryptorFactory::loadKey(encrypted, "wrongpassword").value();
FakeCryKeyProvider keyProvider2(2);
auto loadedEncryptor = CryConfigEncryptorFactory::loadExistingKey(encrypted, &keyProvider2).value();
auto decrypted = loadedEncryptor->decrypt(encrypted);
EXPECT_EQ(none, decrypted);
}
TEST_F(CryConfigEncryptorFactoryTest, DoesntDecryptInvalidData) {
auto loadedEncryptor = CryConfigEncryptorFactory::loadKey(Data(0), "mypassword");
FakeCryKeyProvider keyProvider;
auto loadedEncryptor = CryConfigEncryptorFactory::loadExistingKey(Data(0), &keyProvider);
EXPECT_EQ(none, loadedEncryptor);
}
}

View File

@ -9,6 +9,7 @@
#include <cryfs/filesystem/CryOpenFile.h>
#include "../testutils/MockConsole.h"
#include <cryfs/config/CryConfigLoader.h>
#include <cryfs/config/CryPasswordBasedKeyProvider.h>
#include <cpp-utils/system/homedir.h>
#include "../testutils/TestWithFakeHomeDirectory.h"
#include <cpp-utils/io/NoninteractiveConsole.h>
@ -27,6 +28,7 @@ using cpputils::Data;
using cpputils::NoninteractiveConsole;
using blockstore::ondisk::OnDiskBlockStore2;
using boost::none;
using cryfs::CryPasswordBasedKeyProvider;
namespace bf = boost::filesystem;
using namespace cryfs;
@ -38,7 +40,13 @@ public:
CryConfigFile loadOrCreateConfig() {
auto askPassword = [] {return "mypassword";};
return CryConfigLoader(make_shared<NoninteractiveConsole>(mockConsole()), Random::PseudoRandom(), localStateDir, SCrypt::TestSettings, askPassword, askPassword, none, none, none).loadOrCreate(config.path(), false, false).value().configFile;
auto keyProvider = make_unique_ref<CryPasswordBasedKeyProvider>(
make_shared<MockConsole>(),
askPassword,
askPassword,
make_unique_ref<SCrypt>(SCrypt::TestSettings)
);
return CryConfigLoader(make_shared<NoninteractiveConsole>(mockConsole()), Random::PseudoRandom(), std::move(keyProvider), localStateDir, none, none, none).loadOrCreate(config.path(), false, false).value().configFile;
}
unique_ref<OnDiskBlockStore2> blockStore() {

View File

@ -4,6 +4,7 @@
#include <cpp-utils/io/NoninteractiveConsole.h>
#include <cryfs/filesystem/CryDevice.h>
#include <cryfs/config/CryConfigLoader.h>
#include <cryfs/config/CryPasswordBasedKeyProvider.h>
#include "../testutils/MockConsole.h"
#include "../testutils/TestWithFakeHomeDirectory.h"
@ -16,6 +17,7 @@ using fspp::Device;
using boost::none;
using std::make_shared;
using blockstore::inmemory::InMemoryBlockStore2;
using cryfs::CryPasswordBasedKeyProvider;
using namespace cryfs;
@ -28,7 +30,14 @@ public:
unique_ref<Device> createDevice() override {
auto blockStore = cpputils::make_unique_ref<InMemoryBlockStore2>();
auto askPassword = [] {return "mypassword";};
auto config = CryConfigLoader(make_shared<NoninteractiveConsole>(mockConsole()), Random::PseudoRandom(), localStateDir, SCrypt::TestSettings, askPassword, askPassword, none, none, none)
auto _console = make_shared<NoninteractiveConsole>(mockConsole());
auto keyProvider = make_unique_ref<CryPasswordBasedKeyProvider>(
_console,
askPassword,
askPassword,
make_unique_ref<SCrypt>(SCrypt::TestSettings)
);
auto config = CryConfigLoader(_console, Random::PseudoRandom(), std::move(keyProvider), localStateDir, none, none, none)
.loadOrCreate(configFile.path(), false, false).value();
return make_unique_ref<CryDevice>(std::move(config.configFile), std::move(blockStore), localStateDir, config.myClientId, false, false);
}

View File

@ -2,10 +2,12 @@
#define MESSMER_CRYFS_TEST_CRYFS_FILESYSTEM_CRYTESTBASE_H
#include <cryfs/filesystem/CryDevice.h>
#include <cryfs/config/CryPasswordBasedKeyProvider.h>
#include <blockstore/implementations/inmemory/InMemoryBlockStore2.h>
#include <cpp-utils/tempfile/TempFile.h>
#include <cpp-utils/crypto/kdf/Scrypt.h>
#include "../../testutils/TestWithFakeHomeDirectory.h"
#include "../../testutils/MockConsole.h"
class CryTestBase : public TestWithFakeHomeDirectory {
public:
@ -19,7 +21,13 @@ public:
config.SetCipher("aes-256-gcm");
config.SetEncryptionKey(cpputils::AES256_GCM::EncryptionKey::CreateKey(cpputils::Random::PseudoRandom(), cpputils::AES256_GCM::KEYSIZE).ToString());
config.SetBlocksizeBytes(10240);
return cryfs::CryConfigFile::create(_configFile.path(), std::move(config), "mypassword", cpputils::SCrypt::TestSettings);
cryfs::CryPasswordBasedKeyProvider keyProvider(
std::make_shared<MockConsole>(),
[] () {return "mypassword";},
[] () {return "mypassword";},
cpputils::make_unique_ref<cpputils::SCrypt>(cpputils::SCrypt::TestSettings)
);
return cryfs::CryConfigFile::create(_configFile.path(), std::move(config), &keyProvider);
}
cryfs::CryDevice &device() {

View File

@ -0,0 +1,35 @@
#pragma once
#ifndef CRYFS_FAKECRYKEYPROVIDER_H
#define CRYFS_FAKECRYKEYPROVIDER_H
#include <cryfs/config/CryKeyProvider.h>
#include <cpp-utils/data/DataFixture.h>
class FakeCryKeyProvider final : public cryfs::CryKeyProvider {
private:
static constexpr const unsigned char KDF_TEST_PARAMETERS = 5; // test value to check that kdf parameters are passed in correctly
public:
FakeCryKeyProvider(unsigned char keySeed = 0): _keySeed(keySeed) {}
cpputils::EncryptionKey requestKeyForExistingFilesystem(size_t keySize, const cpputils::Data& kdfParameters) override {
ASSERT(kdfParameters.size() == 1 && *reinterpret_cast<const unsigned char*>(kdfParameters.data()) == KDF_TEST_PARAMETERS, "Wrong kdf parameters");
return cpputils::EncryptionKey::FromString(cpputils::DataFixture::generate(keySize, _keySeed).ToString());
}
KeyResult requestKeyForNewFilesystem(size_t keySize) override {
cpputils::Data kdfParameters(sizeof(unsigned char));
*reinterpret_cast<unsigned char*>(kdfParameters.data()) = KDF_TEST_PARAMETERS;
auto key = requestKeyForExistingFilesystem(keySize, kdfParameters);
return KeyResult{
std::move(key),
std::move(kdfParameters)
};
}
private:
unsigned char _keySeed;
};
#endif

View File

@ -0,0 +1,14 @@
#pragma once
#ifndef CRYFS_MOCKCRYKEYPROVIDER_H
#define CRYFS_MOCKCRYKEYPROVIDER_H
#include <cryfs/config/CryKeyProvider.h>
#include <gmock/gmock.h>
class MockCryKeyProvider: public cryfs::CryKeyProvider {
public:
MOCK_METHOD2(requestKeyForExistingFilesystem, cpputils::EncryptionKey(size_t keySize, const cpputils::Data& kdfParameters));
MOCK_METHOD1(requestKeyForNewFilesystem, cryfs::CryKeyProvider::KeyResult(size_t keySize));
};
#endif