295 lines
7.0 KiB
C++
295 lines
7.0 KiB
C++
#include "storage/SecureStorage.hpp"
|
|
|
|
#include <Void/Security/Security.hpp>
|
|
|
|
#include <QCoreApplication>
|
|
#include <QCryptographicHash>
|
|
#include <QDataStream>
|
|
#include <QDateTime>
|
|
#include <QDir>
|
|
#include <QFile>
|
|
#include <QFileInfo>
|
|
#include <QRandomGenerator>
|
|
#include <QSaveFile>
|
|
#include <QStandardPaths>
|
|
|
|
#include <algorithm>
|
|
#include <span>
|
|
|
|
namespace Echoion::Desktop
|
|
{
|
|
namespace
|
|
{
|
|
const QByteArray storageMagic{"ECV2", 4};
|
|
|
|
[[nodiscard]] Void::Security::SecretKey
|
|
toSecretKey(const QByteArray& value)
|
|
{
|
|
Void::Security::SecretKey key{};
|
|
std::copy_n(
|
|
reinterpret_cast<const unsigned char*>(value.constData()),
|
|
key.size(), key.begin());
|
|
return key;
|
|
}
|
|
} // namespace
|
|
|
|
SecureStorage::SecureStorage() = default;
|
|
|
|
QString SecureStorage::getStorageDir()
|
|
{
|
|
QString appDir = QCoreApplication::applicationDirPath();
|
|
QString dataDir = appDir + "/data";
|
|
|
|
QDir dir(dataDir);
|
|
if (!dir.exists()) {
|
|
dir.mkpath(".");
|
|
}
|
|
|
|
return dataDir;
|
|
}
|
|
|
|
QString SecureStorage::getSettingsPath()
|
|
{
|
|
return getStorageDir() + "/settings.dat";
|
|
}
|
|
|
|
QString SecureStorage::getTokensPath()
|
|
{
|
|
return getStorageDir() + "/tokens.dat";
|
|
}
|
|
|
|
QByteArray SecureStorage::loadOrCreateKey() const
|
|
{
|
|
if (!cachedKey_.isEmpty()) {
|
|
return cachedKey_;
|
|
}
|
|
|
|
const QString keyPath = getStorageDir() + "/secrets.key";
|
|
const QFileInfo keyInfo{keyPath};
|
|
if (keyInfo.isSymLink()) {
|
|
return {};
|
|
}
|
|
QFile keyFile{keyPath};
|
|
if (keyFile.exists()) {
|
|
if (!keyFile.open(QIODevice::ReadOnly)) {
|
|
return {};
|
|
}
|
|
QByteArray key = keyFile.readAll();
|
|
if (key.size() !=
|
|
static_cast<qsizetype>(Void::Security::secret_key_bytes)) {
|
|
return {};
|
|
}
|
|
cachedKey_ = key;
|
|
return cachedKey_;
|
|
}
|
|
|
|
auto generated = Void::Security::random_secret_key();
|
|
if (!generated) {
|
|
return {};
|
|
}
|
|
QByteArray key{reinterpret_cast<const char*>(generated->data()),
|
|
static_cast<qsizetype>(generated->size())};
|
|
QSaveFile output{keyPath};
|
|
if (!output.open(QIODevice::WriteOnly)) {
|
|
return {};
|
|
}
|
|
if (!output.setPermissions(QFileDevice::ReadOwner |
|
|
QFileDevice::WriteOwner) ||
|
|
output.write(key) != key.size() || !output.commit()) {
|
|
output.cancelWriting();
|
|
return {};
|
|
}
|
|
cachedKey_ = key;
|
|
return cachedKey_;
|
|
}
|
|
|
|
QByteArray SecureStorage::legacyKey() const
|
|
{
|
|
QString seed =
|
|
QCoreApplication::applicationDirPath() +
|
|
QCoreApplication::applicationName() +
|
|
QString::number(QDateTime::currentDateTime().date().year());
|
|
|
|
QByteArray hash =
|
|
QCryptographicHash::hash(seed.toUtf8(), QCryptographicHash::Sha256);
|
|
|
|
// Add some randomness but keep it deterministic for this machine
|
|
QRandomGenerator rng(qHash(seed));
|
|
for (int i = 0; i < hash.size(); ++i) {
|
|
hash[i] = hash[i] ^ static_cast<char>(rng.generate() & 0xFF);
|
|
}
|
|
|
|
return hash;
|
|
}
|
|
|
|
QByteArray SecureStorage::legacyXor(const QByteArray& data,
|
|
const QByteArray& key)
|
|
{
|
|
if (key.isEmpty()) {
|
|
return {};
|
|
}
|
|
QByteArray result = data;
|
|
const qsizetype keyLen = key.size();
|
|
|
|
for (qsizetype i = 0; i < result.size(); ++i) {
|
|
result[i] = result[i] ^ key[i % keyLen];
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
QByteArray SecureStorage::encrypt(const QByteArray& data) const
|
|
{
|
|
const QByteArray encodedKey = loadOrCreateKey();
|
|
if (encodedKey.size() !=
|
|
static_cast<qsizetype>(Void::Security::secret_key_bytes)) {
|
|
return {};
|
|
}
|
|
const auto* bytes =
|
|
reinterpret_cast<const unsigned char*>(data.constData());
|
|
auto sealed = Void::Security::seal_secret(
|
|
std::span<const unsigned char>{
|
|
bytes, static_cast<std::size_t>(data.size())},
|
|
toSecretKey(encodedKey));
|
|
if (!sealed) {
|
|
return {};
|
|
}
|
|
QByteArray result = storageMagic;
|
|
result.append(reinterpret_cast<const char*>(sealed->data()),
|
|
static_cast<qsizetype>(sealed->size()));
|
|
return result;
|
|
}
|
|
|
|
QByteArray SecureStorage::decrypt(const QByteArray& data) const
|
|
{
|
|
if (data.startsWith(storageMagic)) {
|
|
const QByteArray encodedKey = loadOrCreateKey();
|
|
if (encodedKey.size() !=
|
|
static_cast<qsizetype>(Void::Security::secret_key_bytes)) {
|
|
return {};
|
|
}
|
|
const auto envelope = data.sliced(storageMagic.size());
|
|
const auto* bytes =
|
|
reinterpret_cast<const unsigned char*>(envelope.constData());
|
|
auto opened = Void::Security::open_secret(
|
|
std::span<const unsigned char>{
|
|
bytes, static_cast<std::size_t>(envelope.size())},
|
|
toSecretKey(encodedKey));
|
|
if (!opened) {
|
|
return {};
|
|
}
|
|
return QByteArray{reinterpret_cast<const char*>(opened->data()),
|
|
static_cast<qsizetype>(opened->size())};
|
|
}
|
|
|
|
// Accept the v1 format only to migrate existing installations.
|
|
if (data.length() < 8) {
|
|
return {};
|
|
}
|
|
|
|
QDataStream headerStream(data);
|
|
quint32 magic = 0;
|
|
quint32 dataLen = 0;
|
|
headerStream >> magic >> dataLen;
|
|
if (magic != 0x4543484F ||
|
|
dataLen != static_cast<quint32>(data.size() - 8)) {
|
|
return {};
|
|
}
|
|
|
|
return legacyXor(data.sliced(8), legacyKey());
|
|
}
|
|
|
|
bool SecureStorage::saveToFile(const QString& filepath,
|
|
const QByteArray& data) const
|
|
{
|
|
// Create backup of existing file
|
|
if (QFile::exists(filepath)) {
|
|
createBackup(filepath);
|
|
}
|
|
|
|
QSaveFile output{filepath};
|
|
if (!output.open(QIODevice::WriteOnly)) {
|
|
return false;
|
|
}
|
|
|
|
if (!output.setPermissions(QFileDevice::ReadOwner |
|
|
QFileDevice::WriteOwner) ||
|
|
output.write(data) != data.size()) {
|
|
output.cancelWriting();
|
|
return false;
|
|
}
|
|
return output.commit();
|
|
}
|
|
|
|
QByteArray SecureStorage::loadFromFile(const QString& filepath) const
|
|
{
|
|
QFile file(filepath);
|
|
|
|
if (!file.open(QIODevice::ReadOnly)) {
|
|
// Try to restore from backup
|
|
if (restoreFromBackup(filepath)) {
|
|
return loadFromFile(filepath); // Retry
|
|
}
|
|
return QByteArray();
|
|
}
|
|
|
|
QByteArray data = file.readAll();
|
|
file.close();
|
|
|
|
return data;
|
|
}
|
|
|
|
void SecureStorage::createBackup(const QString& filepath) const
|
|
{
|
|
QString backupPath = filepath + ".backup";
|
|
QFile::remove(backupPath); // Remove old backup
|
|
QFile::copy(filepath, backupPath);
|
|
|
|
// Cleanup old backups (keep only last 3)
|
|
cleanupOldBackups(filepath, 3);
|
|
}
|
|
|
|
bool SecureStorage::restoreFromBackup(const QString& filepath) const
|
|
{
|
|
QString backupPath = filepath + ".backup";
|
|
|
|
if (!QFile::exists(backupPath)) {
|
|
return false;
|
|
}
|
|
|
|
QFile::remove(filepath);
|
|
return QFile::copy(backupPath, filepath);
|
|
}
|
|
|
|
void SecureStorage::cleanupOldBackups(const QString& filepath,
|
|
int maxBackups) const
|
|
{
|
|
QString basePath = filepath + ".backup";
|
|
QFileInfo info(basePath);
|
|
QDir dir = info.dir();
|
|
QString baseName = info.fileName();
|
|
|
|
// List all backup files
|
|
QStringList filters;
|
|
filters << baseName + "*";
|
|
|
|
QFileInfoList backups = dir.entryInfoList(filters, QDir::Files);
|
|
|
|
if (backups.size() <= maxBackups) {
|
|
return;
|
|
}
|
|
|
|
// Sort by modification time (oldest first)
|
|
std::sort(backups.begin(), backups.end(),
|
|
[](const QFileInfo& a, const QFileInfo& b) {
|
|
return a.lastModified() < b.lastModified();
|
|
});
|
|
|
|
// Remove oldest backups
|
|
for (int i = 0; i < backups.size() - maxBackups; ++i) {
|
|
QFile::remove(backups[i].absoluteFilePath());
|
|
}
|
|
}
|
|
|
|
} // namespace Echoion::Desktop
|