From 649d9c40a0bf76d481183aa44598e985b73a97d2 Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Wed, 4 Nov 2026 17:44:58 +0100 Subject: [PATCH 1/8] config: the key file encryption uses a random salt per file A new encryption of NodePrivate.txt (--encryptkey, "[1] Encrypt with password" at the first start, the change of password at start) now writes base58(salt (16 random bytes) || nonce (8 random bytes) || crypto_aead_chacha20poly1305 ciphertext and tag (80 bytes)), 104 bytes decoded. The key is crypto_pwhash with the same parameters as before (Argon2id, OPSLIMIT_SENSITIVE, MEMLIMIT_SENSITIVE) and the file's own salt. The salt and nonce come from randombytes_buf; no associated data: the format is told by its length. Reading tells the formats apart by the decoded length: 88 bytes is the format of older versions, opened by cscrypto's PrivateKey::readFromEncrypted as before and never rewritten; 104 is the new one; any other length does not open (64 is a plain key, unchanged). Prompts, retries and the file-as-password mode are unchanged. The code lives in the node (client/config/keyfilecrypt.cpp), so the cscrypto submodule is not changed. A failed encryption (e.g. Argon2id unable to allocate its memory) now returns an error instead of an empty buffer, so the key file is never overwritten with an empty line. Only the local key file is concerned: nothing on the wire, in storage or in consensus. Co-Authored-By: Claude Opus 5.5 --- client/config/CMakeLists.txt | 2 + client/config/config.cpp | 13 ++-- client/config/keyfilecrypt.cpp | 78 ++++++++++++++++++++ client/config/keyfilecrypt.hpp | 40 +++++++++++ docs/differences.md | 9 +++ tests/csnode/CMakeLists.txt | 1 + tests/csnode/keyfilecrypt_tests.cpp | 108 ++++++++++++++++++++++++++++ 7 files changed, 245 insertions(+), 6 deletions(-) create mode 100644 client/config/keyfilecrypt.cpp create mode 100644 client/config/keyfilecrypt.hpp create mode 100644 tests/csnode/keyfilecrypt_tests.cpp 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..d7710808a 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 @@ -449,8 +450,8 @@ static bool encryptWithPassword(const cscrypto::PrivateKey& sk, std::vector if (!getBufFromFile(buf)) { return false; } - skBytes = sk.getEncrypted(buf.data(), buf.size()); - return true; + skBytes = cs::keyfile::encrypt(sk, buf.data(), buf.size()); + return !skBytes.empty(); // a failed derivation (e.g. no memory) never writes an empty key file } static bool usePassword() { @@ -654,14 +655,14 @@ 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()); } if (!privateKey_) { diff --git a/client/config/keyfilecrypt.cpp b/client/config/keyfilecrypt.cpp new file mode 100644 index 000000000..850a04ea2 --- /dev/null +++ b/client/config/keyfilecrypt.cpp @@ -0,0 +1,78 @@ +#include "keyfilecrypt.hpp" + +#include + +namespace cs { +namespace keyfile { + +namespace { +using FileKey = cscrypto::MemGuard; + +// the same derivation as cscrypto's, with the file's own salt +bool deriveKey(FileKey& key, const char* passwd, std::size_t pswdLen, const cscrypto::Byte* salt) { + return key && crypto_pwhash(key.data(), key.size(), passwd, pswdLen, salt, crypto_pwhash_OPSLIMIT_SENSITIVE, + crypto_pwhash_MEMLIMIT_SENSITIVE, crypto_pwhash_ALG_DEFAULT) == 0; +} +} // namespace + +cscrypto::Bytes encrypt(const cscrypto::PrivateKey& key, const char* passwd, std::size_t pswdLen) { + cscrypto::Bytes result; + if (!key) { + return result; + } + + cscrypto::Bytes out(kSaltedEncryptedSize); + cscrypto::Byte* salt = out.data(); + cscrypto::Byte* nonce = salt + kSaltSize; + cscrypto::Byte* sealed = nonce + kNonceSize; + randombytes_buf(salt, kSaltSize); + randombytes_buf(nonce, kNonceSize); + + FileKey fileKey; + if (!deriveKey(fileKey, passwd, pswdLen, salt)) { + return result; + } + + auto sk = key.access(); + unsigned long long sealedLen = 0; + if (crypto_aead_chacha20poly1305_encrypt(sealed, &sealedLen, sk.data(), sk.size(), nullptr, 0, nullptr, nonce, fileKey.data()) != 0 || + sealedLen != kSealedSize) { + sodium_memzero(out.data(), out.size()); + return result; + } + + result.swap(out); + return result; +} + +cscrypto::PrivateKey decrypt(const cscrypto::Bytes& bytes, const char* passwd, std::size_t pswdLen) { + if (bytes.size() == kLegacyEncryptedSize) { + return cscrypto::PrivateKey::readFromEncrypted(bytes, passwd, pswdLen); + } + if (bytes.size() != kSaltedEncryptedSize) { + return cscrypto::PrivateKey(); + } + + const cscrypto::Byte* salt = bytes.data(); + const cscrypto::Byte* nonce = salt + kSaltSize; + const cscrypto::Byte* sealed = nonce + kNonceSize; + + FileKey fileKey; + if (!deriveKey(fileKey, passwd, pswdLen, salt)) { + return cscrypto::PrivateKey(); + } + + cscrypto::MemGuard sk; + if (!sk) { + return cscrypto::PrivateKey(); + } + unsigned long long skLen = 0; + if (crypto_aead_chacha20poly1305_decrypt(sk.data(), &skLen, nullptr, sealed, kSealedSize, nullptr, 0, nonce, 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..4f715a645 --- /dev/null +++ b/client/config/keyfilecrypt.hpp @@ -0,0 +1,40 @@ +#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 two formats are told +// apart by their length: +// +// legacy (88 bytes): nonce (8) || ciphertext + tag (64 + 16) +// written by older versions and the official node: cscrypto's +// PrivateKey::getEncrypted, key = Argon2id with a salt that is the same for +// every file. Read as before, never rewritten. +// salted (104 bytes): salt (16) || nonce (8) || ciphertext + tag (64 + 16) +// written by this version: key = crypto_pwhash (Argon2id, OPSLIMIT_SENSITIVE, +// MEMLIMIT_SENSITIVE) with a random salt per file, then the same +// crypto_aead_chacha20poly1305 (original construction, 8-byte nonce, no +// associated data) as the legacy format. +// +// Any other length is not an encrypted key (64 bytes is a plain key). +constexpr std::size_t kSaltSize = crypto_pwhash_SALTBYTES; +constexpr std::size_t kNonceSize = crypto_aead_chacha20poly1305_NPUBBYTES; +constexpr std::size_t kSealedSize = cscrypto::kPrivateKeySize + crypto_aead_chacha20poly1305_ABYTES; +constexpr std::size_t kLegacyEncryptedSize = kNonceSize + kSealedSize; // 88 +constexpr std::size_t kSaltedEncryptedSize = kSaltSize + kNonceSize + kSealedSize; // 104 + +// the salted format for a new encryption; empty on failure +cscrypto::Bytes encrypt(const cscrypto::PrivateKey& key, const char* passwd, std::size_t pswdLen); + +// either format by its length; an empty key on a wrong password, a changed file or another length +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/differences.md b/docs/differences.md index 8e895dd57..a773e823f 100644 --- a/docs/differences.md +++ b/docs/differences.md @@ -253,6 +253,15 @@ 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.** The key file encryption (`--encryptkey`, the "[1] Encrypt with password" + choice at the first start, and the change of password offered at start) now uses a random salt + per file: `NodePrivate.txt` is base58 of the salt (16 bytes), the nonce (8 bytes) and the + encrypted key with its tag (80 bytes), 104 bytes once decoded, with the same Argon2id parameters + and cipher as before. Files encrypted by older versions (88 bytes) are read as before and are + never rewritten by themselves; a plain key (64 bytes) is unchanged. A file encrypted by this + version cannot be opened by older community nodes or by the official node until they read the + new format, so to go back to one of them keep the plain key (or the seed phrase), or encrypt the + plain key again with that node. A failed encryption no longer writes an empty key file. ## Consensus fixes diff --git a/tests/csnode/CMakeLists.txt b/tests/csnode/CMakeLists.txt index d8c64ad40..1c7a12596 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" ) diff --git a/tests/csnode/keyfilecrypt_tests.cpp b/tests/csnode/keyfilecrypt_tests.cpp new file mode 100644 index 000000000..eb4c8307d --- /dev/null +++ b/tests/csnode/keyfilecrypt_tests.cpp @@ -0,0 +1,108 @@ +#include + +#include +#include + +#include +#include + +#include + +// Each derivation is the node's Argon2id with 1 GiB of memory: the tests keep their number low. + +namespace { +// a NodePrivate.txt encrypted by the node's previous code (cscrypto's PrivateKey::getEncrypted), +// with the key below and the password "node password" +const char* kLegacyFile = "2goaN1R5N6WKdz9baKJXWovLDccavzzWR25JKeHj9goSRWFtPVC6qRuqjS74e7hvND4hxDJtv3XeZgLQJ6NPoMAy4YWnUxFUghgaizwodzbU4Zaw6wo55fB5i"; +const char* kLegacyPublic = "FAe4sisG95oZ42w7buUn5qEE4TAnfTTFPiguZUHmhiF"; +const std::string kLegacyPassword = "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, SizesOfTheTwoFormats) { + EXPECT_EQ(cs::keyfile::kLegacyEncryptedSize, 88u); + EXPECT_EQ(cs::keyfile::kSaltedEncryptedSize, 104u); +} + +// a file written by older versions (or the official node) opens as before +TEST_F(KeyFileCrypt, LegacyFileOpens) { + const auto bytes = decode(kLegacyFile); + ASSERT_EQ(bytes.size(), cs::keyfile::kLegacyEncryptedSize); + auto sk = cs::keyfile::decrypt(bytes, kLegacyPassword.data(), kLegacyPassword.size()); + ASSERT_TRUE(sk); + EXPECT_EQ(publicOf(sk), kLegacyPublic); +} + +// a new encryption: 104 bytes, a random salt and nonce each time, opens with its password only +TEST_F(KeyFileCrypt, NewFormatRoundTrip) { + const std::string pw = "round trip ~ 42"; + const auto a = cs::keyfile::encrypt(sk_, pw.data(), pw.size()); + const auto b = cs::keyfile::encrypt(sk_, pw.data(), pw.size()); + ASSERT_EQ(a.size(), cs::keyfile::kSaltedEncryptedSize); + ASSERT_EQ(b.size(), cs::keyfile::kSaltedEncryptedSize); + EXPECT_NE(cscrypto::Bytes(a.begin(), a.begin() + cs::keyfile::kSaltSize), cscrypto::Bytes(b.begin(), b.begin() + cs::keyfile::kSaltSize)); + EXPECT_NE(a, b); + + auto sk = cs::keyfile::decrypt(a, pw.data(), pw.size()); + ASSERT_TRUE(sk); + EXPECT_EQ(cscrypto::getMatchingPublic(sk), pk_); + + // the base58 text the node writes and reads back + const std::string text = EncodeBase58(b.data(), b.data() + b.size()); + auto sk2 = cs::keyfile::decrypt(decode(text), pw.data(), pw.size()); + ASSERT_TRUE(sk2); + EXPECT_EQ(cscrypto::getMatchingPublic(sk2), pk_); +} + +TEST_F(KeyFileCrypt, WrongPasswordAndChangedSaltRefused) { + const std::string pw = "the password"; + const auto enc = cs::keyfile::encrypt(sk_, pw.data(), pw.size()); + ASSERT_EQ(enc.size(), cs::keyfile::kSaltedEncryptedSize); + + const std::string wrong = "the passwore"; + EXPECT_FALSE(cs::keyfile::decrypt(enc, wrong.data(), wrong.size())); + + auto badSalt = enc; + badSalt[3] ^= 1; + EXPECT_FALSE(cs::keyfile::decrypt(badSalt, pw.data(), pw.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, 103u, 105u, 128u}) { + cscrypto::Bytes bytes(n, 1); + EXPECT_FALSE(cs::keyfile::decrypt(bytes, pw.data(), pw.size())) << n; + } +} + +// the old writer's output is still read (the file is not converted) +TEST_F(KeyFileCrypt, LegacyWriterOutputOpens) { + const std::string pw = "legacy"; + const auto enc = sk_.getEncrypted(pw.data(), pw.size()); + ASSERT_EQ(enc.size(), cs::keyfile::kLegacyEncryptedSize); + auto sk = cs::keyfile::decrypt(enc, pw.data(), pw.size()); + ASSERT_TRUE(sk); + EXPECT_EQ(cscrypto::getMatchingPublic(sk), pk_); +} From 580e839bde6ea9c5cad816efe020e7931060af05 Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Wed, 4 Nov 2026 17:45:22 +0100 Subject: [PATCH 2/8] docs: CHANGES row for #170 Co-Authored-By: Claude Opus 5.5 --- docs/CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/CHANGES.md b/docs/CHANGES.md index 9d1b09319..aafc6a459 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: the key file encryption now uses a random salt per file (`NodePrivate.txt` of a new encryption: salt, nonce and encrypted key, 104 bytes decoded, same Argon2id parameters and cipher); files encrypted by older versions (88 bytes) are read as before and never rewritten by themselves. A file encrypted by this version cannot be opened by older or official nodes until they read the new format: to downgrade, keep the plain key or encrypt it again with the older node. A failed encryption no longer writes an empty key file | ## community.16 — 2026-11-03 From e774992abd8272996ad8a85e1b612f3573208dd9 Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Wed, 4 Nov 2026 18:02:13 +0100 Subject: [PATCH 3/8] tests: key file encryption tests in their own ctest entry, fewer derivations Each derivation is Argon2id with 1 GiB (about 5 s here): the tests share their encryptions and run as keyfilecrypt_tests, so nodetests keeps its time within the per-test timeout. Co-Authored-By: Claude Opus 5.5 --- tests/csnode/CMakeLists.txt | 5 ++++- tests/csnode/keyfilecrypt_tests.cpp | 27 +++++++++------------------ 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/tests/csnode/CMakeLists.txt b/tests/csnode/CMakeLists.txt index 1c7a12596..4be839c9e 100644 --- a/tests/csnode/CMakeLists.txt +++ b/tests/csnode/CMakeLists.txt @@ -37,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 index eb4c8307d..45a674bc6 100644 --- a/tests/csnode/keyfilecrypt_tests.cpp +++ b/tests/csnode/keyfilecrypt_tests.cpp @@ -54,8 +54,9 @@ TEST_F(KeyFileCrypt, LegacyFileOpens) { EXPECT_EQ(publicOf(sk), kLegacyPublic); } -// a new encryption: 104 bytes, a random salt and nonce each time, opens with its password only -TEST_F(KeyFileCrypt, NewFormatRoundTrip) { +// a new encryption: 104 bytes, a random salt and nonce each time, opens with its password only, +// and not with a changed salt +TEST_F(KeyFileCrypt, NewFormatRoundTripWrongPasswordChangedSalt) { const std::string pw = "round trip ~ 42"; const auto a = cs::keyfile::encrypt(sk_, pw.data(), pw.size()); const auto b = cs::keyfile::encrypt(sk_, pw.data(), pw.size()); @@ -64,26 +65,16 @@ TEST_F(KeyFileCrypt, NewFormatRoundTrip) { EXPECT_NE(cscrypto::Bytes(a.begin(), a.begin() + cs::keyfile::kSaltSize), cscrypto::Bytes(b.begin(), b.begin() + cs::keyfile::kSaltSize)); EXPECT_NE(a, b); - auto sk = cs::keyfile::decrypt(a, pw.data(), pw.size()); + // the base58 text the node writes and reads back + const std::string text = EncodeBase58(a.data(), a.data() + a.size()); + auto sk = cs::keyfile::decrypt(decode(text), pw.data(), pw.size()); ASSERT_TRUE(sk); EXPECT_EQ(cscrypto::getMatchingPublic(sk), pk_); - // the base58 text the node writes and reads back - const std::string text = EncodeBase58(b.data(), b.data() + b.size()); - auto sk2 = cs::keyfile::decrypt(decode(text), pw.data(), pw.size()); - ASSERT_TRUE(sk2); - EXPECT_EQ(cscrypto::getMatchingPublic(sk2), pk_); -} - -TEST_F(KeyFileCrypt, WrongPasswordAndChangedSaltRefused) { - const std::string pw = "the password"; - const auto enc = cs::keyfile::encrypt(sk_, pw.data(), pw.size()); - ASSERT_EQ(enc.size(), cs::keyfile::kSaltedEncryptedSize); - - const std::string wrong = "the passwore"; - EXPECT_FALSE(cs::keyfile::decrypt(enc, wrong.data(), wrong.size())); + const std::string wrong = "round trip ~ 43"; + EXPECT_FALSE(cs::keyfile::decrypt(a, wrong.data(), wrong.size())); - auto badSalt = enc; + auto badSalt = a; badSalt[3] ^= 1; EXPECT_FALSE(cs::keyfile::decrypt(badSalt, pw.data(), pw.size())); } From d0103f1575fd7e8d144103a51ce7dc28c1371a75 Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Wed, 4 Nov 2026 18:09:07 +0100 Subject: [PATCH 4/8] docs: an older node crashes on the new key file; other lengths refused Co-Authored-By: Claude Opus 5.5 --- docs/CHANGES.md | 2 +- docs/differences.md | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/CHANGES.md b/docs/CHANGES.md index aafc6a459..df7c4fd1c 100644 --- a/docs/CHANGES.md +++ b/docs/CHANGES.md @@ -54,7 +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: the key file encryption now uses a random salt per file (`NodePrivate.txt` of a new encryption: salt, nonce and encrypted key, 104 bytes decoded, same Argon2id parameters and cipher); files encrypted by older versions (88 bytes) are read as before and never rewritten by themselves. A file encrypted by this version cannot be opened by older or official nodes until they read the new format: to downgrade, keep the plain key or encrypt it again with the older node. A failed encryption no longer writes an empty key file | +| #170 | config: the key file encryption now uses a random salt per file (`NodePrivate.txt` of a new encryption: salt, nonce and encrypted key, 104 bytes decoded, same Argon2id parameters and cipher); files encrypted by older versions (88 bytes) are read as before and never rewritten by themselves. A file encrypted by this version cannot be opened by older or official nodes until they read the new format (they crash on it): to downgrade, keep the plain key or encrypt it again with the older node. Other lengths are refused before decryption (older versions crashed on a file longer than 88 bytes); a failed encryption no longer writes an empty key file | ## community.16 — 2026-11-03 diff --git a/docs/differences.md b/docs/differences.md index a773e823f..5a62cfa83 100644 --- a/docs/differences.md +++ b/docs/differences.md @@ -260,8 +260,10 @@ consensus rules. and cipher as before. Files encrypted by older versions (88 bytes) are read as before and are never rewritten by themselves; a plain key (64 bytes) is unchanged. A file encrypted by this version cannot be opened by older community nodes or by the official node until they read the - new format, so to go back to one of them keep the plain key (or the seed phrase), or encrypt the - plain key again with that node. A failed encryption no longer writes an empty key file. + new format (they stop with a crash when they try to open it), so to go back to one of them keep + the plain key (or the seed phrase), or encrypt the plain key again with that node. An encrypted + file of any other length is refused before decryption (older versions crashed on one longer than + 88 bytes), and a failed encryption no longer writes an empty key file. ## Consensus fixes From f5fd9d1214d37394463ae318517ea344759639ec Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Wed, 4 Nov 2026 20:04:57 +0100 Subject: [PATCH 5/8] config: atomic key file write, pinned Argon2id, legacy read in the node (review M1, L1-L5) - M1: the key file is written to NAME.tmp (0600, O_NOFOLLOW), fsync'ed, renamed over NAME (a link is followed, its target replaced) and the folder fsync'ed; on Windows CreateFile, FlushFileBuffers and MoveFileEx(REPLACE_EXISTING | WRITE_THROUGH). Every return value is checked: on failure the old file stays and an error is logged instead of the success line (re-encryption, --encryptkey, a new key at first start, --dumpkeys). - L1: crypto_pwhash_ALG_ARGON2ID13 with the argon2id OPSLIMIT/MEMLIMIT_SENSITIVE, the values the generic aliases had: no format change. - L2: a decoded length other than 64, 88 or 104 stops once with "Bad private key file in ... (N bytes)" before any prompt. - L3: the legacy format is read in keyfilecrypt.cpp with the same derivation and cipher, the key allocation and the derivation checked, so a failed derivation is an error instead of a null dereference in cscrypto's reader; legacy files are still never rewritten. - L4: a file used as password is read straight into its buffer and wiped after use. - L5: tests for a changed ciphertext byte of a 104-byte file and for a failed derivation (both directions: empty encryption, no key, no crash). Co-Authored-By: Claude Opus 5.5 --- client/config/config.cpp | 140 ++++++++++++++++++++++------ client/config/keyfilecrypt.cpp | 62 ++++++------ client/config/keyfilecrypt.hpp | 12 ++- docs/CHANGES.md | 2 +- tests/csnode/keyfilecrypt_tests.cpp | 15 +++ 5 files changed, 170 insertions(+), 61 deletions(-) diff --git a/client/config/config.cpp b/client/config/config.cpp index d7710808a..f95d57edd 100644 --- a/client/config/config.cpp +++ b/client/config/config.cpp @@ -32,6 +32,7 @@ #include #include #include +#include #include #endif @@ -209,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 { @@ -242,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()); @@ -471,18 +515,36 @@ static bool getBufFromFile(std::string& buf) { } } } - std::stringstream ss; - ss << f.rdbuf(); - buf = ss.str(); + // read straight into buf (no intermediate copy), which the caller wipes after use + f.seekg(0, std::ios::end); + const auto size = f.tellg(); + f.seekg(0, std::ios::beg); + if (size < 0 || !f.good()) { + return false; + } + buf.resize(static_cast(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 = 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 } @@ -605,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"; } @@ -638,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::kLegacyEncryptedSize && sk.size() != cs::keyfile::kSaltedEncryptedSize) { + cserror() << "Bad private key file in " << pathToSk << " (" << sk.size() << " bytes)"; + return false; + } encFlag = true; callShowKeys = true; } @@ -663,6 +734,7 @@ bool Config::readKeys(const std::string& pathToPk, const std::string& pathToSk, return false; } privateKey_ = cs::keyfile::decrypt(sk, buf.data(), buf.size()); + wipe(buf); } if (!privateKey_) { @@ -689,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"; @@ -754,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 index 850a04ea2..699b0f23e 100644 --- a/client/config/keyfilecrypt.cpp +++ b/client/config/keyfilecrypt.cpp @@ -1,5 +1,6 @@ #include "keyfilecrypt.hpp" +#include #include namespace cs { @@ -8,10 +9,38 @@ namespace keyfile { namespace { using FileKey = cscrypto::MemGuard; -// the same derivation as cscrypto's, with the file's own salt +// the salt of the legacy format, as cscrypto's PrivateKey::getEncrypted uses it +constexpr std::array kLegacySalt = {0x49, 0x44, 0x49, 0x20, 0x4e, 0x41, 0x48, 0x55, + 0x59, 0x20, 0x42, 0x4c, 0x59, 0x41, 0x54, 0x27}; + +// Argon2id v1.3 with the SENSITIVE limits, pinned (the values of the generic crypto_pwhash +// defaults that both formats were written with); false when the key memory or the derivation's +// memory cannot be had bool deriveKey(FileKey& key, const char* passwd, std::size_t pswdLen, const cscrypto::Byte* salt) { - return key && crypto_pwhash(key.data(), key.size(), passwd, pswdLen, salt, crypto_pwhash_OPSLIMIT_SENSITIVE, - crypto_pwhash_MEMLIMIT_SENSITIVE, crypto_pwhash_ALG_DEFAULT) == 0; + return key && crypto_pwhash(key.data(), key.size(), passwd, pswdLen, salt, crypto_pwhash_argon2id_OPSLIMIT_SENSITIVE, + crypto_pwhash_argon2id_MEMLIMIT_SENSITIVE, crypto_pwhash_ALG_ARGON2ID13) == 0; +} + +// nonce || ciphertext and tag, opened with the key derived from salt +cscrypto::PrivateKey open(const cscrypto::Byte* salt, const cscrypto::Byte* nonce, const char* passwd, std::size_t pswdLen) { + const cscrypto::Byte* sealed = nonce + kNonceSize; + + FileKey fileKey; + if (!deriveKey(fileKey, passwd, pswdLen, salt)) { + return cscrypto::PrivateKey(); + } + + cscrypto::MemGuard sk; + if (!sk) { + return cscrypto::PrivateKey(); + } + // the output is exactly kSealedSize - ABYTES = 64 bytes: libsodium zeroes that many on a bad tag + unsigned long long skLen = 0; + if (crypto_aead_chacha20poly1305_decrypt(sk.data(), &skLen, nullptr, sealed, kSealedSize, nullptr, 0, nonce, fileKey.data()) != 0 || + skLen != cscrypto::kPrivateKeySize) { + return cscrypto::PrivateKey(); + } + return cscrypto::PrivateKey::readFromBytes(sk); } } // namespace @@ -47,31 +76,12 @@ cscrypto::Bytes encrypt(const cscrypto::PrivateKey& key, const char* passwd, std cscrypto::PrivateKey decrypt(const cscrypto::Bytes& bytes, const char* passwd, std::size_t pswdLen) { if (bytes.size() == kLegacyEncryptedSize) { - return cscrypto::PrivateKey::readFromEncrypted(bytes, passwd, pswdLen); + return open(kLegacySalt.data(), bytes.data(), passwd, pswdLen); } - if (bytes.size() != kSaltedEncryptedSize) { - return cscrypto::PrivateKey(); - } - - const cscrypto::Byte* salt = bytes.data(); - const cscrypto::Byte* nonce = salt + kSaltSize; - const cscrypto::Byte* sealed = nonce + kNonceSize; - - FileKey fileKey; - if (!deriveKey(fileKey, passwd, pswdLen, salt)) { - return cscrypto::PrivateKey(); + if (bytes.size() == kSaltedEncryptedSize) { + return open(bytes.data(), bytes.data() + kSaltSize, passwd, pswdLen); } - - cscrypto::MemGuard sk; - if (!sk) { - return cscrypto::PrivateKey(); - } - unsigned long long skLen = 0; - if (crypto_aead_chacha20poly1305_decrypt(sk.data(), &skLen, nullptr, sealed, kSealedSize, nullptr, 0, nonce, fileKey.data()) != 0 || - skLen != cscrypto::kPrivateKeySize) { - return cscrypto::PrivateKey(); - } - return cscrypto::PrivateKey::readFromBytes(sk); + return cscrypto::PrivateKey(); } } // namespace keyfile diff --git a/client/config/keyfilecrypt.hpp b/client/config/keyfilecrypt.hpp index 4f715a645..c4f3fd7fc 100644 --- a/client/config/keyfilecrypt.hpp +++ b/client/config/keyfilecrypt.hpp @@ -14,10 +14,11 @@ namespace keyfile { // legacy (88 bytes): nonce (8) || ciphertext + tag (64 + 16) // written by older versions and the official node: cscrypto's // PrivateKey::getEncrypted, key = Argon2id with a salt that is the same for -// every file. Read as before, never rewritten. +// every file. Read with the same derivation and cipher (here, so that a +// failed derivation is an error), never rewritten. // salted (104 bytes): salt (16) || nonce (8) || ciphertext + tag (64 + 16) -// written by this version: key = crypto_pwhash (Argon2id, OPSLIMIT_SENSITIVE, -// MEMLIMIT_SENSITIVE) with a random salt per file, then the same +// written by this version: key = crypto_pwhash (Argon2id v1.3, the argon2id +// OPSLIMIT_SENSITIVE and MEMLIMIT_SENSITIVE) with a random salt per file, then the same // crypto_aead_chacha20poly1305 (original construction, 8-byte nonce, no // associated data) as the legacy format. // @@ -28,10 +29,11 @@ constexpr std::size_t kSealedSize = cscrypto::kPrivateKeySize + crypto_aead_chac constexpr std::size_t kLegacyEncryptedSize = kNonceSize + kSealedSize; // 88 constexpr std::size_t kSaltedEncryptedSize = kSaltSize + kNonceSize + kSealedSize; // 104 -// the salted format for a new encryption; empty on failure +// the salted format for a new encryption; empty on failure (no key, or the derivation failed) cscrypto::Bytes encrypt(const cscrypto::PrivateKey& key, const char* passwd, std::size_t pswdLen); -// either format by its length; an empty key on a wrong password, a changed file or another length +// either format by its length; 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 diff --git a/docs/CHANGES.md b/docs/CHANGES.md index df7c4fd1c..21d7f003e 100644 --- a/docs/CHANGES.md +++ b/docs/CHANGES.md @@ -54,7 +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: the key file encryption now uses a random salt per file (`NodePrivate.txt` of a new encryption: salt, nonce and encrypted key, 104 bytes decoded, same Argon2id parameters and cipher); files encrypted by older versions (88 bytes) are read as before and never rewritten by themselves. A file encrypted by this version cannot be opened by older or official nodes until they read the new format (they crash on it): to downgrade, keep the plain key or encrypt it again with the older node. Other lengths are refused before decryption (older versions crashed on a file longer than 88 bytes); a failed encryption no longer writes an empty key file | +| #170 | config: the key file encryption now uses a random salt per file (`NodePrivate.txt` of a new encryption: salt, nonce and encrypted key, 104 bytes decoded, same Argon2id parameters and cipher); files encrypted by older versions (88 bytes) are read as before and never rewritten by themselves. A file encrypted by this version cannot be opened by older or official nodes until they read the new format (they crash on it): to downgrade, keep the plain key or encrypt it again with the older node. Other lengths stop the node at once with "Bad private key file in ... (N bytes)" (older versions asked for the password, and crashed on a file longer than 88 bytes); a failed encryption or derivation is an error, never an empty key file; the key file is replaced atomically (`NodePrivate.txt.tmp` flushed, then renamed over it; MoveFileEx on Windows), so a crash or a full disk leaves the previous file and the log reports the failure; a key file used as password is wiped from memory after use | ## community.16 — 2026-11-03 diff --git a/tests/csnode/keyfilecrypt_tests.cpp b/tests/csnode/keyfilecrypt_tests.cpp index 45a674bc6..c6028fb3a 100644 --- a/tests/csnode/keyfilecrypt_tests.cpp +++ b/tests/csnode/keyfilecrypt_tests.cpp @@ -77,6 +77,21 @@ TEST_F(KeyFileCrypt, NewFormatRoundTripWrongPasswordChangedSalt) { auto badSalt = a; badSalt[3] ^= 1; EXPECT_FALSE(cs::keyfile::decrypt(badSalt, pw.data(), pw.size())); + + // a byte changed past the salt (the ciphertext): the tag does not verify + auto badSealed = a; + badSealed[cs::keyfile::kSaltSize + cs::keyfile::kNonceSize + 10] ^= 1; + EXPECT_FALSE(cs::keyfile::decrypt(badSealed, pw.data(), pw.size())); +} + +// 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(kLegacyFile), nullptr, 5)); + cscrypto::Bytes salted(cs::keyfile::kSaltedEncryptedSize, 1); + EXPECT_FALSE(cs::keyfile::decrypt(salted, nullptr, 5)); } // another length is not an encrypted key: refused before any derivation From c5162c2fefbeca4644814d39d3a844d04da2e83b Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Wed, 4 Nov 2026 20:05:10 +0100 Subject: [PATCH 6/8] docs: differences entry for the atomic key file write and the length check Co-Authored-By: Claude Opus 5.5 --- docs/differences.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/differences.md b/docs/differences.md index 5a62cfa83..2de414300 100644 --- a/docs/differences.md +++ b/docs/differences.md @@ -262,8 +262,11 @@ consensus rules. version cannot be opened by older community nodes or by the official node until they read the new format (they stop with a crash when they try to open it), so to go back to one of them keep the plain key (or the seed phrase), or encrypt the plain key again with that node. An encrypted - file of any other length is refused before decryption (older versions crashed on one longer than - 88 bytes), and a failed encryption no longer writes an empty key file. + file of any other length stops the node at once with `Bad private key file in ... (N bytes)` + (older versions asked for the password and crashed on one longer than 88 bytes). A failed + encryption no longer writes an empty key file, and the key file is replaced atomically + (`NodePrivate.txt.tmp`, flushed, then renamed over it): a crash or a full disk leaves the previous + file, and the log says the write failed instead of reporting success. ## Consensus fixes From 6a603a831a8f611ece8c706acd529cfd800ccd2a Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Wed, 4 Nov 2026 20:10:22 +0100 Subject: [PATCH 7/8] config: keyfilecrypt.hpp comment reflowed Co-Authored-By: Claude Opus 5.5 --- client/config/keyfilecrypt.hpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/client/config/keyfilecrypt.hpp b/client/config/keyfilecrypt.hpp index c4f3fd7fc..1055dea00 100644 --- a/client/config/keyfilecrypt.hpp +++ b/client/config/keyfilecrypt.hpp @@ -13,14 +13,15 @@ namespace keyfile { // // legacy (88 bytes): nonce (8) || ciphertext + tag (64 + 16) // written by older versions and the official node: cscrypto's -// PrivateKey::getEncrypted, key = Argon2id with a salt that is the same for -// every file. Read with the same derivation and cipher (here, so that a -// failed derivation is an error), never rewritten. +// PrivateKey::getEncrypted, +// key = Argon2id with a salt that is the same for every file. Read here +// with the same derivation and cipher (so that a failed derivation is an +// error), never rewritten. // salted (104 bytes): salt (16) || nonce (8) || ciphertext + tag (64 + 16) -// written by this version: key = crypto_pwhash (Argon2id v1.3, the argon2id -// OPSLIMIT_SENSITIVE and MEMLIMIT_SENSITIVE) with a random salt per file, then the same -// crypto_aead_chacha20poly1305 (original construction, 8-byte nonce, no -// associated data) as the legacy format. +// written by this version: key = crypto_pwhash (Argon2id v1.3, the +// argon2id OPSLIMIT_SENSITIVE and MEMLIMIT_SENSITIVE) with a random salt +// per file, then the same crypto_aead_chacha20poly1305 (original +// construction, 8-byte nonce, no associated data) as the legacy format. // // Any other length is not an encrypted key (64 bytes is a plain key). constexpr std::size_t kSaltSize = crypto_pwhash_SALTBYTES; From 61241b879ed3e2ac712a6c9d0506e72c4bc6a971 Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Wed, 4 Nov 2026 21:10:42 +0100 Subject: [PATCH 8/8] config: the encrypted key file keeps its one format; safety fixes only The key file format is unchanged: the node writes and reads only the 88-byte format of cscrypto's PrivateKey::getEncrypted / readFromEncrypted, which the official node and every earlier node write and read. The 104-byte format of the previous commits is removed: never written, never read (a 104-byte file now stops the node like any other unexpected length). cs::keyfile::encrypt / decrypt implement that same format (same salt, same Argon2id derivation with pinned identifiers of the same values, same cipher and layout) so that a failed allocation or derivation is an error instead of a null dereference; encryptWithNonce lets the tests prove the bytes identical to cscrypto's. Kept from the review: atomic re-encryption (tmp, fsync, rename, every return value checked, no false success line), no empty key file when encryption fails, "Bad private key file in ... (N bytes)" for a length other than 64 or 88 before any prompt, the file-as-password buffer wiped. Tests: a cscrypto-written file opens and re-encrypts with its nonce to the same bytes; cscrypto's reader opens what this node writes and this node opens what cscrypto writes; wrong password, changed byte, other lengths (104 included), failed derivation. Docs: CHANGES and differences describe safer handling with the format unchanged; README advises a long, unique password when the key is encrypted. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 + client/config/config.cpp | 2 +- client/config/keyfilecrypt.cpp | 86 ++++++++++----------- client/config/keyfilecrypt.hpp | 35 ++++----- docs/CHANGES.md | 2 +- docs/differences.md | 24 +++--- tests/csnode/keyfilecrypt_tests.cpp | 112 +++++++++++++--------------- 7 files changed, 123 insertions(+), 141 deletions(-) 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/config.cpp b/client/config/config.cpp index f95d57edd..43441e0c8 100644 --- a/client/config/config.cpp +++ b/client/config/config.cpp @@ -705,7 +705,7 @@ bool Config::readKeys(const std::string& pathToPk, const std::string& pathToSk, return false; } else if (sk.size() > cscrypto::kPrivateKeySize) { - if (sk.size() != cs::keyfile::kLegacyEncryptedSize && sk.size() != cs::keyfile::kSaltedEncryptedSize) { + if (sk.size() != cs::keyfile::kEncryptedSize) { cserror() << "Bad private key file in " << pathToSk << " (" << sk.size() << " bytes)"; return false; } diff --git a/client/config/keyfilecrypt.cpp b/client/config/keyfilecrypt.cpp index 699b0f23e..f7903edca 100644 --- a/client/config/keyfilecrypt.cpp +++ b/client/config/keyfilecrypt.cpp @@ -9,62 +9,36 @@ namespace keyfile { namespace { using FileKey = cscrypto::MemGuard; -// the salt of the legacy format, as cscrypto's PrivateKey::getEncrypted uses it -constexpr std::array kLegacySalt = {0x49, 0x44, 0x49, 0x20, 0x4e, 0x41, 0x48, 0x55, - 0x59, 0x20, 0x42, 0x4c, 0x59, 0x41, 0x54, 0x27}; +// 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}; -// Argon2id v1.3 with the SENSITIVE limits, pinned (the values of the generic crypto_pwhash -// defaults that both formats were written with); false when the key memory or the derivation's -// memory cannot be had -bool deriveKey(FileKey& key, const char* passwd, std::size_t pswdLen, const cscrypto::Byte* salt) { - return key && crypto_pwhash(key.data(), key.size(), passwd, pswdLen, salt, crypto_pwhash_argon2id_OPSLIMIT_SENSITIVE, +// 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; } - -// nonce || ciphertext and tag, opened with the key derived from salt -cscrypto::PrivateKey open(const cscrypto::Byte* salt, const cscrypto::Byte* nonce, const char* passwd, std::size_t pswdLen) { - const cscrypto::Byte* sealed = nonce + kNonceSize; - - FileKey fileKey; - if (!deriveKey(fileKey, passwd, pswdLen, salt)) { - return cscrypto::PrivateKey(); - } - - cscrypto::MemGuard sk; - if (!sk) { - return cscrypto::PrivateKey(); - } - // the output is exactly kSealedSize - ABYTES = 64 bytes: libsodium zeroes that many on a bad tag - unsigned long long skLen = 0; - if (crypto_aead_chacha20poly1305_decrypt(sk.data(), &skLen, nullptr, sealed, kSealedSize, nullptr, 0, nonce, fileKey.data()) != 0 || - skLen != cscrypto::kPrivateKeySize) { - return cscrypto::PrivateKey(); - } - return cscrypto::PrivateKey::readFromBytes(sk); -} } // namespace -cscrypto::Bytes encrypt(const cscrypto::PrivateKey& key, const char* passwd, std::size_t pswdLen) { +cscrypto::Bytes encryptWithNonce(const cscrypto::PrivateKey& key, const char* passwd, std::size_t pswdLen, const cscrypto::Byte* nonce) { cscrypto::Bytes result; - if (!key) { + if (!key || nonce == nullptr) { return result; } - cscrypto::Bytes out(kSaltedEncryptedSize); - cscrypto::Byte* salt = out.data(); - cscrypto::Byte* nonce = salt + kSaltSize; - cscrypto::Byte* sealed = nonce + kNonceSize; - randombytes_buf(salt, kSaltSize); - randombytes_buf(nonce, kNonceSize); - FileKey fileKey; - if (!deriveKey(fileKey, passwd, pswdLen, salt)) { + 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(sealed, &sealedLen, sk.data(), sk.size(), nullptr, 0, nullptr, nonce, fileKey.data()) != 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; @@ -74,14 +48,34 @@ cscrypto::Bytes encrypt(const cscrypto::PrivateKey& key, const char* passwd, std 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() == kLegacyEncryptedSize) { - return open(kLegacySalt.data(), bytes.data(), passwd, pswdLen); + if (bytes.size() != kEncryptedSize) { + return cscrypto::PrivateKey(); } - if (bytes.size() == kSaltedEncryptedSize) { - return open(bytes.data(), bytes.data() + kSaltSize, passwd, pswdLen); + + FileKey fileKey; + if (!deriveKey(fileKey, passwd, pswdLen)) { + return cscrypto::PrivateKey(); } - 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 diff --git a/client/config/keyfilecrypt.hpp b/client/config/keyfilecrypt.hpp index 1055dea00..0efa1f949 100644 --- a/client/config/keyfilecrypt.hpp +++ b/client/config/keyfilecrypt.hpp @@ -8,33 +8,28 @@ namespace cs { namespace keyfile { -// The encrypted private key file (NodePrivate.txt), decoded from base58. The two formats are told -// apart by their length: +// 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: // -// legacy (88 bytes): nonce (8) || ciphertext + tag (64 + 16) -// written by older versions and the official node: cscrypto's -// PrivateKey::getEncrypted, -// key = Argon2id with a salt that is the same for every file. Read here -// with the same derivation and cipher (so that a failed derivation is an -// error), never rewritten. -// salted (104 bytes): salt (16) || nonce (8) || ciphertext + tag (64 + 16) -// written by this version: key = crypto_pwhash (Argon2id v1.3, the -// argon2id OPSLIMIT_SENSITIVE and MEMLIMIT_SENSITIVE) with a random salt -// per file, then the same crypto_aead_chacha20poly1305 (original -// construction, 8-byte nonce, no associated data) as the legacy format. +// nonce (8) || crypto_aead_chacha20poly1305 (original construction, no associated data) of the +// 64-byte secret key: ciphertext + tag (64 + 16) = 88 bytes // -// Any other length is not an encrypted key (64 bytes is a plain key). -constexpr std::size_t kSaltSize = crypto_pwhash_SALTBYTES; +// 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 kLegacyEncryptedSize = kNonceSize + kSealedSize; // 88 -constexpr std::size_t kSaltedEncryptedSize = kSaltSize + kNonceSize + kSealedSize; // 104 +constexpr std::size_t kEncryptedSize = kNonceSize + kSealedSize; // 88 -// the salted format for a new encryption; empty on failure (no key, or the derivation failed) +// 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); -// either format by its length; an empty key on a wrong password, a changed file, another length -// or a failed derivation +// 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 diff --git a/docs/CHANGES.md b/docs/CHANGES.md index 21d7f003e..3db147b4f 100644 --- a/docs/CHANGES.md +++ b/docs/CHANGES.md @@ -54,7 +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: the key file encryption now uses a random salt per file (`NodePrivate.txt` of a new encryption: salt, nonce and encrypted key, 104 bytes decoded, same Argon2id parameters and cipher); files encrypted by older versions (88 bytes) are read as before and never rewritten by themselves. A file encrypted by this version cannot be opened by older or official nodes until they read the new format (they crash on it): to downgrade, keep the plain key or encrypt it again with the older node. Other lengths stop the node at once with "Bad private key file in ... (N bytes)" (older versions asked for the password, and crashed on a file longer than 88 bytes); a failed encryption or derivation is an error, never an empty key file; the key file is replaced atomically (`NodePrivate.txt.tmp` flushed, then renamed over it; MoveFileEx on Windows), so a crash or a full disk leaves the previous file and the log reports the failure; a key file used as password is wiped from memory after use | +| #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 2de414300..fcfcf0a25 100644 --- a/docs/differences.md +++ b/docs/differences.md @@ -253,20 +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.** The key file encryption (`--encryptkey`, the "[1] Encrypt with password" - choice at the first start, and the change of password offered at start) now uses a random salt - per file: `NodePrivate.txt` is base58 of the salt (16 bytes), the nonce (8 bytes) and the - encrypted key with its tag (80 bytes), 104 bytes once decoded, with the same Argon2id parameters - and cipher as before. Files encrypted by older versions (88 bytes) are read as before and are - never rewritten by themselves; a plain key (64 bytes) is unchanged. A file encrypted by this - version cannot be opened by older community nodes or by the official node until they read the - new format (they stop with a crash when they try to open it), so to go back to one of them keep - the plain key (or the seed phrase), or encrypt the plain key again with that node. An encrypted - file of any other length stops the node at once with `Bad private key file in ... (N bytes)` - (older versions asked for the password and crashed on one longer than 88 bytes). A failed - encryption no longer writes an empty key file, and the key file is replaced atomically - (`NodePrivate.txt.tmp`, flushed, then renamed over it): a crash or a full disk leaves the previous - file, and the log says the write failed instead of reporting success. +- **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/keyfilecrypt_tests.cpp b/tests/csnode/keyfilecrypt_tests.cpp index c6028fb3a..bb58798ed 100644 --- a/tests/csnode/keyfilecrypt_tests.cpp +++ b/tests/csnode/keyfilecrypt_tests.cpp @@ -8,14 +8,16 @@ #include -// Each derivation is the node's Argon2id with 1 GiB of memory: the tests keep their number low. +// 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 the node's previous code (cscrypto's PrivateKey::getEncrypted), -// with the key below and the password "node password" -const char* kLegacyFile = "2goaN1R5N6WKdz9baKJXWovLDccavzzWR25JKeHj9goSRWFtPVC6qRuqjS74e7hvND4hxDJtv3XeZgLQJ6NPoMAy4YWnUxFUghgaizwodzbU4Zaw6wo55fB5i"; -const char* kLegacyPublic = "FAe4sisG95oZ42w7buUn5qEE4TAnfTTFPiguZUHmhiF"; -const std::string kLegacyPassword = "node password"; +// 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; @@ -40,75 +42,67 @@ class KeyFileCrypt : public ::testing::Test { }; } // namespace -TEST_F(KeyFileCrypt, SizesOfTheTwoFormats) { - EXPECT_EQ(cs::keyfile::kLegacyEncryptedSize, 88u); - EXPECT_EQ(cs::keyfile::kSaltedEncryptedSize, 104u); +TEST_F(KeyFileCrypt, Size) { + EXPECT_EQ(cs::keyfile::kEncryptedSize, 88u); } -// a file written by older versions (or the official node) opens as before -TEST_F(KeyFileCrypt, LegacyFileOpens) { - const auto bytes = decode(kLegacyFile); - ASSERT_EQ(bytes.size(), cs::keyfile::kLegacyEncryptedSize); - auto sk = cs::keyfile::decrypt(bytes, kLegacyPassword.data(), kLegacyPassword.size()); +// 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), kLegacyPublic); + 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); } -// a new encryption: 104 bytes, a random salt and nonce each time, opens with its password only, -// and not with a changed salt -TEST_F(KeyFileCrypt, NewFormatRoundTripWrongPasswordChangedSalt) { +// 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 a = cs::keyfile::encrypt(sk_, pw.data(), pw.size()); - const auto b = cs::keyfile::encrypt(sk_, pw.data(), pw.size()); - ASSERT_EQ(a.size(), cs::keyfile::kSaltedEncryptedSize); - ASSERT_EQ(b.size(), cs::keyfile::kSaltedEncryptedSize); - EXPECT_NE(cscrypto::Bytes(a.begin(), a.begin() + cs::keyfile::kSaltSize), cscrypto::Bytes(b.begin(), b.begin() + cs::keyfile::kSaltSize)); - EXPECT_NE(a, b); - - // the base58 text the node writes and reads back - const std::string text = EncodeBase58(a.data(), a.data() + a.size()); - auto sk = cs::keyfile::decrypt(decode(text), pw.data(), pw.size()); - ASSERT_TRUE(sk); - EXPECT_EQ(cscrypto::getMatchingPublic(sk), pk_); - - const std::string wrong = "round trip ~ 43"; - EXPECT_FALSE(cs::keyfile::decrypt(a, wrong.data(), wrong.size())); - - auto badSalt = a; - badSalt[3] ^= 1; - EXPECT_FALSE(cs::keyfile::decrypt(badSalt, pw.data(), pw.size())); - - // a byte changed past the salt (the ciphertext): the tag does not verify - auto badSealed = a; - badSealed[cs::keyfile::kSaltSize + cs::keyfile::kNonceSize + 10] ^= 1; - EXPECT_FALSE(cs::keyfile::decrypt(badSealed, pw.data(), pw.size())); + 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_); } -// 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(kLegacyFile), nullptr, 5)); - cscrypto::Bytes salted(cs::keyfile::kSaltedEncryptedSize, 1); - EXPECT_FALSE(cs::keyfile::decrypt(salted, nullptr, 5)); +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, 103u, 105u, 128u}) { + 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; } } -// the old writer's output is still read (the file is not converted) -TEST_F(KeyFileCrypt, LegacyWriterOutputOpens) { - const std::string pw = "legacy"; - const auto enc = sk_.getEncrypted(pw.data(), pw.size()); - ASSERT_EQ(enc.size(), cs::keyfile::kLegacyEncryptedSize); - auto sk = cs::keyfile::decrypt(enc, pw.data(), pw.size()); - ASSERT_TRUE(sk); - EXPECT_EQ(cscrypto::getMatchingPublic(sk), pk_); +// 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)); }