diff --git a/README.md b/README.md index 2ccb338af..6cd5ef3bf 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,9 @@ Indicative requirements: See [docs/storage.md](docs/storage.md) for the storage options. +If you encrypt the node key (`--encryptkey`, or the password choice at the first start), use a +long, unique password. + ## Building from source The builds that CI runs on every change are the reference: [build.yml](.github/workflows/build.yml) (Linux) and diff --git a/client/config/CMakeLists.txt b/client/config/CMakeLists.txt index 7dbf451e1..bbc21437c 100644 --- a/client/config/CMakeLists.txt +++ b/client/config/CMakeLists.txt @@ -12,6 +12,8 @@ add_library(${PROJECT_NAME} "config.cpp" "banner.hpp" "banner.cpp" + "keyfilecrypt.hpp" + "keyfilecrypt.cpp" ) target_link_libraries (${PROJECT_NAME} csnode lib) diff --git a/client/config/config.cpp b/client/config/config.cpp index 90951132f..43441e0c8 100644 --- a/client/config/config.cpp +++ b/client/config/config.cpp @@ -22,6 +22,7 @@ #include #include "config.hpp" +#include "keyfilecrypt.hpp" #ifdef _WIN32 #include @@ -31,6 +32,7 @@ #include #include #include +#include #include #endif @@ -208,30 +210,71 @@ static inline void writeFile(const std::string name, const std::string data) { } // the private key file (in clear, or encrypted by the node) and the keys JSON: readable by their -// owner only, mode 0600 on POSIX whatever the umask, also when the file existed with a wider mode. -// Same content and path as writeFile (no temporary file, a link is followed as before); Windows -// keeps the folder's ACL. -static inline void writeKeyFile(const std::string& name, const std::string& data) { +// owner only (mode 0600 on POSIX whatever the umask; Windows keeps the folder's ACL), and replaced +// atomically: the data goes to NAME.tmp, is flushed to disk, then renamed over NAME (a link named +// NAME is followed, its target replaced), and the folder is flushed where the system allows it. On +// any failure NAME is left as it was and false is returned. +static bool writeKeyFile(const std::string& name, const std::string& data) { #ifndef _WIN32 - const int fd = ::open(name.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); - if (fd >= 0) { - ::fchmod(fd, 0600); - size_t done = 0; - while (done < data.size()) { - const ssize_t n = ::write(fd, data.data() + done, data.size() - done); - if (n < 0 && errno == EINTR) { - continue; - } - if (n <= 0) { - break; - } - done += static_cast(n); + std::string target = name; + if (char* resolved = ::realpath(name.c_str(), nullptr)) { + target = resolved; + ::free(resolved); + } + const std::string tmp = target + ".tmp"; + const int fd = ::open(tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600); + if (fd < 0) { + return false; + } + bool ok = ::fchmod(fd, 0600) == 0; + size_t done = 0; + while (ok && done < data.size()) { + const ssize_t n = ::write(fd, data.data() + done, data.size() - done); + if (n < 0 && errno == EINTR) { + continue; } - ::close(fd); - return; + if (n <= 0) { + ok = false; + break; + } + done += static_cast(n); } + ok = ok && ::fsync(fd) == 0; + ok = (::close(fd) == 0) && ok; + if (!ok || ::rename(tmp.c_str(), target.c_str()) != 0) { + ::unlink(tmp.c_str()); + return false; + } + const auto slash = target.find_last_of('/'); + const std::string dir = slash == std::string::npos ? std::string(".") : (slash == 0 ? std::string("/") : target.substr(0, slash)); + const int dfd = ::open(dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dfd >= 0) { // best effort: the rename is done either way + ::fsync(dfd); + ::close(dfd); + } + return true; +#else + const std::string tmp = name + ".tmp"; + HANDLE h = ::CreateFileA(tmp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + return false; + } + bool ok = true; + size_t done = 0; + while (ok && done < data.size()) { + DWORD n = 0; + const DWORD chunk = static_cast(std::min(data.size() - done, 1u << 20)); + ok = ::WriteFile(h, data.data() + done, chunk, &n, nullptr) && n > 0; + done += n; + } + ok = ok && ::FlushFileBuffers(h); + ok = ::CloseHandle(h) && ok; + if (!ok || !::MoveFileExA(tmp.c_str(), name.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { + ::DeleteFileA(tmp.c_str()); + return false; + } + return true; #endif - writeFile(name, data); } void Config::dumpJSONKeys(const std::string& fName) const { @@ -241,7 +284,9 @@ void Config::dumpJSONKeys(const std::string& fName) const { auto sk58 = EncodeBase58(sk.data(), sk.data() + sk.size()); std::string json = "{\"key\":{\"public\":\"" + pk58 + "\",\"private\":\"" + sk58 + "\"}}"; - writeKeyFile(fName, json); + if (!writeKeyFile(fName, json)) { + cserror() << "Could not write " << fName; + } cscrypto::fillWithZeros(const_cast(json.data()), json.size()); cscrypto::fillWithZeros(const_cast(pk58.data()), pk58.size()); @@ -449,8 +494,8 @@ static bool encryptWithPassword(const cscrypto::PrivateKey& sk, std::vector(size)); + if (!buf.empty() && !f.read(&buf[0], static_cast(buf.size()))) { + sodium_memzero(&buf[0], buf.size()); + buf.clear(); + return false; + } return true; } +static void wipe(std::string& buf) { + if (!buf.empty()) { + sodium_memzero(&buf[0], buf.size()); + } + buf.clear(); +} + static bool encryptWithFile(const cscrypto::PrivateKey& sk, std::vector& skBytes) { std::string buf; if (!getBufFromFile(buf)) { return false; } - skBytes = sk.getEncrypted(buf.data(), buf.size()); - return true; + skBytes = cs::keyfile::encrypt(sk, buf.data(), buf.size()); + wipe(buf); + return !skBytes.empty(); // a failed derivation (e.g. no memory) never writes an empty key file } static bool usePassword() { @@ -604,9 +667,14 @@ void Config::changePasswordOption(const std::string& pathToSk) { const bool encSucc = getEncryptedPrivateBytes(privateKey_, skBytes); if (encSucc) { std::string sk58tmp = EncodeBase58(skBytes.data(), skBytes.data() + skBytes.size()); - writeKeyFile(pathToSk, sk58tmp); + const bool written = writeKeyFile(pathToSk, sk58tmp); cscrypto::fillWithZeros(const_cast(sk58tmp.data()), sk58tmp.size()); - cslog() << "Key in " << pathToSk << " has been encrypted successfully"; + if (written) { + cslog() << "Key in " << pathToSk << " has been encrypted successfully"; + } + else { + cserror() << "Could not write " << pathToSk << ": the key file was left as it was"; + } } else { cslog() << "Not encrypting the private key file due to errors"; } @@ -637,6 +705,10 @@ bool Config::readKeys(const std::string& pathToPk, const std::string& pathToSk, return false; } else if (sk.size() > cscrypto::kPrivateKeySize) { + if (sk.size() != cs::keyfile::kEncryptedSize) { + cserror() << "Bad private key file in " << pathToSk << " (" << sk.size() << " bytes)"; + return false; + } encFlag = true; callShowKeys = true; } @@ -654,14 +726,15 @@ bool Config::readKeys(const std::string& pathToPk, const std::string& pathToSk, return false; } std::cout << "Trying to open file..." << std::endl; - privateKey_ = cscrypto::PrivateKey::readFromEncrypted(sk, pass.data(), std::strlen(pass.data())); + privateKey_ = cs::keyfile::decrypt(sk, pass.data(), std::strlen(pass.data())); } else { std::string buf; if (!getBufFromFile(buf)) { return false; } - privateKey_ = cscrypto::PrivateKey::readFromEncrypted(sk, buf.data(), buf.size()); + privateKey_ = cs::keyfile::decrypt(sk, buf.data(), buf.size()); + wipe(buf); } if (!privateKey_) { @@ -688,9 +761,14 @@ bool Config::readKeys(const std::string& pathToPk, const std::string& pathToSk, const bool encSucc = getEncryptedPrivateBytes(privateKey_, skBytes); if (encSucc) { std::string sk58tmp = EncodeBase58(skBytes.data(), skBytes.data() + skBytes.size()); - writeKeyFile(pathToSk, sk58tmp); + const bool written = writeKeyFile(pathToSk, sk58tmp); cscrypto::fillWithZeros(const_cast(sk58tmp.data()), sk58tmp.size()); - cslog() << "Key in " << pathToSk << " has been encrypted successfully"; + if (written) { + cslog() << "Key in " << pathToSk << " has been encrypted successfully"; + } + else { + cserror() << "Could not write " << pathToSk << ": the key file was left as it was"; + } } else { cslog() << "Not encrypting the private key file due to errors"; @@ -753,12 +831,17 @@ bool Config::readKeys(const std::string& pathToPk, const std::string& pathToSk, std::string sk58 = EncodeBase58(skBytes.data(), skBytes.data() + skBytes.size()); writeFile(pathToPk, pk58); - writeKeyFile(pathToSk, sk58); + const bool written = writeKeyFile(pathToSk, sk58); // Just in case... cscrypto::fillWithZeros(const_cast(sk58.data()), sk58.size()); cscrypto::fillWithZeros(const_cast(skBytes.data()), skBytes.size()); + if (!written) { + cserror() << "Could not write " << pathToSk << ": keep the seed phrase above to restore the key"; + return false; + } + cslog() << "Keys generated"; break; } diff --git a/client/config/keyfilecrypt.cpp b/client/config/keyfilecrypt.cpp new file mode 100644 index 000000000..f7903edca --- /dev/null +++ b/client/config/keyfilecrypt.cpp @@ -0,0 +1,82 @@ +#include "keyfilecrypt.hpp" + +#include +#include + +namespace cs { +namespace keyfile { + +namespace { +using FileKey = cscrypto::MemGuard; + +// cscrypto's salt (cscrypto/src/privatekey.cpp, getKeyFromPassword) +constexpr std::array kSalt = {0x49, 0x44, 0x49, 0x20, 0x4e, 0x41, 0x48, 0x55, + 0x59, 0x20, 0x42, 0x4c, 0x59, 0x41, 0x54, 0x27}; + +// cscrypto's derivation with its identifiers pinned: Argon2id v1.3 and the argon2id SENSITIVE +// limits are the values of crypto_pwhash_ALG_DEFAULT and crypto_pwhash_OPSLIMIT/MEMLIMIT_SENSITIVE +// it uses. False when the key memory or the derivation's memory cannot be had. +bool deriveKey(FileKey& key, const char* passwd, std::size_t pswdLen) { + return key && crypto_pwhash(key.data(), key.size(), passwd, pswdLen, kSalt.data(), crypto_pwhash_argon2id_OPSLIMIT_SENSITIVE, + crypto_pwhash_argon2id_MEMLIMIT_SENSITIVE, crypto_pwhash_ALG_ARGON2ID13) == 0; +} +} // namespace + +cscrypto::Bytes encryptWithNonce(const cscrypto::PrivateKey& key, const char* passwd, std::size_t pswdLen, const cscrypto::Byte* nonce) { + cscrypto::Bytes result; + if (!key || nonce == nullptr) { + return result; + } + + FileKey fileKey; + if (!deriveKey(fileKey, passwd, pswdLen)) { + return result; + } + + cscrypto::Bytes out(kEncryptedSize); + std::memcpy(out.data(), nonce, kNonceSize); + auto sk = key.access(); + unsigned long long sealedLen = 0; + if (crypto_aead_chacha20poly1305_encrypt(out.data() + kNonceSize, &sealedLen, sk.data(), sk.size(), nullptr, 0, nullptr, out.data(), + fileKey.data()) != 0 || + sealedLen != kSealedSize) { + sodium_memzero(out.data(), out.size()); + return result; + } + + result.swap(out); + return result; +} + +cscrypto::Bytes encrypt(const cscrypto::PrivateKey& key, const char* passwd, std::size_t pswdLen) { + std::array nonce; + randombytes_buf(nonce.data(), nonce.size()); + return encryptWithNonce(key, passwd, pswdLen, nonce.data()); +} + +cscrypto::PrivateKey decrypt(const cscrypto::Bytes& bytes, const char* passwd, std::size_t pswdLen) { + if (bytes.size() != kEncryptedSize) { + return cscrypto::PrivateKey(); + } + + FileKey fileKey; + if (!deriveKey(fileKey, passwd, pswdLen)) { + return cscrypto::PrivateKey(); + } + + cscrypto::MemGuard sk; + if (!sk) { + return cscrypto::PrivateKey(); + } + // the output is exactly 64 bytes, which libsodium also zeroes on a bad tag + unsigned long long skLen = 0; + if (crypto_aead_chacha20poly1305_decrypt(sk.data(), &skLen, nullptr, bytes.data() + kNonceSize, kSealedSize, nullptr, 0, bytes.data(), + fileKey.data()) != 0 || + skLen != cscrypto::kPrivateKeySize) { + return cscrypto::PrivateKey(); + } + return cscrypto::PrivateKey::readFromBytes(sk); +} + +} // namespace keyfile +} // namespace cs diff --git a/client/config/keyfilecrypt.hpp b/client/config/keyfilecrypt.hpp new file mode 100644 index 000000000..0efa1f949 --- /dev/null +++ b/client/config/keyfilecrypt.hpp @@ -0,0 +1,38 @@ +#ifndef CLIENT_CONFIG_KEYFILECRYPT_HPP +#define CLIENT_CONFIG_KEYFILECRYPT_HPP + +#include + +#include + +namespace cs { +namespace keyfile { + +// The encrypted private key file (NodePrivate.txt), decoded from base58: the format of cscrypto's +// PrivateKey::getEncrypted / readFromEncrypted, which every node writes and reads, unchanged: +// +// nonce (8) || crypto_aead_chacha20poly1305 (original construction, no associated data) of the +// 64-byte secret key: ciphertext + tag (64 + 16) = 88 bytes +// +// with the key derived by crypto_pwhash (Argon2id v1.3, OPSLIMIT_SENSITIVE, MEMLIMIT_SENSITIVE) +// and cscrypto's salt. The functions here write and read exactly those bytes; they differ from +// cscrypto's only in their checks: a failed allocation or derivation is an error (an empty result) +// and any other length is refused before decryption. 64 bytes is a plain key. +constexpr std::size_t kNonceSize = crypto_aead_chacha20poly1305_NPUBBYTES; +constexpr std::size_t kSealedSize = cscrypto::kPrivateKeySize + crypto_aead_chacha20poly1305_ABYTES; +constexpr std::size_t kEncryptedSize = kNonceSize + kSealedSize; // 88 + +// a new encryption with a random nonce; empty on failure (no key, or the derivation failed) +cscrypto::Bytes encrypt(const cscrypto::PrivateKey& key, const char* passwd, std::size_t pswdLen); + +// the same with the given nonce (kNonceSize bytes): for the tests, which compare the bytes with +// files written by cscrypto +cscrypto::Bytes encryptWithNonce(const cscrypto::PrivateKey& key, const char* passwd, std::size_t pswdLen, const cscrypto::Byte* nonce); + +// an empty key on a wrong password, a changed file, another length or a failed derivation +cscrypto::PrivateKey decrypt(const cscrypto::Bytes& bytes, const char* passwd, std::size_t pswdLen); + +} // namespace keyfile +} // namespace cs + +#endif // CLIENT_CONFIG_KEYFILECRYPT_HPP diff --git a/docs/CHANGES.md b/docs/CHANGES.md index 9d1b09319..3db147b4f 100644 --- a/docs/CHANGES.md +++ b/docs/CHANGES.md @@ -54,6 +54,7 @@ lines under the new release. | #167 | solver: stage-3 diagnostics at info level, logging only: what this node signed (`stage3 inputs`: sequence, previous hash, timestamp, reward, hashes of the transactions and fees, the three signed hashes), why a peer's stage 3 failed (another block/round hash or a key/message mismatch), the agree/disagree split among the confidants, the keys a round package gray-lists (`OWN KEY` when ours is one), the counts on "not enough active confidants", and the block on "signatures of the block are insufficient" (now a warning); see [consensus-diagnostics.md](consensus-diagnostics.md) | | #168 | solver: the `stage3 inputs` line of #167 is logged at info level only when a stage-3 check fails (once per iteration, before the first `stage3 check failed`), at debug level every round, so a healthy node logs none of the stage-3 diagnostics | | #169 | config: the node writes `NodePrivate.txt` (generated, encrypted or re-encrypted) and the `--dumpkeys` JSON with mode 0600 on POSIX (`open` with 0600 and `fchmod`, which also narrows an existing wider file) instead of `std::ofstream`, which left them 0644 (readable by every user) under the usual umask; `NodePublic.txt` and Windows unchanged | +| #170 | config: safer handling of the encrypted key file (atomic re-encryption, no empty file on failure, clear errors); the file format is unchanged and stays compatible with the official node. Re-encryption (`--encryptkey`, the change of password at start, a new key at first start) writes `NodePrivate.txt.tmp`, flushes it and renames it over the key file (MoveFileEx on Windows), so a crash or a full disk leaves the previous file and the log reports the failure instead of success; a failed encryption never writes an empty key file; a key file of an unexpected length stops the node with "Bad private key file in ... (N bytes)" instead of asking for a password; a failed key derivation is an error instead of a crash; a file used as password is wiped from memory after use | ## community.16 — 2026-11-03 diff --git a/docs/differences.md b/docs/differences.md index 8e895dd57..fcfcf0a25 100644 --- a/docs/differences.md +++ b/docs/differences.md @@ -253,6 +253,16 @@ consensus rules. - the rewards of an uncertain block kept when the trusted mask differs; - the revert of a timed delegation; - uninitialised consensus settings. +- **Encrypted key file.** Safer handling of the encrypted key file (atomic re-encryption, no empty + file on failure, clear errors); the file format is unchanged and stays compatible with the + official node. When the node encrypts or re-encrypts `NodePrivate.txt` (`--encryptkey`, the + change of password offered at start, a new key at the first start) it writes + `NodePrivate.txt.tmp`, flushes it and renames it over the key file, so a crash or a full disk + leaves the previous file, and the log says the write failed instead of reporting success. A + failed encryption never writes an empty key file, a key file of an unexpected length stops the + node with `Bad private key file in ... (N bytes)` instead of asking for a password, a failed key + derivation is an error instead of a crash, and a file used as password is wiped from memory + after use. ## Consensus fixes diff --git a/tests/csnode/CMakeLists.txt b/tests/csnode/CMakeLists.txt index d8c64ad40..4be839c9e 100644 --- a/tests/csnode/CMakeLists.txt +++ b/tests/csnode/CMakeLists.txt @@ -7,6 +7,7 @@ file(GLOB SRCS *.cpp) list(APPEND SRCS "${CMAKE_CURRENT_SOURCE_DIR}/../../client/config/config.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/../../client/config/banner.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/../../client/config/keyfilecrypt.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/../../client/src/dbcheck.cpp" ) @@ -36,6 +37,9 @@ target_link_libraries(${TEST_NAME} ${LINKER_START_GROUP} csdb csconnector solver ) add_test(NAME ${TEST_NAME} - COMMAND ${TEST_NAME}) + COMMAND ${TEST_NAME} --gtest_filter=-KeyFileCrypt.*) +# the key file encryption runs Argon2id with 1 GiB a few times: its own entry, its own timeout +add_test(NAME keyfilecrypt_tests + COMMAND ${TEST_NAME} --gtest_filter=KeyFileCrypt.*) configure_msvc_flags() diff --git a/tests/csnode/keyfilecrypt_tests.cpp b/tests/csnode/keyfilecrypt_tests.cpp new file mode 100644 index 000000000..bb58798ed --- /dev/null +++ b/tests/csnode/keyfilecrypt_tests.cpp @@ -0,0 +1,108 @@ +#include + +#include +#include + +#include +#include + +#include + +// The key file keeps cscrypto's format: these tests compare the bytes with cscrypto's own writer +// and reader (PrivateKey::getEncrypted / readFromEncrypted, the code of the official node). Each +// derivation is Argon2id with 1 GiB: the tests keep their number low. + +namespace { +// a NodePrivate.txt encrypted by cscrypto's PrivateKey::getEncrypted (an earlier node), with the +// password "node password" +const char* kVectorFile = "2goaN1R5N6WKdz9baKJXWovLDccavzzWR25JKeHj9goSRWFtPVC6qRuqjS74e7hvND4hxDJtv3XeZgLQJ6NPoMAy4YWnUxFUghgaizwodzbU4Zaw6wo55fB5i"; +const char* kVectorPublic = "FAe4sisG95oZ42w7buUn5qEE4TAnfTTFPiguZUHmhiF"; +const std::string kVectorPassword = "node password"; + +cscrypto::Bytes decode(const std::string& s) { + std::vector out; + DecodeBase58(s, out); + return out; +} + +std::string publicOf(const cscrypto::PrivateKey& sk) { + auto pk = cscrypto::getMatchingPublic(sk); + return EncodeBase58(pk.data(), pk.data() + pk.size()); +} + +class KeyFileCrypt : public ::testing::Test { +protected: + void SetUp() override { + ASSERT_TRUE(cscrypto::cryptoInit()); + sk_ = cscrypto::PrivateKey::generateWithPair(pk_); + } + + cscrypto::PrivateKey sk_; + cscrypto::PublicKey pk_; +}; +} // namespace + +TEST_F(KeyFileCrypt, Size) { + EXPECT_EQ(cs::keyfile::kEncryptedSize, 88u); +} + +// a file cscrypto wrote opens, and encrypting its key again with the same password and nonce gives +// the same bytes: the derivation, the cipher and the layout are cscrypto's +TEST_F(KeyFileCrypt, ByteIdenticalToCscryptoVector) { + const auto bytes = decode(kVectorFile); + ASSERT_EQ(bytes.size(), cs::keyfile::kEncryptedSize); + auto sk = cs::keyfile::decrypt(bytes, kVectorPassword.data(), kVectorPassword.size()); + ASSERT_TRUE(sk); + EXPECT_EQ(publicOf(sk), kVectorPublic); + + const auto again = cs::keyfile::encryptWithNonce(sk, kVectorPassword.data(), kVectorPassword.size(), bytes.data()); + EXPECT_EQ(again, bytes); + EXPECT_EQ(EncodeBase58(again.data(), again.data() + again.size()), kVectorFile); +} + +// each way with cscrypto's code: what this node writes, cscrypto's reader opens (the official +// node's reader), and what cscrypto writes, this node opens; a new nonce every time +TEST_F(KeyFileCrypt, CscryptoReadsOursAndWeReadCscrypto) { + const std::string pw = "round trip ~ 42"; + const auto ours = cs::keyfile::encrypt(sk_, pw.data(), pw.size()); + ASSERT_EQ(ours.size(), cs::keyfile::kEncryptedSize); + auto byCscrypto = cscrypto::PrivateKey::readFromEncrypted(ours, pw.data(), pw.size()); + ASSERT_TRUE(byCscrypto); + EXPECT_EQ(cscrypto::getMatchingPublic(byCscrypto), pk_); + + const auto theirs = sk_.getEncrypted(pw.data(), pw.size()); + ASSERT_EQ(theirs.size(), cs::keyfile::kEncryptedSize); + EXPECT_NE(cscrypto::Bytes(ours.begin(), ours.begin() + cs::keyfile::kNonceSize), + cscrypto::Bytes(theirs.begin(), theirs.begin() + cs::keyfile::kNonceSize)); + const std::string text = EncodeBase58(theirs.data(), theirs.data() + theirs.size()); + auto byUs = cs::keyfile::decrypt(decode(text), pw.data(), pw.size()); + ASSERT_TRUE(byUs); + EXPECT_EQ(cscrypto::getMatchingPublic(byUs), pk_); +} + +TEST_F(KeyFileCrypt, WrongPasswordAndChangedByteRefused) { + const auto bytes = decode(kVectorFile); + const std::string wrong = "node passwore"; + EXPECT_FALSE(cs::keyfile::decrypt(bytes, wrong.data(), wrong.size())); + + auto changed = bytes; + changed[cs::keyfile::kNonceSize + 10] ^= 1; // the ciphertext: the tag does not verify + EXPECT_FALSE(cs::keyfile::decrypt(changed, kVectorPassword.data(), kVectorPassword.size())); +} + +// another length is not an encrypted key: refused before any derivation +TEST_F(KeyFileCrypt, OtherLengthsRefused) { + const std::string pw = "pw"; + for (std::size_t n : {0u, 8u, 64u, 72u, 87u, 89u, 96u, 104u, 128u}) { + cscrypto::Bytes bytes(n, 1); + EXPECT_FALSE(cs::keyfile::decrypt(bytes, pw.data(), pw.size())) << n; + } +} + +// a failed derivation (here refused at once by Argon2id: no password bytes for a length of 5, as an +// allocation failure would be) is an error, never an empty file nor a crash, in both directions +TEST_F(KeyFileCrypt, FailedDerivationIsAnError) { + EXPECT_TRUE(cs::keyfile::encrypt(sk_, nullptr, 5).empty()); + EXPECT_TRUE(cs::keyfile::encrypt(cscrypto::PrivateKey(), "pw", 2).empty()); + EXPECT_FALSE(cs::keyfile::decrypt(decode(kVectorFile), nullptr, 5)); +}