Skip to content
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions client/config/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
153 changes: 118 additions & 35 deletions client/config/config.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

#include <cscrypto/cscrypto.hpp>
#include "config.hpp"
#include "keyfilecrypt.hpp"

#ifdef _WIN32
#include <windows.h>
Expand All @@ -31,6 +32,7 @@
#include <unistd.h>
#include <cerrno>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#endif

Expand Down Expand Up @@ -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<size_t>(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<size_t>(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<DWORD>(std::min<size_t>(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 {
Expand All @@ -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<char*>(json.data()), json.size());

cscrypto::fillWithZeros(const_cast<char*>(pk58.data()), pk58.size());
Expand Down Expand Up @@ -449,8 +494,8 @@ static bool encryptWithPassword(const cscrypto::PrivateKey& sk, std::vector<uint
pGood = true;
}

skBytes = sk.getEncrypted(pass.data(), std::strlen(pass.data()));
return true;
skBytes = cs::keyfile::encrypt(sk, pass.data(), std::strlen(pass.data()));
return !skBytes.empty(); // a failed derivation (e.g. no memory) never writes an empty key file
}

static bool getBufFromFile(std::string& buf) {
Expand All @@ -470,19 +515,37 @@ 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_t>(size));
if (!buf.empty() && !f.read(&buf[0], static_cast<std::streamsize>(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<uint8_t>& 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() {
Expand Down Expand Up @@ -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<char*>(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";
}
Expand Down Expand Up @@ -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;
}
Expand All @@ -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_) {
Expand All @@ -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<char*>(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";
Expand Down Expand Up @@ -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<char*>(sk58.data()), sk58.size());
cscrypto::fillWithZeros(const_cast<uint8_t*>(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;
}
Expand Down
82 changes: 82 additions & 0 deletions client/config/keyfilecrypt.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#include "keyfilecrypt.hpp"

#include <array>
#include <cstring>

namespace cs {
namespace keyfile {

namespace {
using FileKey = cscrypto::MemGuard<cscrypto::Byte, crypto_aead_chacha20poly1305_KEYBYTES>;

// cscrypto's salt (cscrypto/src/privatekey.cpp, getKeyFromPassword)
constexpr std::array<cscrypto::Byte, crypto_pwhash_SALTBYTES> 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<cscrypto::Byte, kNonceSize> 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<cscrypto::Byte, cscrypto::kPrivateKeySize> 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
38 changes: 38 additions & 0 deletions client/config/keyfilecrypt.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#ifndef CLIENT_CONFIG_KEYFILECRYPT_HPP
#define CLIENT_CONFIG_KEYFILECRYPT_HPP

#include <cstddef>

#include <cscrypto/cscrypto.hpp>

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
Loading
Loading