1 parent
38e86d4a07
commit
6dddf513b3
6 files changed
+600
-3
No files matched your search
@@ -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 "<offset>V<base64>" key.
|
||||
static Identity importTeamSpeakIni(const std::string& path);
|
||||
void save(const std::string& path) const;
|
||||
|
||||
// libtomcrypt ASN.1 public key, base64 ("omega" in clientinitiv).
|
||||
|
||||
@@ -12,7 +12,10 @@
|
||||
#include "echoion/protocol/Identity.hpp"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
@@ -66,6 +69,14 @@ namespace Echoion::Protocol
|
||||
std::function<void(const std::string&)> onDebug;
|
||||
};
|
||||
|
||||
struct CommandResult {
|
||||
std::vector<CommandParams> 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<std::string, uint64_t> channelMap_;
|
||||
|
||||
struct PendingRequest {
|
||||
CommandResult result;
|
||||
std::string returnCode;
|
||||
bool completed = false;
|
||||
std::condition_variable cv;
|
||||
};
|
||||
std::mutex requestSerialMutex_;
|
||||
std::mutex pendingMutex_;
|
||||
std::deque<std::shared_ptr<PendingRequest>> pendingRequests_;
|
||||
std::atomic<uint64_t> requestId_{0};
|
||||
std::atomic<uint16_t> transferId_{0};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Protocol
|
||||
+6
-2
@@ -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];
|
||||
|
||||
+250
-1
@@ -4,13 +4,20 @@
|
||||
|
||||
#include <openssl/bn.h>
|
||||
#include <openssl/core_names.h>
|
||||
#include <openssl/ec.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/param_build.h>
|
||||
#include <openssl/pem.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <regex>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
|
||||
namespace Echoion::Protocol
|
||||
{
|
||||
@@ -28,6 +35,151 @@ namespace Echoion::Protocol
|
||||
return static_cast<EVP_PKEY*>(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<size_t>(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<BIGNUM*> 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<int>(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<uint8_t, 65> 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<EVP_PKEY*>(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<char>(input)),
|
||||
std::istreambuf_iterator<char>());
|
||||
// TeamSpeak's exported value is <valid-key-offset>V<base64>. 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<size_t>(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<uint8_t>(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<void>(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<const uint8_t*>(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<size_t>(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)
|
||||
|
||||
@@ -13,8 +13,12 @@
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
|
||||
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<std::recursive_mutex> 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<std::mutex> serialLock(requestSerialMutex_);
|
||||
auto pending = std::make_shared<PendingRequest>();
|
||||
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<std::recursive_mutex> sendLock(mu_);
|
||||
if (state_.load() != ClientState::Connected) {
|
||||
return {{}, -1, "client is not connected"};
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> pendingLock(pendingMutex_);
|
||||
pendingRequests_.push_back(pending);
|
||||
}
|
||||
sendCommand(cmd + " return_code=" + pending->returnCode);
|
||||
}
|
||||
|
||||
std::unique_lock<std::mutex> 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<long>(
|
||||
std::max<int64_t>(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<size_t>(count);
|
||||
}
|
||||
if (!output || keySent != transferKey.size()) {
|
||||
::close(transferSocket);
|
||||
std::filesystem::remove(temporary);
|
||||
return {{}, -1, "cannot start file transfer"};
|
||||
}
|
||||
std::array<char, 81920> 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<uint64_t>(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<const uint8_t> opus)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
||||
@@ -660,6 +834,47 @@ namespace Echoion::Protocol
|
||||
}
|
||||
|
||||
const std::string& name = parsed.name;
|
||||
if (name == "error") {
|
||||
std::shared_ptr<PendingRequest> pending;
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<std::mutex> 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<std::shared_ptr<PendingRequest>> pending;
|
||||
{
|
||||
std::lock_guard<std::mutex> 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
|
||||
@@ -4,6 +4,8 @@
|
||||
#include "echoion/protocol/Util.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
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<uint8_t> der{0x30, 0x0a, 0x03, 0x02, 0x06, 0xc0,
|
||||
0x02, 0x01, 0x20, 0x02, 0x01, 0x01};
|
||||
const auto decoded = Util::base64Encode(der);
|
||||
std::vector<uint8_t> 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<uint8_t>(' '));
|
||||
for (size_t i = 20; i < obfuscated.size(); ++i) {
|
||||
obfuscated[i] ^= static_cast<uint8_t>(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<uint8_t>(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<const uint8_t*>("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());
|
||||
}
|
||||
Reference in new issue
Block a user