diff --git a/client/config/config.cpp b/client/config/config.cpp index eccd1faf2..86c0ca64d 100644 --- a/client/config/config.cpp +++ b/client/config/config.cpp @@ -209,73 +209,7 @@ static inline void writeFile(const std::string name, const std::string data) { file.close(); } -// 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; 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 - 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; - } - 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 -} +using cs::keyfile::writeKeyFile; void Config::dumpJSONKeys(const std::string& fName) const { auto sk = privateKey_.access(); @@ -413,8 +347,44 @@ static int _kbhit() { } #endif +#ifndef _WIN32 +// a password character from std::cin, where the choice before it ("p") was read: with +// sync_with_stdio(false) std::cin buffers what it reads, so getchar() would miss piped input that +// std::cin already holds. On a terminal the echo and the line editing are off while it is read (the +// typed characters print as *); a pipe or a file is read as it is. -1 at the end of the input. +class PasswordInput { +public: + PasswordInput() : tty_(::isatty(STDIN_FILENO) == 1 && ::tcgetattr(STDIN_FILENO, &old_) == 0) { + if (tty_) { + termios raw = old_; + raw.c_lflag &= ~(ICANON | ECHO); + raw.c_cc[VMIN] = 1; + raw.c_cc[VTIME] = 0; + ::tcsetattr(STDIN_FILENO, TCSANOW, &raw); + } + } + ~PasswordInput() { + if (tty_) { + ::tcsetattr(STDIN_FILENO, TCSANOW, &old_); + } + } + PasswordInput(const PasswordInput&) = delete; + PasswordInput& operator=(const PasswordInput&) = delete; + + int next() { + const auto c = std::cin.get(); + return c == std::char_traits::eof() ? -1 : static_cast(c); + } + +private: + termios old_{}; + bool tty_; +}; +#endif + +// prints the prompt once the terminal no longer echoes, so that nothing typed after it shows template -static bool readPasswordFromCin(T& mem) { +static bool readPasswordFromCin(T& mem, const char* prompt) { auto ptr = mem.data(); unsigned char ch = 0; @@ -429,13 +399,25 @@ static bool readPasswordFromCin(T& mem) { GetConsoleMode(hIn, &con_mode); SetConsoleMode(hIn, con_mode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT)); + std::cout << prompt << std::flush; while (ReadConsoleA(hIn, &ch, 1, &dwRead, nullptr) && ch != RETURN) { #else const char BACKSPACE = 127; const char RETURN = 10; - while ((ch = getch()) != RETURN) { + PasswordInput input; + std::cout << prompt << std::flush; + int c = input.next(); + // the end of the choice's line ("p" and Enter), left in std::cin: not an empty password + while (c == '\n' || c == '\r') { + c = input.next(); + } + for (; c != -1 && c != RETURN; c = input.next()) { + ch = static_cast(c); + if (ch == '\r') { // CRLF input + continue; + } #endif if (ch == BACKSPACE) { if (ptr != mem.data()) { @@ -458,7 +440,11 @@ static bool readPasswordFromCin(T& mem) { if (!sz) return false; +#ifdef _WIN32 return ferror(stdin) == 0; +#else + return !std::cin.bad(); +#endif } static bool encryptWithPassword(const cscrypto::PrivateKey& sk, std::vector& skBytes) { @@ -466,8 +452,7 @@ static bool encryptWithPassword(const cscrypto::PrivateKey& sk, std::vector pass; while (!pGood) { - std::cout << "Enter password: " << std::flush; - if (!readPasswordFromCin(pass)) { + if (!readPasswordFromCin(pass, "Enter password: ")) { return false; } const auto pLen = strlen(pass.data()); @@ -481,9 +466,8 @@ static bool encryptWithPassword(const cscrypto::PrivateKey& sk, std::vector passConf; - if (!readPasswordFromCin(passConf)) + if (!readPasswordFromCin(passConf, "Confirm password: ")) return false; if (strcmp(pass.data(), passConf.data()) != 0) { @@ -554,6 +538,10 @@ static bool usePassword() { std::cout << "\nTo use password for encrytion/decryption press \"p\", to use file press \"f\": " << std::flush; std::cin >> choice; + if (!std::cin.good()) { // the end of the input (a service, < /dev/null): the caller stops + std::cout << std::endl; + return false; + } std::cout << std::endl; } if (choice == 'p') { @@ -566,12 +554,57 @@ static bool getEncryptedPrivateBytes(const cscrypto::PrivateKey& sk, std::vector if (!std::cin.good()) { return false; } - if (usePassword()) { + const bool password = usePassword(); + if (!std::cin.good()) { + return false; + } + if (password) { return encryptWithPassword(sk, skBytes); } return encryptWithFile(sk, skBytes); } +// the encrypted key file's password (or key file), asked until it opens the key; an empty key when +// the input ends +static cscrypto::PrivateKey unlockWithPrompt(const cscrypto::Bytes& sk) { + cscrypto::PrivateKey key; + while (!key) { + if (!std::cin.good()) { + return cscrypto::PrivateKey(); + } + const bool password = usePassword(); + if (!std::cin.good()) { + return cscrypto::PrivateKey(); + } + bool noMemory = false; + if (password) { + cscrypto::MemGuard pass; + if (!readPasswordFromCin(pass, "Enter password: ")) { + return cscrypto::PrivateKey(); + } + std::cout << "Trying to open file..." << std::endl; + key = cs::keyfile::decrypt(sk, pass.data(), std::strlen(pass.data()), &noMemory); + } + else { + std::string buf; + if (!getBufFromFile(buf)) { + return cscrypto::PrivateKey(); + } + key = cs::keyfile::decrypt(sk, buf.data(), buf.size(), &noMemory); + wipe(buf); + } + + if (noMemory) { // asking again would fail the same way + std::cout << "Could not open the key: not enough memory (the password check needs about 1 GB free)" << std::endl; + return cscrypto::PrivateKey(); + } + if (!key) { + std::cout << "Incorrect password (or corrupted file)" << std::endl; + } + } + return key; +} + static bool findWordInDictionary(const char* word, size_t& index) { using cscrypto::mnemonic::langs::en; bool found = false; @@ -716,30 +749,9 @@ bool Config::readKeys(const std::string& pathToPk, const std::string& pathToSk, if (encFlag) { // Check the encryption flag std::cout << "The key file seems to be encrypted" << std::endl; - while (!privateKey_) { - if (!std::cin.good()) - return false; - if (usePassword()) { - std::cout << "Enter password: " << std::flush; - cscrypto::MemGuard pass; - if (!readPasswordFromCin(pass)) { - return false; - } - std::cout << "Trying to open file..." << std::endl; - privateKey_ = cs::keyfile::decrypt(sk, pass.data(), std::strlen(pass.data())); - } - else { - std::string buf; - if (!getBufFromFile(buf)) { - return false; - } - privateKey_ = cs::keyfile::decrypt(sk, buf.data(), buf.size()); - wipe(buf); - } - - if (!privateKey_) { - std::cout << "Incorrect password (or corrupted file)" << std::endl; - } + privateKey_ = unlockWithPrompt(sk); + if (!privateKey_) { + return false; } changePasswordOption(pathToSk); } @@ -879,6 +891,50 @@ bool Config::readKeys(const std::string& pathToPk, const std::string& pathToSk, return true; } +/*public*/ +int Config::decryptKeyFile(const po::variables_map& vm) { + const std::string pathToPk = getArgFromCmdLine(vm, ARG_NAME_PUBLIC_KEY_FILE, DEFAULT_PATH_TO_PUBLIC_KEY); + const std::string pathToSk = getArgFromCmdLine(vm, ARG_NAME_PRIVATE_KEY_FILE, DEFAULT_PATH_TO_PRIVATE_KEY); + const auto unlock = [&pathToSk](const cscrypto::Bytes& sk) { + std::cout << pathToSk << " is encrypted: its password turns it into the plain key" << std::endl; + return unlockWithPrompt(sk); + }; + const auto r = cs::keyfile::toPlain(pathToPk, pathToSk, unlock, cs::keyfile::timestamp()); + using cs::keyfile::ToPlain; + switch (r.status) { + case ToPlain::Done: + std::cout << pathToSk << " is now in clear (address " << r.address << "); the encrypted original is kept as " << r.backup << std::endl; + std::cout << "Keep an offline copy of the original, never run two nodes with one key, and remember that the plain key is as safe as this machine." << std::endl; + return EXIT_SUCCESS; + case ToPlain::AlreadyPlain: + std::cout << pathToSk << " is already in clear (address " << r.address << "): nothing to do" << std::endl; + return EXIT_SUCCESS; + case ToPlain::NoPrivateFile: + std::cout << "No private key file " << pathToSk << " (set it with --private-key-file)" << std::endl; + break; + case ToPlain::BadPrivateFile: + std::cout << pathToSk << " holds neither a plain key nor a key encrypted by the node: nothing changed" << std::endl; + break; + case ToPlain::NoPublicFile: + std::cout << "No public key file " << pathToPk << " next to the encrypted key (set it with --public-key-file): nothing changed" << std::endl; + break; + case ToPlain::Cancelled: + std::cout << "Cancelled: the key was not opened, nothing changed" << std::endl; + break; + case ToPlain::PublicMismatch: + std::cout << "The key in " << pathToSk << " is address " << r.address << ", but " << pathToPk + << " holds another public key: nothing changed (copy NodePublic.txt and NodePrivate.txt of the same node)" << std::endl; + break; + case ToPlain::BackupFailed: + std::cout << "Could not keep a copy of the encrypted " << pathToSk << " next to it (is the folder writable?): nothing changed" << std::endl; + break; + case ToPlain::WriteFailed: + std::cout << "Could not write " << pathToSk << ": it is still encrypted, as it was (a copy is in " << r.backup << ")" << std::endl; + break; + } + return EXIT_FAILURE; +} + /*public*/ bool Config::readKeys(const po::variables_map& vm) { return readKeys(getArgFromCmdLine(vm, ARG_NAME_PUBLIC_KEY_FILE, DEFAULT_PATH_TO_PUBLIC_KEY), diff --git a/client/config/config.hpp b/client/config/config.hpp index 980858036..55c762f50 100644 --- a/client/config/config.hpp +++ b/client/config/config.hpp @@ -352,6 +352,9 @@ class Config { } bool readKeys(const po::variables_map& vm); + // --decryptkey: the key file encrypted by the node becomes the plain key file after its password + // is typed (the encrypted file is kept next to it); the exit code. No configuration is read. + static int decryptKeyFile(const po::variables_map& vm); bool enterWithSeed(); const ConveyerData& conveyerData() const { diff --git a/client/config/keyfilecrypt.cpp b/client/config/keyfilecrypt.cpp index f7903edca..4793ae8e3 100644 --- a/client/config/keyfilecrypt.cpp +++ b/client/config/keyfilecrypt.cpp @@ -1,7 +1,24 @@ #include "keyfilecrypt.hpp" +#include #include +#include #include +#include +#include +#include +#include + +#include + +#ifdef _WIN32 +#include +#else +#include +#include +#include +#include +#endif namespace cs { namespace keyfile { @@ -54,13 +71,19 @@ cscrypto::Bytes encrypt(const cscrypto::PrivateKey& key, const char* passwd, std return encryptWithNonce(key, passwd, pswdLen, nonce.data()); } -cscrypto::PrivateKey decrypt(const cscrypto::Bytes& bytes, const char* passwd, std::size_t pswdLen) { +cscrypto::PrivateKey decrypt(const cscrypto::Bytes& bytes, const char* passwd, std::size_t pswdLen, bool* derivationFailed) { + if (derivationFailed) { + *derivationFailed = false; + } if (bytes.size() != kEncryptedSize) { return cscrypto::PrivateKey(); } FileKey fileKey; if (!deriveKey(fileKey, passwd, pswdLen)) { + if (derivationFailed) { + *derivationFailed = true; + } return cscrypto::PrivateKey(); } @@ -78,5 +101,241 @@ cscrypto::PrivateKey decrypt(const cscrypto::Bytes& bytes, const char* passwd, s return cscrypto::PrivateKey::readFromBytes(sk); } +bool writeKeyFile(const std::string& name, const std::string& data) { +#ifndef _WIN32 + std::string target = name; + if (char* resolved = ::realpath(name.c_str(), nullptr)) { + target = resolved; + ::free(resolved); + } + const std::string tmp = target + ".tmp"; + // a new file: whatever has the name (a file left by a crash, a link, a FIFO) is removed, never + // written through or waited on + if (::unlink(tmp.c_str()) != 0 && errno != ENOENT) { + return false; + } + const int fd = ::open(tmp.c_str(), O_WRONLY | O_CREAT | O_EXCL | 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; + } + 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"; + ::DeleteFileA(tmp.c_str()); // a file left by a crash; CREATE_NEW fails on anything left + HANDLE h = ::CreateFileA(tmp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, 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 +} + + +namespace { +// the whole file; false when it cannot be read +bool readAll(const std::string& name, std::string& out) { + std::ifstream f(name, std::ios::binary); + if (!f.is_open()) { + return false; + } + out.assign(std::istreambuf_iterator(f), std::istreambuf_iterator()); + return !f.bad(); +} + +// the first line, as the node reads its key files (std::getline), without a trailing \r or blanks +std::string firstLine(const std::string& text) { + std::string line = text.substr(0, text.find('\n')); + while (!line.empty() && (line.back() == '\r' || line.back() == ' ' || line.back() == '\t')) { + line.pop_back(); + } + return line; +} + +void wipe(std::string& s) { + if (!s.empty()) { + sodium_memzero(&s[0], s.size()); + } + s.clear(); +} + +// a new file NAME with DATA, mode 0600, flushed; false when NAME exists (exists is set) or on an error +bool createNew(const std::string& name, const std::string& data, bool& exists) { + exists = false; +#ifndef _WIN32 + const int fd = ::open(name.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600); + if (fd < 0) { + exists = errno == EEXIST; + 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; + } + if (n <= 0) { + ok = false; + break; + } + done += static_cast(n); + } + ok = ok && ::fsync(fd) == 0; + ok = (::close(fd) == 0) && ok; + if (!ok) { + ::unlink(name.c_str()); + } + return ok; +#else + HANDLE h = ::CreateFileA(name.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + const DWORD err = ::GetLastError(); + exists = err == ERROR_FILE_EXISTS || err == ERROR_ALREADY_EXISTS; + return false; + } + bool ok = true; + DWORD n = 0; + ok = data.empty() || (::WriteFile(h, data.data(), static_cast(data.size()), &n, nullptr) && n == data.size()); + ok = ok && ::FlushFileBuffers(h); + ok = ::CloseHandle(h) && ok; + if (!ok) { + ::DeleteFileA(name.c_str()); + } + return ok; +#endif +} +} // namespace + +ToPlainResult toPlain(const std::string& pathToPublic, const std::string& pathToPrivate, const Unlock& unlock, const std::string& stamp) { + ToPlainResult result; + + std::string content; + if (!readAll(pathToPrivate, content)) { + result.status = ToPlain::NoPrivateFile; + return result; + } + std::string sk58 = firstLine(content); + cscrypto::Bytes bytes; + const bool decoded = DecodeBase58(sk58, bytes); + wipe(sk58); + + if (decoded && bytes.size() == cscrypto::kPrivateKeySize) { + auto key = cscrypto::PrivateKey::readFromBytes(bytes); + sodium_memzero(bytes.data(), bytes.size()); + wipe(content); + if (!key) { + result.status = ToPlain::BadPrivateFile; + return result; + } + const auto pk = cscrypto::getMatchingPublic(key); + result.address = EncodeBase58(pk.data(), pk.data() + pk.size()); + result.status = ToPlain::AlreadyPlain; + return result; + } + if (!decoded || bytes.size() != kEncryptedSize) { + result.status = ToPlain::BadPrivateFile; + return result; + } + + // before the password: a key without its public key file is refused anyway + std::string publicText; + if (!readAll(pathToPublic, publicText)) { + result.status = ToPlain::NoPublicFile; + return result; + } + const std::string publicOnFile = firstLine(publicText); + + const cscrypto::PrivateKey key = unlock(bytes); + if (!key) { + result.status = ToPlain::Cancelled; + return result; + } + const auto pk = cscrypto::getMatchingPublic(key); + result.address = EncodeBase58(pk.data(), pk.data() + pk.size()); + if (result.address != publicOnFile) { + result.status = ToPlain::PublicMismatch; + return result; + } + + // the encrypted original first, under a name not taken yet + const std::string base = pathToPrivate + ".encrypted-" + stamp; + bool kept = false; + for (int i = 1; i <= 100 && !kept; ++i) { + const std::string name = i == 1 ? base : base + "-" + std::to_string(i); + bool exists = false; + if (createNew(name, content, exists)) { + result.backup = name; + kept = true; + } + else if (!exists) { + break; + } + } + if (!kept) { + result.status = ToPlain::BackupFailed; + return result; + } + + auto sk = key.access(); + std::string plain = EncodeBase58(sk.data(), sk.data() + sk.size()); + const bool written = writeKeyFile(pathToPrivate, plain); + wipe(plain); + result.status = written ? ToPlain::Done : ToPlain::WriteFailed; + return result; +} + +std::string timestamp() { + const std::time_t now = std::time(nullptr); + std::tm tm{}; +#ifdef _WIN32 + localtime_s(&tm, &now); +#else + localtime_r(&now, &tm); +#endif + char buf[32] = {}; + std::strftime(buf, sizeof(buf), "%Y%m%d-%H%M%S", &tm); + return buf; +} + } // namespace keyfile } // namespace cs diff --git a/client/config/keyfilecrypt.hpp b/client/config/keyfilecrypt.hpp index 0efa1f949..381f4723a 100644 --- a/client/config/keyfilecrypt.hpp +++ b/client/config/keyfilecrypt.hpp @@ -2,6 +2,8 @@ #define CLIENT_CONFIG_KEYFILECRYPT_HPP #include +#include +#include #include @@ -29,8 +31,47 @@ cscrypto::Bytes encrypt(const cscrypto::PrivateKey& key, const char* passwd, std // 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); +// an empty key on a wrong password, a changed file, another length or a failed derivation; +// derivationFailed, when given, tells the last (libsodium could not allocate its memory, about 1 GiB) +cscrypto::PrivateKey decrypt(const cscrypto::Bytes& bytes, const char* passwd, std::size_t pswdLen, bool* derivationFailed = nullptr); + +// The private key file and the keys JSON: readable by their 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. +bool writeKeyFile(const std::string& name, const std::string& data); + +// --decryptkey: the private key file encrypted by the node (88 bytes) becomes the plain key file (64 +// bytes in base58, the format the node and keygen write). The encrypted file is kept first as +// .encrypted- (mode 0600, created new: an existing file of that name is never +// replaced, -2, -3... are added), then the plain key replaces the file with writeKeyFile. The public +// key file must exist and hold the key's public key, or nothing is changed. +enum class ToPlain { + Done, // written; address and backup are set + AlreadyPlain, // nothing to do; address is set + NoPrivateFile, + BadPrivateFile, // neither a plain nor an encrypted key + NoPublicFile, + Cancelled, // unlock returned no key (the input ended) + PublicMismatch, // address is the key's, NodePublic.txt holds another one + BackupFailed, // nothing changed + WriteFailed // the backup exists, the key file is as it was +}; + +struct ToPlainResult { + ToPlain status = ToPlain::Cancelled; + std::string address; // base58 public key of the private key + std::string backup; // the copy of the encrypted file +}; + +// unlock gets the encrypted bytes and returns the key, or an empty key to give up; stamp is the +// backup's suffix (timestamp()) +using Unlock = std::function; +ToPlainResult toPlain(const std::string& pathToPublic, const std::string& pathToPrivate, const Unlock& unlock, const std::string& stamp); + +// the local time as YYYYMMDD-HHMMSS +std::string timestamp(); } // namespace keyfile } // namespace cs diff --git a/client/src/main.cpp b/client/src/main.cpp index 408e1112d..6989d85f5 100644 --- a/client/src/main.cpp +++ b/client/src/main.cpp @@ -72,6 +72,7 @@ int main(int argc, char* argv[]) { ("private-key-file", po::value(), "path to private key file (default: \"NodePrivate.txt\")") ("dumpkeys", po::value(), "dump your public and private keys into a JSON file with the specified name (UNENCRYPTED!)") ("encryptkey", "encrypts the private key with password upon startup (if not yet encrypted)") + ("decryptkey", "turn a private key file encrypted by the node into the plain key file after asking its password, then exit; the encrypted file is kept as .encrypted- (the node must be stopped; no configuration or database is needed)") #ifdef _WIN32 (cmdline::argInstall, po::value(), @@ -188,6 +189,16 @@ int main(int argc, char* argv[]) { #endif } + // the key files only: no configuration, network or database (db/.lock tells a running node) + if (vm.count("decryptkey") > 0) { + const std::string dbPath = vm.count(cmdline::argDBPath) ? vm[cmdline::argDBPath].as() : std::string("db"); + if (dbcheck::lockedByAnotherProcess(dbPath)) { + std::cerr << "a node runs with " << dbPath << " (db/.lock is held): stop it first, then run --decryptkey again" << std::endl; + return 3; + } + return Config::decryptKeyFile(vm); + } + auto config = Config::read(vm, true); if (!config.isGood()) { diff --git a/docs/CHANGES.md b/docs/CHANGES.md index 9e146632c..ff0547bc8 100644 --- a/docs/CHANGES.md +++ b/docs/CHANGES.md @@ -46,6 +46,8 @@ lines under the new release. |---|---| | #172 | docs: `docs/quick-start.md`, a short quick-start guide (Docker and native Linux, Windows and macOS; pruned on lmdb or full on rocksdb from the snapshot, snapshot serving on; requirements, ports, first checks, the wallet, upgrading with the database kept, common problems), linked from the top of the README | | #173 | packaging: a new full node defaults to rocksdb (it starts from a snapshot) in Docker and in the guided set-up (setup.sh, setup.ps1); pruned stays on lmdb; existing installs keep their backend (the database in `db/`, the `db_backend` of `config.ini`, berkeleydb for a full `[storage]` without one; the entrypoint also detects the database of a data folder whose `config.ini` was removed); `docker-compose.yml` takes its limits from `CREDITS_CPUS` (1.5) and `CREDITS_MEMORY` (4g) in `.env` (a full node: 4 and 8g); texts aligned: a full node on rocksdb about 250 to 300 GB, backfill about 2 to 3 days, glibc 2.38 for `linux-x64` (2.31 for `-glibc2.31`) in the README, the image `ghcr.io/creditscommunity/credits-node`, the `config.pruned.ini` comment on the snapshot start; quick-start, storage.md and the Docker README updated; ci: setup-test and the Docker entrypoint test check the rocksdb default and that a full berkeleydb install is kept | +| #174 | docs: quick-start: using an existing node key, plain or encrypted, in Docker or native (a section with copy-paste steps; an encrypted key converted once to plain with the node's own `--dumpkeys`, for Docker and systemd) | +| #175 | node: `--decryptkey` turns a key file encrypted with a password by the node into the plain key after asking the old password (the encrypted file kept as `NodePrivate.txt.encrypted-`, the public key checked, no configuration, network or database); Docker: `docker compose run --rm node decrypt-key`, and a normal start with an encrypted key stops with that hint instead of waiting for a password; quick-start section 10 uses it instead of the `--dumpkeys` procedure of #174 | ## community.17 — 2026-11-05 diff --git a/docs/quick-start.md b/docs/quick-start.md index 22f5acbe5..779752561 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -295,7 +295,133 @@ Docker: `docker compose pull && docker compose up -d`. Native: Never run the old and the new node at the same time with the same key or the same `db/` folder. -## 10. Troubleshooting +## 10. Using your existing node key + +Your node's identity is its key: `NodePrivate.txt` and `NodePublic.txt`. To keep an identity you +already have, give the node those two files instead of letting it make new ones. First check which +kind of `NodePrivate.txt` you have: + +```sh +wc -c NodePrivate.txt # about 88 characters: plain; about 120: encrypted with a password +``` + +A **plain** key works everywhere. A key **encrypted by the node** (`--encryptkey`, or the password +choice at its first start) makes the node ask for the password at every start, on its console. + +Before you start: + +- **Never run two nodes with the same key**, not even for a moment. Stop every node that uses + this key first, including an official node or one on another machine: the node can only tell + a community node running in the same folder. +- **Keep an offline backup** (USB stick, paper) of the original files. A plain key is as exposed + as the machine it is on. +- The wallet uses a plain node key as the account `node` without a password. On mainnet it still + asks you to type `send` before every transfer. + +### Native, plain key + +Put `NodePrivate.txt` and `NodePublic.txt` in the `csnode` folder **before** you run `./setup.sh` +(`setup.bat` on Windows). The set-up finds them, offers the key as the wallet's account `node` +(answer `node`), and sets `NodePrivate.txt` to mode 600. + +### Native, encrypted key + +Same place, same set-up. At every start the node asks: + +``` +The key file seems to be encrypted +To use password for encrytion/decryption press "p", to use file press "f": p +Enter password: ******** +``` + +This works in tmux or in a Windows console window you type into. It does **not** work under +systemd or any start without a console: the node cannot ask and does not start. Either keep it +in tmux, or convert the key to plain once with `./node --decryptkey` +([below](#convert-an-encrypted-key-to-plain)). The +wallet opens an encrypted key with `--node-key` or as the account `node`, and asks the node's +password; it needs about 1 GB of free memory for that. + +### Docker, plain key + +1. Stop the node, and save the keys the container may have made at its first start: + + ```sh + docker compose stop + sudo cp -a ~/.credits/keys ~/.credits/keys.generated-$(date +%F) + ``` + +2. Copy your two files in, owned by the container's user (uid 1000), mode 600: + + ```sh + sudo cp NodePrivate.txt NodePublic.txt ~/.credits/keys/ + sudo chown 1000:1000 ~/.credits/keys/NodePrivate.txt ~/.credits/keys/NodePublic.txt + sudo chmod 600 ~/.credits/keys/NodePrivate.txt ~/.credits/keys/NodePublic.txt + ``` + +3. Start it and check the key it runs with: + + ```sh + docker compose up -d + docker compose exec node credits-wallet account node-key + ``` + + `address` must be your `NodePublic.txt`, with `public file : ... matches`. The log must not + show `new node keys` nor ask for a password. (The node does not print its own key in the log.) + +On a **new** installation you can put the two files in `~/.credits/keys/` (with the `chown` and +`chmod` above) before the first `docker compose up -d`: the container makes new keys only when +`keys/NodePublic.txt` is missing. Always copy both files. + +### Docker, encrypted key + +The container cannot type a password at every start: with an encrypted key it stops with +`NOT STARTING: keys/NodePrivate.txt is encrypted`. Turn the key into the plain key once, with the +node of the image (community.18 or later); it asks the old password and needs no network. Opening +the key takes about 1 GB of free memory for a few seconds, so `CREDITS_MEMORY` in `.env` must be at +least about `1.2g` (the default is `4g`). Until the key is converted, `docker compose up -d` keeps +restarting the container with that message: stop it with `docker compose stop`. + +1. Stop the node and save the keys it may have made (step 1 above). +2. Copy your two files in, as in step 2 above. +3. Decrypt and start: + + ```sh + docker compose run --rm node decrypt-key # press p, Enter, then type the old password + docker compose up -d + ``` + + It prints `keys/NodePrivate.txt is now in clear (address ); the encrypted + original is kept as keys/NodePrivate.txt.encrypted--