Files
VoidTeamspeak/src/Identity.cpp
T
faumaray c1a11ffe29 Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-12 02:34:34 +03:00

676 lines
19 KiB
C++

#include "Void/TeamSpeak/Protocol/Identity.hpp"
#include "Void/TeamSpeak/Protocol/Crypto.hpp"
#include "Void/TeamSpeak/Protocol/Util.hpp"
#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 Void::TeamSpeak::Protocol
{
namespace
{
using Bytes = std::vector<uint8_t>;
[[noreturn]] void fail(const char* what)
{
throw std::runtime_error(std::string("Identity: ") + what);
}
EVP_PKEY* asPkey(const std::shared_ptr<void>& p)
{
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)
{
int n = BN_num_bytes(bn);
Bytes out(static_cast<size_t>(n < 0 ? 0 : n), 0);
if (n > 0) {
BN_bn2bin(bn, out.data());
}
return out;
}
Bytes derLength(size_t len)
{
if (len < 0x80) {
return {static_cast<uint8_t>(len)};
}
if (len < 0x100) {
return {0x81, static_cast<uint8_t>(len)};
}
return {0x82, static_cast<uint8_t>((len >> 8) & 0xff),
static_cast<uint8_t>(len & 0xff)};
}
// DER INTEGER from a non-negative big-endian magnitude.
Bytes derInteger(Bytes mag)
{
if (mag.empty()) {
mag.push_back(0);
}
if (mag[0] & 0x80) {
mag.insert(mag.begin(), 0x00);
}
Bytes out;
out.push_back(0x02);
Bytes len = derLength(mag.size());
out.insert(out.end(), len.begin(), len.end());
out.insert(out.end(), mag.begin(), mag.end());
return out;
}
Bytes derIntegerFromU64(uint64_t v)
{
BIGNUM* bn = BN_new();
BN_set_word(bn, v);
Bytes r = derInteger(bnBytes(bn));
BN_free(bn);
return r;
}
// libtomcrypt public key: SEQ{ BITSTRING(00 07 00), INT(32), INT(x),
// INT(y) }. The BITSTRING carries a leading "unused bits" byte (0x00)
// plus 0x07 0x00 in the reference; we reproduce it verbatim.
std::string buildPublicKeyString(const BIGNUM* x, const BIGNUM* y)
{
Bytes content;
const uint8_t bitStr[] = {0x03, 0x02, 0x07, 0x00};
content.insert(content.end(), std::begin(bitStr), std::end(bitStr));
Bytes i32 = derIntegerFromU64(32);
Bytes ix = derInteger(bnBytes(x));
Bytes iy = derInteger(bnBytes(y));
content.insert(content.end(), i32.begin(), i32.end());
content.insert(content.end(), ix.begin(), ix.end());
content.insert(content.end(), iy.begin(), iy.end());
Bytes der;
der.push_back(0x30);
Bytes len = derLength(content.size());
der.insert(der.end(), len.begin(), len.end());
der.insert(der.end(), content.begin(), content.end());
return Util::base64Encode(Crypto::ByteView(der.data(), der.size()));
}
// Uncompressed EC point (0x04 || x || y) from a public EVP_PKEY.
Bytes pubPoint(EVP_PKEY* pkey)
{
size_t len = 0;
if (EVP_PKEY_get_octet_string_param(
pkey, OSSL_PKEY_PARAM_PUB_KEY, nullptr, 0, &len) != 1) {
fail("cannot read public point length");
}
Bytes buf(len, 0);
if (EVP_PKEY_get_octet_string_param(pkey, OSSL_PKEY_PARAM_PUB_KEY,
buf.data(), len, &len) != 1) {
fail("cannot read public point");
}
buf.resize(len);
return buf;
}
int countLeadingZeroBits(Crypto::ByteView data)
{
int count = 0;
for (uint8_t b : data) {
if (b == 0) {
count += 8;
} else {
for (int bit = 0; bit < 8; ++bit) {
if ((b & (1 << bit)) == 0) {
++count;
} else {
return count;
}
}
}
}
return count;
}
int securityLevelFor(const std::string& pubKeyString, uint64_t offset)
{
std::string s = pubKeyString + std::to_string(offset);
auto h = Crypto::sha1(Crypto::ByteView(
reinterpret_cast<const uint8_t*>(s.data()), s.size()));
return countLeadingZeroBits(
Crypto::ByteView(h.data(), h.size()));
}
// libtomcrypt DER parse → the two public-key INTEGERs (x, y). See
// reference parseDerSequence: collected = [bitByte, 32, x, y].
void parseServerPub(Crypto::ByteView der, BIGNUM** x, BIGNUM** y)
{
size_t pos = 0;
auto readLen = [&](size_t& p) -> size_t {
uint8_t first = der[p++];
if (first < 0x80) {
return first;
}
int nb = first & 0x7f;
size_t len = 0;
for (int i = 0; i < nb; ++i) {
len = (len << 8) | der[p++];
}
return len;
};
if (der.empty() || der[pos++] != 0x30) {
fail("server key: expected SEQUENCE");
}
readLen(pos);
std::vector<BIGNUM*> ints;
while (pos < der.size()) {
uint8_t tag = der[pos++];
size_t len = readLen(pos);
if (tag == 0x02) {
ints.push_back(
BN_bin2bn(der.data() + pos, static_cast<int>(len),
nullptr));
}
pos += len;
}
// ints = [32, x, y]; guard against short input.
if (ints.size() < 3) {
for (auto* b : ints) {
BN_free(b);
}
fail("server key: too few integers");
}
*x = ints[1];
*y = ints[2];
for (size_t i = 0; i < ints.size(); ++i) {
if (i != 1 && i != 2) {
BN_free(ints[i]);
}
}
}
} // namespace
void Identity::PKeyDeleter::operator()(void* p) const noexcept
{
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;
EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr);
if (!ctx) {
fail("keygen ctx");
}
if (EVP_PKEY_keygen_init(ctx) != 1) {
EVP_PKEY_CTX_free(ctx);
fail("keygen init");
}
OSSL_PARAM params[2] = {
OSSL_PARAM_construct_utf8_string(
OSSL_PKEY_PARAM_GROUP_NAME,
const_cast<char*>("prime256v1"), 0),
OSSL_PARAM_construct_end()};
EVP_PKEY_CTX_set_params(ctx, params);
if (EVP_PKEY_keygen(ctx, &pkey) != 1) {
EVP_PKEY_CTX_free(ctx);
fail("keygen");
}
EVP_PKEY_CTX_free(ctx);
Identity id;
id.pkey_ = std::shared_ptr<void>(pkey, PKeyDeleter{});
Bytes point = pubPoint(pkey);
if (point.size() != 65 || point[0] != 0x04) {
fail("unexpected public point format");
}
BIGNUM* x = BN_bin2bn(point.data() + 1, 32, nullptr);
BIGNUM* y = BN_bin2bn(point.data() + 33, 32, nullptr);
id.publicKeyString_ = buildPublicKeyString(x, y);
BN_free(x);
BN_free(y);
auto uidHash = Crypto::sha1(Crypto::ByteView(
reinterpret_cast<const uint8_t*>(id.publicKeyString_.data()),
id.publicKeyString_.size()));
id.uid_ = Util::base64Encode(
Crypto::ByteView(uidHash.data(), uidHash.size()));
// Hashcash: find the offset giving the most leading-zero bits, up to
// the requested level.
if (securityLevel > 0) {
uint64_t offset = 0;
int best = securityLevelFor(id.publicKeyString_, offset);
uint64_t checked = 0;
while (best < securityLevel) {
++checked;
int curr = securityLevelFor(id.publicKeyString_, checked);
if (curr > best) {
best = curr;
offset = checked;
}
}
id.keyOffset_ = offset;
}
return id;
}
int Identity::securityLevel() const
{
return securityLevelFor(publicKeyString_, keyOffset_);
}
Identity::Bytes Identity::sign(ByteView data) const
{
EVP_PKEY* pkey = asPkey(pkey_);
EVP_MD_CTX* md = EVP_MD_CTX_new();
if (!md) {
fail("sign ctx");
}
size_t siglen = 0;
if (EVP_DigestSignInit(md, nullptr, EVP_sha256(), nullptr, pkey) != 1 ||
EVP_DigestSign(md, nullptr, &siglen, data.data(), data.size()) !=
1) {
EVP_MD_CTX_free(md);
fail("sign init");
}
Bytes sig(siglen, 0);
if (EVP_DigestSign(md, sig.data(), &siglen, data.data(), data.size()) !=
1) {
EVP_MD_CTX_free(md);
fail("sign");
}
sig.resize(siglen);
EVP_MD_CTX_free(md);
return sig;
}
Identity::Bytes Identity::sharedSecret(ByteView serverPublicKeyDer) const
{
BIGNUM* x = nullptr;
BIGNUM* y = nullptr;
parseServerPub(serverPublicKeyDer, &x, &y);
// Build uncompressed point 0x04 || x(32) || y(32).
Bytes point(65, 0);
point[0] = 0x04;
BN_bn2binpad(x, point.data() + 1, 32);
BN_bn2binpad(y, point.data() + 33, 32);
BN_free(x);
BN_free(y);
EVP_PKEY* peer = nullptr;
{
OSSL_PARAM_BLD* bld = OSSL_PARAM_BLD_new();
OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_GROUP_NAME,
"prime256v1", 0);
OSSL_PARAM_BLD_push_octet_string(bld, OSSL_PKEY_PARAM_PUB_KEY,
point.data(), point.size());
OSSL_PARAM* p = OSSL_PARAM_BLD_to_param(bld);
EVP_PKEY_CTX* pctx =
EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr);
if (!pctx || EVP_PKEY_fromdata_init(pctx) != 1 ||
EVP_PKEY_fromdata(pctx, &peer, EVP_PKEY_PUBLIC_KEY, p) != 1) {
if (pctx) {
EVP_PKEY_CTX_free(pctx);
}
OSSL_PARAM_free(p);
OSSL_PARAM_BLD_free(bld);
fail("build peer key");
}
EVP_PKEY_CTX_free(pctx);
OSSL_PARAM_free(p);
OSSL_PARAM_BLD_free(bld);
}
EVP_PKEY_CTX* dctx = EVP_PKEY_CTX_new(asPkey(pkey_), nullptr);
size_t secretLen = 0;
if (!dctx || EVP_PKEY_derive_init(dctx) != 1 ||
EVP_PKEY_derive_set_peer(dctx, peer) != 1 ||
EVP_PKEY_derive(dctx, nullptr, &secretLen) != 1) {
if (dctx) {
EVP_PKEY_CTX_free(dctx);
}
EVP_PKEY_free(peer);
fail("ecdh derive init");
}
Bytes secret(secretLen, 0);
if (EVP_PKEY_derive(dctx, secret.data(), &secretLen) != 1) {
EVP_PKEY_CTX_free(dctx);
EVP_PKEY_free(peer);
fail("ecdh derive");
}
secret.resize(secretLen);
EVP_PKEY_CTX_free(dctx);
EVP_PKEY_free(peer);
// Pad/truncate to 32 bytes, then SHA-1 (matches reference).
Bytes keyArr(32, 0);
if (secret.size() >= 32) {
std::copy(secret.end() - 32, secret.end(), keyArr.begin());
} else {
std::copy(secret.begin(), secret.end(),
keyArr.begin() + (32 - secret.size()));
}
auto h = Crypto::sha1(Crypto::ByteView(keyArr.data(), keyArr.size()));
return Bytes(h.begin(), h.end());
}
void Identity::save(const std::string& path) const
{
EVP_PKEY* pkey = asPkey(pkey_);
BIO* mem = BIO_new(BIO_s_mem());
if (!PEM_write_bio_PrivateKey(mem, pkey, nullptr, nullptr, 0, nullptr,
nullptr)) {
BIO_free(mem);
fail("serialize private key");
}
char* data = nullptr;
long n = BIO_get_mem_data(mem, &data);
std::string pem(data, static_cast<size_t>(n));
BIO_free(mem);
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");
}
out << "ECHOION_IDENTITY_V1\n";
out << keyOffset_ << "\n";
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)
{
std::ifstream in(path);
if (!in) {
fail("cannot open identity file");
}
std::string magic;
std::getline(in, magic);
if (magic != "ECHOION_IDENTITY_V1") {
fail("bad identity file magic");
}
std::string offsetLine;
std::getline(in, offsetLine);
Identity id;
id.keyOffset_ = std::stoull(offsetLine);
std::getline(in, id.publicKeyString_);
std::string sep;
std::getline(in, sep); // -----PRIVATE-----
std::string pem((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
BIO* mem = BIO_new_mem_buf(pem.data(), static_cast<int>(pem.size()));
EVP_PKEY* pkey = PEM_read_bio_PrivateKey(mem, nullptr, nullptr, nullptr);
BIO_free(mem);
if (!pkey) {
fail("cannot parse private key");
}
id.pkey_ = std::shared_ptr<void>(pkey, PKeyDeleter{});
auto uidHash = Crypto::sha1(Crypto::ByteView(
reinterpret_cast<const uint8_t*>(id.publicKeyString_.data()),
id.publicKeyString_.size()));
id.uid_ = Util::base64Encode(
Crypto::ByteView(uidHash.data(), uidHash.size()));
return id;
}
} // namespace Void::TeamSpeak::Protocol