From 6dddf513b355d3fcdbbda97334f99c45c6bb1fb4 Mon Sep 17 00:00:00 2001 From: faumaray Date: Sat, 11 Jul 2026 16:30:05 +0300 Subject: [PATCH] New arch Signed-off-by: faumaray --- include/echoion/protocol/Identity.hpp | 3 + include/echoion/protocol/TsClient.hpp | 34 ++++ src/Crypto.cpp | 8 +- src/Identity.cpp | 251 +++++++++++++++++++++++++- src/TsClient.cpp | 234 ++++++++++++++++++++++++ tests/test_identity.cpp | 73 ++++++++ 6 files changed, 600 insertions(+), 3 deletions(-) diff --git a/include/echoion/protocol/Identity.hpp b/include/echoion/protocol/Identity.hpp index 1a58bf4..3d20cad 100644 --- a/include/echoion/protocol/Identity.hpp +++ b/include/echoion/protocol/Identity.hpp @@ -28,6 +28,9 @@ namespace Echoion::Protocol // Load / save the identity to a small text file: // privateKeyPem, publicKeyString, keyOffset (one per line). static Identity load(const std::string& path); + // Import an identity exported by the TeamSpeak client. The export is + // an INI file containing its obfuscated "V" key. + static Identity importTeamSpeakIni(const std::string& path); void save(const std::string& path) const; // libtomcrypt ASN.1 public key, base64 ("omega" in clientinitiv). diff --git a/include/echoion/protocol/TsClient.hpp b/include/echoion/protocol/TsClient.hpp index 704aa1b..444c66c 100644 --- a/include/echoion/protocol/TsClient.hpp +++ b/include/echoion/protocol/TsClient.hpp @@ -12,7 +12,10 @@ #include "echoion/protocol/Identity.hpp" #include +#include +#include #include +#include #include #include #include @@ -66,6 +69,14 @@ namespace Echoion::Protocol std::function onDebug; }; + struct CommandResult { + std::vector records; + int errorId = 0; + std::string errorMessage; + + [[nodiscard]] bool ok() const noexcept { return errorId == 0; } + }; + class TsClient { public: @@ -100,6 +111,16 @@ namespace Echoion::Protocol // Send a raw pre-built TS3 command line (fragmented if large). void sendCommand(const std::string& cmd); + // Send a command and wait for its data records plus terminating + // `error` response. Safe to call from threads other than the receive + // callback thread. + CommandResult requestCommand( + const std::string& cmd, + std::chrono::milliseconds timeout = std::chrono::seconds{3}); + CommandResult downloadFile( + const std::string& remotePath, const std::string& destination, + uint64_t channelId = 0, const std::string& channelPassword = {}, + std::chrono::milliseconds timeout = std::chrono::seconds{10}); private: @@ -139,6 +160,7 @@ namespace Echoion::Protocol void resendTick(); void debug(const std::string& msg); void cleanup(); + void cancelPendingRequests(const std::string& reason); // counters / crypto struct Counter { @@ -190,6 +212,18 @@ namespace Echoion::Protocol // channel map for auto-move std::map channelMap_; + + struct PendingRequest { + CommandResult result; + std::string returnCode; + bool completed = false; + std::condition_variable cv; + }; + std::mutex requestSerialMutex_; + std::mutex pendingMutex_; + std::deque> pendingRequests_; + std::atomic requestId_{0}; + std::atomic transferId_{0}; }; } // namespace Echoion::Protocol diff --git a/src/Crypto.cpp b/src/Crypto.cpp index 362574c..ae44a8f 100644 --- a/src/Crypto.cpp +++ b/src/Crypto.cpp @@ -57,7 +57,9 @@ namespace Echoion::Protocol::Crypto { Bytes input(BLOCK_SIZE + data.size(), 0); input[BLOCK_SIZE - 1] = tag; - std::memcpy(input.data() + BLOCK_SIZE, data.data(), data.size()); + if (!data.empty()) { + std::memcpy(input.data() + BLOCK_SIZE, data.data(), data.size()); + } return cmac(key, input); } @@ -160,7 +162,9 @@ namespace Echoion::Protocol::Crypto } } else { const size_t rem = n - off; - std::memcpy(last.data(), data.data() + off, rem); + if (rem != 0) { + std::memcpy(last.data(), data.data() + off, rem); + } last[rem] = 0x80; for (size_t j = 0; j < BLOCK_SIZE; ++j) { last[j] ^= K2[j]; diff --git a/src/Identity.cpp b/src/Identity.cpp index 9359b1d..899a69c 100644 --- a/src/Identity.cpp +++ b/src/Identity.cpp @@ -4,13 +4,20 @@ #include #include +#include #include #include #include +#include +#include +#include #include +#include #include #include +#include +#include namespace Echoion::Protocol { @@ -28,6 +35,151 @@ namespace Echoion::Protocol return static_cast(p.get()); } + struct ParsedPrivateKey { + BIGNUM* privateKey = nullptr; + BIGNUM* publicX = nullptr; + BIGNUM* publicY = nullptr; + + ~ParsedPrivateKey() + { + BN_free(privateKey); + BN_free(publicX); + BN_free(publicY); + } + ParsedPrivateKey() = default; + ParsedPrivateKey(const ParsedPrivateKey&) = delete; + ParsedPrivateKey& operator=(const ParsedPrivateKey&) = delete; + ParsedPrivateKey(ParsedPrivateKey&& other) noexcept + : privateKey(std::exchange(other.privateKey, nullptr)), + publicX(std::exchange(other.publicX, nullptr)), + publicY(std::exchange(other.publicY, nullptr)) + { + } + }; + + size_t readDerLength(Crypto::ByteView der, size_t& position) + { + if (position >= der.size()) { + fail("truncated DER length"); + } + const auto first = der[position++]; + if (first < 0x80) { + return first; + } + const auto bytes = static_cast(first & 0x7f); + if (bytes == 0 || bytes > sizeof(size_t) || + position + bytes > der.size()) { + fail("invalid DER length"); + } + size_t length = 0; + for (size_t i = 0; i < bytes; ++i) { + length = (length << 8) | der[position++]; + } + return length; + } + + ParsedPrivateKey parsePrivateKeyDer(Crypto::ByteView der) + { + if (der.empty() || der.front() != 0x30) { + fail("imported key is not a DER sequence"); + } + size_t position = 1; + const auto sequenceLength = readDerLength(der, position); + if (position + sequenceLength != der.size()) { + fail("invalid imported key length"); + } + + uint8_t keyKind = 0; + std::vector integers; + while (position < der.size()) { + const auto tag = der[position++]; + const auto length = readDerLength(der, position); + if (position + length > der.size()) { + for (auto* value : integers) { + BN_free(value); + } + fail("truncated imported key"); + } + if (tag == 0x03) { + if (length < 2) { + fail("invalid imported key flags"); + } + keyKind = der[position + 1]; + } else if (tag == 0x02) { + integers.push_back(BN_bin2bn( + der.data() + position, static_cast(length), nullptr)); + } + position += length; + } + + ParsedPrivateKey parsed; + // INTEGER lists exclude the bit string. Public+private is + // [32, x, y, d]; private-only is [32, d]. + if (keyKind == 0x80 && integers.size() == 4) { + parsed.publicX = integers[1]; + parsed.publicY = integers[2]; + parsed.privateKey = integers[3]; + BN_free(integers[0]); + } else if (keyKind == 0xc0 && integers.size() == 2) { + parsed.privateKey = integers[1]; + BN_free(integers[0]); + } else { + for (auto* value : integers) { + BN_free(value); + } + fail("unsupported imported identity key"); + } + return parsed; + } + + EVP_PKEY* makePrivateKey(ParsedPrivateKey& parsed) + { + std::array publicPoint{}; + publicPoint[0] = 0x04; + if (!parsed.publicX || !parsed.publicY) { + EC_GROUP* group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1); + EC_POINT* point = group ? EC_POINT_new(group) : nullptr; + if (!group || !point || + EC_POINT_mul(group, point, parsed.privateKey, nullptr, nullptr, + nullptr) != 1 || + EC_POINT_point2oct(group, point, POINT_CONVERSION_UNCOMPRESSED, + publicPoint.data(), publicPoint.size(), nullptr) != + publicPoint.size()) { + EC_POINT_free(point); + EC_GROUP_free(group); + fail("cannot derive imported public key"); + } + EC_POINT_free(point); + EC_GROUP_free(group); + } else { + if (BN_bn2binpad(parsed.publicX, publicPoint.data() + 1, 32) != 32 || + BN_bn2binpad(parsed.publicY, publicPoint.data() + 33, 32) != 32) { + fail("invalid imported public key"); + } + } + + OSSL_PARAM_BLD* builder = OSSL_PARAM_BLD_new(); + OSSL_PARAM_BLD_push_utf8_string(builder, OSSL_PKEY_PARAM_GROUP_NAME, + "prime256v1", 0); + OSSL_PARAM_BLD_push_octet_string(builder, OSSL_PKEY_PARAM_PUB_KEY, + publicPoint.data(), publicPoint.size()); + OSSL_PARAM_BLD_push_BN(builder, OSSL_PKEY_PARAM_PRIV_KEY, + parsed.privateKey); + OSSL_PARAM* params = OSSL_PARAM_BLD_to_param(builder); + EVP_PKEY_CTX* context = + EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr); + EVP_PKEY* key = nullptr; + const bool ok = context && EVP_PKEY_fromdata_init(context) == 1 && + EVP_PKEY_fromdata(context, &key, EVP_PKEY_KEYPAIR, params) == 1; + EVP_PKEY_CTX_free(context); + OSSL_PARAM_free(params); + OSSL_PARAM_BLD_free(builder); + if (!ok) { + fail("cannot construct imported private key"); + } + return key; + } + // Minimal big-endian encoding of a BIGNUM (no leading zeros). Bytes bnBytes(const BIGNUM* bn) { @@ -199,6 +351,85 @@ namespace Echoion::Protocol EVP_PKEY_free(static_cast(p)); } + Identity Identity::importTeamSpeakIni(const std::string& path) + { + std::ifstream input(path, std::ios::binary); + if (!input) { + fail("cannot open TeamSpeak identity export"); + } + const std::string contents((std::istreambuf_iterator(input)), + std::istreambuf_iterator()); + // TeamSpeak's exported value is V. It may + // appear quoted or as the value of an INI property. + const std::regex pattern{R"((\d+)V([A-Za-z0-9+/]+={0,2}))"}; + std::smatch match; + if (!std::regex_search(contents, match, pattern)) { + fail("TeamSpeak export does not contain an identity"); + } + + uint64_t offset = 0; + try { + offset = std::stoull(match[1].str()); + } catch (const std::exception&) { + fail("invalid TeamSpeak key offset"); + } + auto obfuscated = Util::base64Decode(match[2].str()); + if (obfuscated.size() < 20) { + fail("TeamSpeak identity is too short"); + } + + const auto payloadBegin = obfuscated.begin() + 20; + const auto nullPosition = + std::find(payloadBegin, obfuscated.end(), uint8_t{0}); + const auto hash = Crypto::sha1(Crypto::ByteView( + &*payloadBegin, static_cast(nullPosition - payloadBegin))); + for (size_t i = 0; i < hash.size(); ++i) { + obfuscated[i] ^= hash[i]; + } + constexpr std::string_view obfuscationKey = + "b9dfaa7bee6ac57ac7b65f1094a1c155e747327bc2fe5d51c512023fe54a2802" + "01004e90ad1daaae1075d53b7d571c30e063b5a62a4a017bb394833aa0983e6e"; + const auto xorLength = std::min(obfuscated.size(), size_t{100}); + for (size_t i = 0; i < xorLength; ++i) { + obfuscated[i] ^= static_cast(obfuscationKey[i]); + } + + std::string encoded(obfuscated.begin(), obfuscated.end()); + if (const auto nul = encoded.find('\0'); nul != std::string::npos) { + encoded.resize(nul); + } + const auto der = Util::base64Decode(encoded); + auto parsed = parsePrivateKeyDer(der); + EVP_PKEY* key = makePrivateKey(parsed); + EVP_PKEY_CTX* checkContext = EVP_PKEY_CTX_new(key, nullptr); + const bool valid = checkContext && + EVP_PKEY_private_check(checkContext) == 1 && + EVP_PKEY_pairwise_check(checkContext) == 1; + EVP_PKEY_CTX_free(checkContext); + if (!valid) { + EVP_PKEY_free(key); + fail("TeamSpeak identity key pair is inconsistent"); + } + + Identity identity; + identity.pkey_ = std::shared_ptr(key, PKeyDeleter{}); + const auto point = pubPoint(key); + if (point.size() != 65 || point.front() != 0x04) { + fail("unexpected imported public key format"); + } + BIGNUM* x = BN_bin2bn(point.data() + 1, 32, nullptr); + BIGNUM* y = BN_bin2bn(point.data() + 33, 32, nullptr); + identity.publicKeyString_ = buildPublicKeyString(x, y); + BN_free(x); + BN_free(y); + identity.keyOffset_ = offset; + const auto uidHash = Crypto::sha1(Crypto::ByteView( + reinterpret_cast(identity.publicKeyString_.data()), + identity.publicKeyString_.size())); + identity.uid_ = Util::base64Encode(uidHash); + return identity; + } + Identity Identity::generate(int securityLevel) { EVP_PKEY* pkey = nullptr; @@ -375,7 +606,9 @@ namespace Echoion::Protocol std::string pem(data, static_cast(n)); BIO_free(mem); - std::ofstream out(path, std::ios::trunc); + const std::filesystem::path destination{path}; + const auto temporary = destination.string() + ".tmp"; + std::ofstream out(temporary, std::ios::binary | std::ios::trunc); if (!out) { fail("cannot open identity file for writing"); } @@ -384,6 +617,22 @@ namespace Echoion::Protocol out << publicKeyString_ << "\n"; out << "-----PRIVATE-----\n"; out << pem; + out.close(); + if (!out) { + std::filesystem::remove(temporary); + fail("cannot finish writing identity file"); + } + std::filesystem::permissions( + temporary, + std::filesystem::perms::owner_read | + std::filesystem::perms::owner_write, + std::filesystem::perm_options::replace); + std::error_code renameError; + std::filesystem::rename(temporary, destination, renameError); + if (renameError) { + std::filesystem::remove(temporary); + fail("cannot install identity file"); + } } Identity Identity::load(const std::string& path) diff --git a/src/TsClient.cpp b/src/TsClient.cpp index c3a9be2..23cfe0b 100644 --- a/src/TsClient.cpp +++ b/src/TsClient.cpp @@ -13,8 +13,12 @@ #include #include +#include +#include #include #include +#include +#include #include namespace Echoion::Protocol @@ -122,6 +126,10 @@ namespace Echoion::Protocol void TsClient::connect(const TsClientOptions& opts) { + if (thread_.joinable()) { + forceClose(); + thread_.join(); + } std::lock_guard lock(mu_); if (!opts.identity) { throw std::runtime_error("TsClient: identity is required"); @@ -352,6 +360,172 @@ namespace Echoion::Protocol } } + CommandResult TsClient::requestCommand( + const std::string& cmd, std::chrono::milliseconds timeout) + { + if (std::this_thread::get_id() == thread_.get_id()) { + return {{}, -1, "requestCommand cannot block the receive thread"}; + } + // TeamSpeak returns data records without a request identifier; keep one + // response-bearing command in flight so those records remain unambiguous. + std::unique_lock serialLock(requestSerialMutex_); + auto pending = std::make_shared(); + pending->returnCode = "echoion-" + std::to_string(++requestId_); + { + // Keep queue insertion and wire send in the same order when callers + // issue requests concurrently. + std::lock_guard sendLock(mu_); + if (state_.load() != ClientState::Connected) { + return {{}, -1, "client is not connected"}; + } + { + std::lock_guard pendingLock(pendingMutex_); + pendingRequests_.push_back(pending); + } + sendCommand(cmd + " return_code=" + pending->returnCode); + } + + std::unique_lock lock(pendingMutex_); + if (!pending->cv.wait_for(lock, timeout, + [&pending] { return pending->completed; })) { + const auto entry = + std::find(pendingRequests_.begin(), pendingRequests_.end(), pending); + if (entry != pendingRequests_.end()) { + pendingRequests_.erase(entry); + } + return {{}, -1, "command timed out"}; + } + return pending->result; + } + + CommandResult TsClient::downloadFile( + const std::string& remotePath, const std::string& destination, + uint64_t channelId, const std::string& channelPassword, + std::chrono::milliseconds timeout) + { + CommandParams parameters; + parameters["cid"] = std::to_string(channelId); + parameters["cpw"] = channelPassword; + parameters["name"] = remotePath; + parameters["clientftfid"] = std::to_string(++transferId_); + parameters["seekpos"] = "0"; + auto result = requestCommand(buildCommand("ftinitdownload", parameters), + timeout); + if (!result.ok() || result.records.empty()) { + if (result.ok()) { + result.errorId = -1; + result.errorMessage = "file transfer returned no connection data"; + } + return result; + } + const auto& record = result.records.front(); + auto value = [&record](const char* name) -> std::string { + const auto entry = record.find(name); + return entry == record.end() ? std::string{} : entry->second; + }; + const auto transferKey = value("ftkey"); + const auto portText = value("port"); + const auto sizeText = value("size"); + if (transferKey.empty() || portText.empty() || sizeText.empty()) { + return {{}, -1, "file transfer response is incomplete"}; + } + + addrinfo hints{}; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + addrinfo* addresses = nullptr; + if (getaddrinfo(opts_.host.c_str(), portText.c_str(), &hints, + &addresses) != 0 || !addresses) { + return {{}, -1, "cannot resolve file-transfer endpoint"}; + } + int transferSocket = -1; + for (auto* address = addresses; address; address = address->ai_next) { + transferSocket = + ::socket(address->ai_family, address->ai_socktype, + address->ai_protocol); + if (transferSocket >= 0 && + ::connect(transferSocket, address->ai_addr, address->ai_addrlen) == + 0) { + break; + } + if (transferSocket >= 0) { + ::close(transferSocket); + transferSocket = -1; + } + } + freeaddrinfo(addresses); + if (transferSocket < 0) { + return {{}, -1, "cannot connect to file-transfer endpoint"}; + } + + const auto temporary = destination + ".part"; + if (const auto parent = std::filesystem::path(destination).parent_path(); + !parent.empty()) { + std::error_code directoryError; + std::filesystem::create_directories(parent, directoryError); + if (directoryError) { + ::close(transferSocket); + return {{}, -1, "cannot create file-transfer destination"}; + } + } + std::ofstream output(temporary, std::ios::binary | std::ios::trunc); + timeval socketTimeout{}; + socketTimeout.tv_sec = static_cast( + std::max(1, timeout.count() / 1000)); + setsockopt(transferSocket, SOL_SOCKET, SO_RCVTIMEO, &socketTimeout, + sizeof(socketTimeout)); + size_t keySent = 0; + while (keySent < transferKey.size()) { + const auto count = ::send(transferSocket, transferKey.data() + keySent, + transferKey.size() - keySent, 0); + if (count <= 0) { + break; + } + keySent += static_cast(count); + } + if (!output || keySent != transferKey.size()) { + ::close(transferSocket); + std::filesystem::remove(temporary); + return {{}, -1, "cannot start file transfer"}; + } + std::array buffer{}; + uint64_t received = 0; + while (true) { + const auto count = ::recv(transferSocket, buffer.data(), buffer.size(), 0); + if (count == 0) { + break; + } + if (count < 0) { + output.close(); + ::close(transferSocket); + std::filesystem::remove(temporary); + return {{}, -1, "file transfer was interrupted"}; + } + output.write(buffer.data(), count); + received += static_cast(count); + } + ::close(transferSocket); + output.close(); + uint64_t expected = 0; + try { + expected = std::stoull(sizeText); + } catch (const std::exception&) { + std::filesystem::remove(temporary); + return {{}, -1, "invalid file-transfer size"}; + } + if (!output || received != expected) { + std::filesystem::remove(temporary); + return {{}, -1, "file transfer size mismatch"}; + } + std::error_code renameError; + std::filesystem::rename(temporary, destination, renameError); + if (renameError) { + std::filesystem::remove(temporary); + return {{}, -1, "cannot install downloaded file"}; + } + return {}; + } + void TsClient::sendVoice(std::span opus) { std::lock_guard lock(mu_); @@ -660,6 +834,47 @@ namespace Echoion::Protocol } const std::string& name = parsed.name; + if (name == "error") { + std::shared_ptr pending; + { + std::lock_guard lock(pendingMutex_); + const auto returnCode = parsed.params.find("return_code"); + if (!pendingRequests_.empty() && + returnCode != parsed.params.end() && + returnCode->second == pendingRequests_.front()->returnCode) { + pending = pendingRequests_.front(); + pendingRequests_.pop_front(); + if (const auto id = parsed.params.find("id"); + id != parsed.params.end()) { + try { + pending->result.errorId = std::stoi(id->second); + } catch (const std::exception&) { + pending->result.errorId = -1; + } + } + if (const auto message = parsed.params.find("msg"); + message != parsed.params.end()) { + pending->result.errorMessage = message->second; + } + pending->completed = true; + } + } + if (pending) { + pending->cv.notify_all(); + } + } else if (!name.starts_with("notify") && name != "initivexpand" && + name != "initivexpand2" && name != "initserver") { + std::lock_guard lock(pendingMutex_); + if (!pendingRequests_.empty()) { + auto& records = pendingRequests_.front()->result.records; + if (parsed.groups.empty()) { + records.push_back(parsed.params); + } else { + records.insert(records.end(), parsed.groups.begin(), + parsed.groups.end()); + } + } + } if (name == "initivexpand") { handleInitIvExpand(parsed.params); } else if (name == "initivexpand2") { @@ -963,6 +1178,7 @@ namespace Echoion::Protocol if (sock_ >= 0) { ::shutdown(sock_, SHUT_RDWR); } + cancelPendingRequests("connection closed"); } void TsClient::cleanup() @@ -972,9 +1188,27 @@ namespace Echoion::Protocol } state_ = ClientState::Disconnected; running_ = false; + cancelPendingRequests("connection closed"); if (cb_.onDisconnected) { cb_.onDisconnected(); } } + void TsClient::cancelPendingRequests(const std::string& reason) + { + std::deque> pending; + { + std::lock_guard lock(pendingMutex_); + pending.swap(pendingRequests_); + for (const auto& request : pending) { + request->result.errorId = -1; + request->result.errorMessage = reason; + request->completed = true; + } + } + for (const auto& request : pending) { + request->cv.notify_all(); + } + } + } // namespace Echoion::Protocol diff --git a/tests/test_identity.cpp b/tests/test_identity.cpp index 452bdf4..c0c7bc1 100644 --- a/tests/test_identity.cpp +++ b/tests/test_identity.cpp @@ -4,6 +4,8 @@ #include "echoion/protocol/Util.hpp" #include +#include +#include #include using namespace Echoion::Protocol; @@ -50,3 +52,74 @@ TEST_CASE(identity_save_load_roundtrip) CHECK_EQ(loaded.keyOffset(), id.keyOffset()); std::remove(path.c_str()); } + +namespace +{ + std::string teamSpeakExportForScalarOne(uint64_t offset) + { + // libtomcrypt private-only key: flags 0xc0, 256 bits, scalar d=1. + const std::vector der{0x30, 0x0a, 0x03, 0x02, 0x06, 0xc0, + 0x02, 0x01, 0x20, 0x02, 0x01, 0x01}; + const auto decoded = Util::base64Encode(der); + std::vector obfuscated(decoded.begin(), decoded.end()); + constexpr std::string_view key = + "b9dfaa7bee6ac57ac7b65f1094a1c155e747327bc2fe5d51c512023fe54a2802" + "01004e90ad1daaae1075d53b7d571c30e063b5a62a4a017bb394833aa0983e6e"; + // Real exported identities are longer than 20 bytes. Pad the base64 + // text with whitespace, which the decoder accepts, to exercise the + // exact TeamSpeak obfuscation algorithm. + obfuscated.resize(32, static_cast(' ')); + for (size_t i = 20; i < obfuscated.size(); ++i) { + obfuscated[i] ^= static_cast(key[i]); + } + const auto hash = Crypto::sha1(Crypto::ByteView( + obfuscated.data() + 20, obfuscated.size() - 20)); + for (size_t i = 0; i < 20; ++i) { + obfuscated[i] ^= + static_cast(key[i]) ^ hash[i]; + } + return std::to_string(offset) + "V" + Util::base64Encode(obfuscated); + } +} + +TEST_CASE(identity_import_teamspeak_ini) +{ + const std::string exportPath = "/tmp/echoion_ts_identity.ini"; + const std::string nativePath = "/tmp/echoion_imported_identity.txt"; + { + std::ofstream output(exportPath); + output << "[Identity]\nidentity=\"" << teamSpeakExportForScalarOne(42) + << "\"\n"; + } + const auto imported = Identity::importTeamSpeakIni(exportPath); + CHECK_EQ(imported.keyOffset(), uint64_t{42}); + CHECK(!imported.uid().empty()); + CHECK(!imported.sign({reinterpret_cast("x"), 1}).empty()); + imported.save(nativePath); + const auto loaded = Identity::load(nativePath); + CHECK_EQ(loaded.uid(), imported.uid()); + const auto permissions = std::filesystem::status(nativePath).permissions(); + CHECK((permissions & std::filesystem::perms::group_all) == + std::filesystem::perms::none); + CHECK((permissions & std::filesystem::perms::others_all) == + std::filesystem::perms::none); + std::remove(exportPath.c_str()); + std::remove(nativePath.c_str()); +} + +TEST_CASE(identity_import_rejects_malformed_export) +{ + const std::string path = "/tmp/echoion_bad_identity.ini"; + { + std::ofstream output(path); + output << "[Identity]\nidentity=not-a-private-key\n"; + } + bool rejected = false; + try { + (void)Identity::importTeamSpeakIni(path); + } catch (const std::exception&) { + rejected = true; + } + CHECK(rejected); + std::remove(path.c_str()); +}