Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-11 15:06:22 +03:00
commit 38e86d4a07
23 files changed
+3219

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
#pragma once
// TS3 command wire format: "commandname key=value key=value|key=value".
// Ported from ts6-manager tslib/commands.ts.
#include <map>
#include <string>
#include <vector>
namespace Echoion::Protocol
{
// Escape / unescape a single token per the TS3 rules
// (\\ \/ \s \p \f \n \r \t \v).
std::string tsEscape(const std::string& str);
std::string tsUnescape(const std::string& str);
// Ordered key/value params for a command. std::map keeps a stable order so
// serialization is deterministic (helpful for tests); the server does not
// care about ordering.
using CommandParams = std::map<std::string, std::string>;
struct ParsedCommand {
std::string name;
CommandParams params; // first group
std::vector<CommandParams> groups; // all '|'-separated groups
};
// Serialize "name k=v k=v". Empty values are emitted as "k=".
std::string buildCommand(const std::string& name,
const CommandParams& params);
// Parse a raw command / notify line into name + params (+ pipe groups).
ParsedCommand parseCommand(const std::string& raw);
} // namespace Echoion::Protocol
+88
View File
@@ -0,0 +1,88 @@
#pragma once
// Low-level cryptographic primitives for the TeamSpeak 3/6 full-client voice
// protocol. Ported byte-for-byte from ts6-manager's tslib/crypto.ts (MIT) so the
// on-wire behaviour is identical; implemented over OpenSSL EVP.
//
// The protocol uses AES-128-EAX for per-packet authenticated encryption. OpenSSL
// has no native EAX, so — exactly like the reference — we compose it from
// AES-128-CTR (confidentiality) and AES-128-CMAC / OMAC1 (authenticity).
#include <array>
#include <cstdint>
#include <optional>
#include <span>
#include <string>
#include <vector>
namespace Echoion::Protocol::Crypto
{
using Bytes = std::vector<uint8_t>;
using ByteView = std::span<const uint8_t>;
inline constexpr size_t BLOCK_SIZE = 16;
inline constexpr size_t MAC_LEN = 8;
// "TS3INIT1" — the fake/static MAC stamped on low-level init packets before a
// shared secret exists.
inline constexpr std::array<uint8_t, 8> INIT_MAC = {'T', 'S', '3', 'I',
'N', 'I', 'T', '1'};
// "c:\\windows\\syste" / "m\\firewall32.cpl" — the fixed key/nonce used to
// (de)crypt command packets during the handshake, before key exchange.
inline constexpr std::array<uint8_t, 16> DUMMY_KEY = {
'c', ':', '\\', 'w', 'i', 'n', 'd', 'o',
'w', 's', '\\', 's', 'y', 's', 't', 'e'};
inline constexpr std::array<uint8_t, 16> DUMMY_NONCE = {
'm', '\\', 'f', 'i', 'r', 'e', 'w', 'a',
'l', 'l', '3', '2', '.', 'c', 'p', 'l'};
// Client version signature used in clientinit (3.5.0 [Stable]).
inline constexpr uint32_t INIT_VERSION = 1566914096u;
// --- Hashes -------------------------------------------------------------
std::array<uint8_t, 20> sha1(ByteView data);
std::array<uint8_t, 32> sha256(ByteView data);
std::array<uint8_t, 64> sha512(ByteView data);
// --- XOR helpers --------------------------------------------------------
// out[i] = a[i] ^ b[i] for i in [0, min(a,b)).
Bytes xorBuffers(ByteView a, ByteView b);
// a[i] ^= b[i] for i in [0, len). Caller guarantees bounds.
void xorInto(std::span<uint8_t> a, ByteView b, size_t len);
// --- AES-128-CMAC (OMAC1) ----------------------------------------------
// 16-byte MAC over `data` under the 16-byte `key`.
std::array<uint8_t, BLOCK_SIZE> cmac(ByteView key, ByteView data);
// --- AES-128-EAX --------------------------------------------------------
struct EaxResult {
Bytes ciphertext;
std::array<uint8_t, MAC_LEN> mac;
};
// Encrypt `plaintext` with 16-byte `key`, `nonce` and associated `header`.
EaxResult eaxEncrypt(ByteView key, ByteView nonce, ByteView header,
ByteView plaintext);
// Decrypt/verify; returns nullopt on MAC mismatch.
std::optional<Bytes> eaxDecrypt(ByteView key, ByteView nonce,
ByteView header, ByteView ciphertext,
ByteView mac);
// --- Per-packet key/nonce derivation -----------------------------------
struct KeyNonce {
std::array<uint8_t, 16> key;
std::array<uint8_t, 16> nonce;
};
// Derive the packet key+nonce from the connection `ivStruct` (20 bytes for
// the SHA1 handshake secret, 64 bytes for the license path), keyed by
// direction, packet id, generation and packet type.
KeyNonce deriveKeyNonce(bool fromServer, uint16_t packetId,
uint32_t generationId, uint8_t packetType,
ByteView ivStruct);
// --- Misc ---------------------------------------------------------------
// base64(sha1(utf8(password))); empty string for empty password.
std::string hashPassword(const std::string& password);
} // namespace Echoion::Protocol::Crypto
+62
View File
@@ -0,0 +1,62 @@
#pragma once
// TeamSpeak client identity: an ECDSA P-256 keypair plus the libtomcrypt-style
// public-key export ("omega"), the derived unique-id, and the hashcash
// key-offset that raises the identity's "security level".
// Ported from ts6-manager tslib/identity.ts.
#include <cstdint>
#include <memory>
#include <span>
#include <string>
#include <vector>
namespace Echoion::Protocol
{
class Identity
{
public:
using Bytes = std::vector<uint8_t>;
using ByteView = std::span<const uint8_t>;
// Generate a fresh identity and raise it to at least `securityLevel`
// leading-zero bits (hashcash over the public key + offset).
static Identity generate(int securityLevel = 8);
// Load / save the identity to a small text file:
// privateKeyPem, publicKeyString, keyOffset (one per line).
static Identity load(const std::string& path);
void save(const std::string& path) const;
// libtomcrypt ASN.1 public key, base64 ("omega" in clientinitiv).
const std::string& publicKeyString() const { return publicKeyString_; }
// base64(sha1(ascii(publicKeyString))).
const std::string& uid() const { return uid_; }
uint64_t keyOffset() const { return keyOffset_; }
int securityLevel() const;
// ECDSA sign `data` with SHA-256; returns the raw signature.
Bytes sign(ByteView data) const;
// ECDH(this private key, server public key) → SHA-1 of the shared
// x-coordinate. `serverPublicKeyDer` is the libtomcrypt DER blob
// (base64-decoded "omega" from initivexpand).
Bytes sharedSecret(ByteView serverPublicKeyDer) const;
private:
Identity() = default;
struct PKeyDeleter {
void operator()(void* p) const noexcept;
};
// EVP_PKEY* held opaquely so this header stays OpenSSL-free.
std::shared_ptr<void> pkey_;
std::string publicKeyString_;
std::string uid_;
uint64_t keyOffset_ = 0;
};
} // namespace Echoion::Protocol
+45
View File
@@ -0,0 +1,45 @@
#pragma once
// TeamSpeak license chain handling for the modern handshake (initivexpand2).
// The chain is walked with Ed25519 point arithmetic (scalar-mult + point-add),
// which OpenSSL does not expose, so this module uses libsodium.
// Ported from ts6-manager tslib/license.ts.
#include <array>
#include <cstdint>
#include <span>
#include <vector>
namespace Echoion::Protocol
{
using Bytes = std::vector<uint8_t>;
using ByteView = std::span<const uint8_t>;
struct LicenseBlock {
std::array<uint8_t, 32> key;
std::array<uint8_t, 32> hash; // first 32 bytes of SHA-512(content)
uint8_t type = 0;
};
struct TempKey {
std::array<uint8_t, 32> publicKey;
std::array<uint8_t, 32> privateKey;
};
// Parse the server license blob into its chain of blocks.
std::vector<LicenseBlock> parseLicense(ByteView data);
// Walk the chain from the root key to the final server public key (32 bytes).
std::array<uint8_t, 32>
deriveLicenseKey(const std::vector<LicenseBlock>& blocks);
// Generate an ephemeral Ed25519 keypair (clamped like the reference).
TempKey generateTemporaryKey();
// initivexpand2 shared secret: SHA-512( tempPriv * serverDerivedKey ),
// 64 bytes. Returns the raw digest.
std::array<uint8_t, 64>
getSharedSecret2(ByteView serverDerivedKey, ByteView tempPrivateKey);
} // namespace Echoion::Protocol
+23
View File
@@ -0,0 +1,23 @@
#pragma once
// QuickLZ level-1 decompression, used to inflate compressed command packets.
// Clients send commands uncompressed, so only decompression is needed.
// Ported from ts6-manager tslib/quicklz.ts (itself from TSLib QuickerLz.cs).
#include <cstdint>
#include <span>
#include <vector>
namespace Echoion::Protocol
{
using Bytes = std::vector<uint8_t>;
using ByteView = std::span<const uint8_t>;
uint32_t qlzDecompressedSize(ByteView data);
uint32_t qlzCompressedSize(ByteView data);
// Throws std::runtime_error on malformed input or unsupported level.
Bytes qlzDecompress(ByteView data);
} // namespace Echoion::Protocol
+195
View File
@@ -0,0 +1,195 @@
#pragma once
// Full-client connection to a TeamSpeak 3/6 server over the native UDP voice
// protocol. Owns the socket, handshake, per-packet crypto, resend/keepalive and
// voice send path. Ported from ts6-manager tslib/client.ts.
//
// Threading: a single background thread runs the receive + timer loop. Public
// send methods are thread-safe (guarded by an internal mutex) so the audio
// thread can call sendVoice() directly. Callbacks fire on the loop thread.
#include "echoion/protocol/Command.hpp"
#include "echoion/protocol/Identity.hpp"
#include <atomic>
#include <cstdint>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <span>
#include <string>
#include <thread>
#include <vector>
namespace Echoion::Protocol
{
enum class PacketType : uint8_t {
Voice = 0,
VoiceWhisper = 1,
Command = 2,
CommandLow = 3,
Ping = 4,
Pong = 5,
Ack = 6,
AckLow = 7,
Init1 = 8,
};
enum class ClientState {
Disconnected,
Init,
Handshake,
Connected,
Disconnecting,
};
struct TsClientOptions {
std::string host;
uint16_t port = 9987;
const Identity* identity = nullptr; // not owned
std::string nickname = "EchoionBot";
std::string serverPassword;
std::string defaultChannel; // channel id or name
std::string channelPassword;
};
// All callbacks fire on the internal loop thread.
struct TsClientCallbacks {
std::function<void()> onConnected;
std::function<void()> onDisconnected;
std::function<void(const std::string&)> onError;
std::function<void(const ParsedCommand&)> onCommand;
std::function<void(const CommandParams&)> onTextMessage;
std::function<void(std::span<const uint8_t>)> onVoice;
std::function<void(const std::string&)> onDebug;
};
class TsClient
{
public:
TsClient();
~TsClient();
TsClient(const TsClient&) = delete;
TsClient& operator=(const TsClient&) = delete;
void setCallbacks(TsClientCallbacks cb) { cb_ = std::move(cb); }
// Begin connecting. Returns immediately; onConnected/onError fire
// asynchronously. Throws only on immediate socket setup failure.
void connect(const TsClientOptions& opts);
// Graceful: send clientdisconnect, then close.
void disconnect();
// Immediate close, no disconnect command.
void forceClose();
ClientState state() const { return state_.load(); }
uint16_t clientId() const { return clientId_.load(); }
// Send one already-Opus-encoded 20 ms frame to the current channel.
void sendVoice(std::span<const uint8_t> opus);
// Whisper the frame to the given channel/client targets.
void sendWhisper(std::span<const uint8_t> opus,
const std::vector<uint64_t>& channelIds,
const std::vector<uint16_t>& clientIds);
// End-of-voice marker (empty frame).
void sendVoiceStop();
// Send a raw pre-built TS3 command line (fragmented if large).
void sendCommand(const std::string& cmd);
private:
// ---- packet path ----
void loopThread();
void handleIncomingPacket(std::span<const uint8_t> raw);
void sendOutgoing(std::span<const uint8_t> data, PacketType type,
uint8_t extraFlags = 0);
std::vector<uint8_t> buildRawPacket(std::span<const uint8_t> data,
PacketType type,
uint16_t packetId,
uint8_t flags);
void encryptPacket(std::vector<uint8_t>& raw, PacketType type,
uint16_t packetId, uint32_t gen, uint8_t flags,
std::span<const uint8_t> data);
std::vector<uint8_t> decryptPacket(std::span<const uint8_t> raw,
PacketType type,
uint16_t packetId, uint32_t gen,
uint8_t flags, bool& ok);
void sendRawLocked(const std::vector<uint8_t>& raw);
void sendInitPacket(const std::vector<uint8_t>& data);
// ---- handshake / commands ----
std::vector<uint8_t> buildInit0();
void handleInit(std::span<const uint8_t> data);
void handleCommandData(std::span<const uint8_t> data, uint8_t flags);
void processCommand(std::span<const uint8_t> data, uint8_t flags);
void handleInitIvExpand(const CommandParams& params);
void handleInitIvExpand2(const CommandParams& params);
void sendClientInit();
void handleInitServer(const CommandParams& params);
void handleChannelList(const ParsedCommand& parsed);
void handleChannelListFinished();
void sendAck(uint16_t ackId, PacketType ackType);
void handlePing(uint16_t packetId);
void resendTick();
void debug(const std::string& msg);
void cleanup();
// counters / crypto
struct Counter {
uint16_t id = 0;
uint32_t gen = 0;
};
Counter getCounter(PacketType type);
void incCounter(PacketType type);
TsClientOptions opts_;
TsClientCallbacks cb_;
int sock_ = -1;
std::atomic<ClientState> state_{ClientState::Disconnected};
std::atomic<uint16_t> clientId_{0};
std::thread thread_;
std::atomic<bool> running_{false};
// Recursive: command handlers running under the loop lock call
// sendCommand()/sendOutgoing() which re-lock.
mutable std::recursive_mutex mu_;
int64_t disconnectDeadline_ = 0;
std::array<uint16_t, 9> packetCounter_{};
std::array<uint32_t, 9> generationCounter_{};
bool cryptoInitComplete_ = false;
std::vector<uint8_t> ivStruct_;
std::array<uint8_t, 8> fakeSignature_{};
std::vector<uint8_t> alphaTmp_;
// resend tracking
struct Resend {
std::vector<uint8_t> raw;
uint16_t packetId = 0;
int64_t firstSend = 0;
int64_t lastSend = 0;
};
std::map<uint16_t, Resend> resendMap_;
std::unique_ptr<Resend> initResend_;
int64_t lastMessageTime_ = 0;
int64_t lastPing_ = 0;
int64_t connectStart_ = 0;
// fragment reassembly
std::vector<uint8_t> fragmentBuffer_;
bool fragmenting_ = false;
uint8_t fragmentFlags_ = 0;
// channel map for auto-move
std::map<std::string, uint64_t> channelMap_;
};
} // namespace Echoion::Protocol
+24
View File
@@ -0,0 +1,24 @@
#pragma once
// Small dependency-free encoding helpers shared across the protocol modules.
#include <cstdint>
#include <span>
#include <string>
#include <vector>
namespace Echoion::Protocol::Util
{
using Bytes = std::vector<uint8_t>;
using ByteView = std::span<const uint8_t>;
// Standard base64 (RFC 4648) with '+' '/' and '=' padding.
std::string base64Encode(ByteView data);
Bytes base64Decode(const std::string& text);
// Lowercase hex, no separators.
std::string toHex(ByteView data);
Bytes fromHex(const std::string& hex);
} // namespace Echoion::Protocol::Util