commit
38e86d4a07
23 files changed
+3219
No files matched your search
+184
@@ -0,0 +1,184 @@
|
||||
#include "echoion/protocol/Command.hpp"
|
||||
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Echoion::Protocol
|
||||
{
|
||||
|
||||
std::string tsEscape(const std::string& str)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(str.size());
|
||||
for (char c : str) {
|
||||
switch (c) {
|
||||
case '\\':
|
||||
out += "\\\\";
|
||||
break;
|
||||
case '/':
|
||||
out += "\\/";
|
||||
break;
|
||||
case ' ':
|
||||
out += "\\s";
|
||||
break;
|
||||
case '|':
|
||||
out += "\\p";
|
||||
break;
|
||||
case '\f':
|
||||
out += "\\f";
|
||||
break;
|
||||
case '\n':
|
||||
out += "\\n";
|
||||
break;
|
||||
case '\r':
|
||||
out += "\\r";
|
||||
break;
|
||||
case '\t':
|
||||
out += "\\t";
|
||||
break;
|
||||
case '\v':
|
||||
out += "\\v";
|
||||
break;
|
||||
default:
|
||||
out.push_back(c);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string tsUnescape(const std::string& str)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(str.size());
|
||||
for (size_t i = 0; i < str.size(); ++i) {
|
||||
if (str[i] == '\\') {
|
||||
if (++i >= str.size()) {
|
||||
throw std::runtime_error("invalid escape sequence");
|
||||
}
|
||||
switch (str[i]) {
|
||||
case '\\':
|
||||
out.push_back('\\');
|
||||
break;
|
||||
case '/':
|
||||
out.push_back('/');
|
||||
break;
|
||||
case 's':
|
||||
out.push_back(' ');
|
||||
break;
|
||||
case 'p':
|
||||
out.push_back('|');
|
||||
break;
|
||||
case 'f':
|
||||
out.push_back('\f');
|
||||
break;
|
||||
case 'n':
|
||||
out.push_back('\n');
|
||||
break;
|
||||
case 'r':
|
||||
out.push_back('\r');
|
||||
break;
|
||||
case 't':
|
||||
out.push_back('\t');
|
||||
break;
|
||||
case 'v':
|
||||
out.push_back('\v');
|
||||
break;
|
||||
default:
|
||||
throw std::runtime_error(std::string("unknown escape: \\") +
|
||||
str[i]);
|
||||
}
|
||||
} else {
|
||||
out.push_back(str[i]);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string buildCommand(const std::string& name,
|
||||
const CommandParams& params)
|
||||
{
|
||||
std::string cmd = tsEscape(name);
|
||||
for (const auto& [key, value] : params) {
|
||||
cmd += ' ';
|
||||
cmd += key;
|
||||
cmd += '=';
|
||||
cmd += tsEscape(value);
|
||||
}
|
||||
return cmd;
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
CommandParams parseGroup(const std::string& part)
|
||||
{
|
||||
CommandParams params;
|
||||
std::istringstream iss(part);
|
||||
std::string token;
|
||||
while (std::getline(iss, token, ' ')) {
|
||||
if (token.empty()) {
|
||||
continue;
|
||||
}
|
||||
auto eq = token.find('=');
|
||||
if (eq != std::string::npos) {
|
||||
params[token.substr(0, eq)] =
|
||||
tsUnescape(token.substr(eq + 1));
|
||||
} else {
|
||||
params[token] = "";
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
std::string trim(const std::string& s)
|
||||
{
|
||||
size_t a = s.find_first_not_of(" \t\r\n");
|
||||
if (a == std::string::npos) {
|
||||
return "";
|
||||
}
|
||||
size_t b = s.find_last_not_of(" \t\r\n");
|
||||
return s.substr(a, b - a + 1);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
ParsedCommand parseCommand(const std::string& raw)
|
||||
{
|
||||
// Split on '|' into groups.
|
||||
std::vector<std::string> parts;
|
||||
{
|
||||
std::string cur;
|
||||
for (char c : raw) {
|
||||
if (c == '|') {
|
||||
parts.push_back(cur);
|
||||
cur.clear();
|
||||
} else {
|
||||
cur.push_back(c);
|
||||
}
|
||||
}
|
||||
parts.push_back(cur);
|
||||
}
|
||||
|
||||
ParsedCommand out;
|
||||
std::string first = trim(parts[0]);
|
||||
|
||||
// The command name is the first whitespace-delimited token.
|
||||
std::string body;
|
||||
auto sp = first.find(' ');
|
||||
if (sp == std::string::npos) {
|
||||
out.name = tsUnescape(first);
|
||||
body = "";
|
||||
} else {
|
||||
out.name = tsUnescape(first.substr(0, sp));
|
||||
body = first.substr(sp + 1);
|
||||
}
|
||||
out.params = parseGroup(body);
|
||||
|
||||
if (parts.size() > 1) {
|
||||
out.groups.push_back(out.params);
|
||||
for (size_t g = 1; g < parts.size(); ++g) {
|
||||
out.groups.push_back(parseGroup(trim(parts[g])));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Protocol
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
#include "echoion/protocol/Crypto.hpp"
|
||||
#include "echoion/protocol/Util.hpp"
|
||||
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/sha.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Echoion::Protocol::Crypto
|
||||
{
|
||||
namespace
|
||||
{
|
||||
// Raw single-block AES-128-ECB encryption (no padding). Used to build
|
||||
// CMAC; matches the reference's aesEncryptBlock().
|
||||
std::array<uint8_t, BLOCK_SIZE> aesEncryptBlock(
|
||||
ByteView key, std::span<const uint8_t, BLOCK_SIZE> block)
|
||||
{
|
||||
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
|
||||
if (!ctx) {
|
||||
throw std::runtime_error("EVP_CIPHER_CTX_new failed");
|
||||
}
|
||||
std::array<uint8_t, BLOCK_SIZE> out{};
|
||||
int len = 0;
|
||||
if (EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), nullptr, key.data(),
|
||||
nullptr) != 1 ||
|
||||
EVP_CIPHER_CTX_set_padding(ctx, 0) != 1 ||
|
||||
EVP_EncryptUpdate(ctx, out.data(), &len, block.data(),
|
||||
static_cast<int>(BLOCK_SIZE)) != 1) {
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
throw std::runtime_error("AES-ECB block encrypt failed");
|
||||
}
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
return out;
|
||||
}
|
||||
|
||||
// GF(2^128) left-shift-by-one with the 0x87 reduction polynomial.
|
||||
std::array<uint8_t, BLOCK_SIZE> doubleBlock(
|
||||
const std::array<uint8_t, BLOCK_SIZE>& buf)
|
||||
{
|
||||
std::array<uint8_t, BLOCK_SIZE> out{};
|
||||
uint8_t carry = 0;
|
||||
for (int i = BLOCK_SIZE - 1; i >= 0; --i) {
|
||||
uint16_t tmp = static_cast<uint16_t>((buf[i] << 1) | carry);
|
||||
out[i] = static_cast<uint8_t>(tmp & 0xff);
|
||||
carry = (buf[i] >> 7) & 1;
|
||||
}
|
||||
if (carry) {
|
||||
out[BLOCK_SIZE - 1] ^= 0x87;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// EAX OMAC over a tag byte prepended in a leading block, then `data`.
|
||||
std::array<uint8_t, BLOCK_SIZE> eaxOmac(ByteView key, uint8_t tag,
|
||||
ByteView data)
|
||||
{
|
||||
Bytes input(BLOCK_SIZE + data.size(), 0);
|
||||
input[BLOCK_SIZE - 1] = tag;
|
||||
std::memcpy(input.data() + BLOCK_SIZE, data.data(), data.size());
|
||||
return cmac(key, input);
|
||||
}
|
||||
|
||||
// AES-128-CTR keystream applied to `in`, IV = `nonce`.
|
||||
Bytes aesCtr(ByteView key, std::span<const uint8_t, BLOCK_SIZE> nonce,
|
||||
ByteView in)
|
||||
{
|
||||
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
|
||||
if (!ctx) {
|
||||
throw std::runtime_error("EVP_CIPHER_CTX_new failed");
|
||||
}
|
||||
Bytes out(in.size(), 0);
|
||||
int len = 0;
|
||||
int total = 0;
|
||||
if (EVP_EncryptInit_ex(ctx, EVP_aes_128_ctr(), nullptr, key.data(),
|
||||
nonce.data()) != 1 ||
|
||||
EVP_EncryptUpdate(ctx, out.data(), &len, in.data(),
|
||||
static_cast<int>(in.size())) != 1) {
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
throw std::runtime_error("AES-CTR failed");
|
||||
}
|
||||
total = len;
|
||||
if (EVP_EncryptFinal_ex(ctx, out.data() + total, &len) != 1) {
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
throw std::runtime_error("AES-CTR final failed");
|
||||
}
|
||||
EVP_CIPHER_CTX_free(ctx);
|
||||
out.resize(static_cast<size_t>(total) + len);
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::array<uint8_t, 20> sha1(ByteView data)
|
||||
{
|
||||
std::array<uint8_t, 20> out{};
|
||||
::SHA1(data.data(), data.size(), out.data());
|
||||
return out;
|
||||
}
|
||||
|
||||
std::array<uint8_t, 32> sha256(ByteView data)
|
||||
{
|
||||
std::array<uint8_t, 32> out{};
|
||||
::SHA256(data.data(), data.size(), out.data());
|
||||
return out;
|
||||
}
|
||||
|
||||
std::array<uint8_t, 64> sha512(ByteView data)
|
||||
{
|
||||
std::array<uint8_t, 64> out{};
|
||||
::SHA512(data.data(), data.size(), out.data());
|
||||
return out;
|
||||
}
|
||||
|
||||
Bytes xorBuffers(ByteView a, ByteView b)
|
||||
{
|
||||
size_t len = std::min(a.size(), b.size());
|
||||
Bytes out(len, 0);
|
||||
for (size_t i = 0; i < len; ++i) {
|
||||
out[i] = a[i] ^ b[i];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void xorInto(std::span<uint8_t> a, ByteView b, size_t len)
|
||||
{
|
||||
for (size_t i = 0; i < len; ++i) {
|
||||
a[i] ^= b[i];
|
||||
}
|
||||
}
|
||||
|
||||
std::array<uint8_t, BLOCK_SIZE> cmac(ByteView key, ByteView data)
|
||||
{
|
||||
const std::array<uint8_t, BLOCK_SIZE> zero{};
|
||||
auto L = aesEncryptBlock(key, std::span<const uint8_t, BLOCK_SIZE>(
|
||||
zero.data(), BLOCK_SIZE));
|
||||
auto K1 = doubleBlock(L);
|
||||
auto K2 = doubleBlock(K1);
|
||||
|
||||
const size_t n = data.size();
|
||||
const size_t numBlocks = n == 0 ? 1 : (n + BLOCK_SIZE - 1) / BLOCK_SIZE;
|
||||
const bool lastComplete = n > 0 && n % BLOCK_SIZE == 0;
|
||||
|
||||
std::array<uint8_t, BLOCK_SIZE> x{};
|
||||
for (size_t i = 0; i + 1 < numBlocks; ++i) {
|
||||
std::array<uint8_t, BLOCK_SIZE> block{};
|
||||
std::memcpy(block.data(), data.data() + i * BLOCK_SIZE, BLOCK_SIZE);
|
||||
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
|
||||
block[j] ^= x[j];
|
||||
}
|
||||
x = aesEncryptBlock(key, std::span<const uint8_t, BLOCK_SIZE>(
|
||||
block.data(), BLOCK_SIZE));
|
||||
}
|
||||
|
||||
std::array<uint8_t, BLOCK_SIZE> last{};
|
||||
const size_t off = (numBlocks - 1) * BLOCK_SIZE;
|
||||
if (lastComplete) {
|
||||
std::memcpy(last.data(), data.data() + off, BLOCK_SIZE);
|
||||
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
|
||||
last[j] ^= K1[j];
|
||||
}
|
||||
} else {
|
||||
const size_t rem = n - off;
|
||||
std::memcpy(last.data(), data.data() + off, rem);
|
||||
last[rem] = 0x80;
|
||||
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
|
||||
last[j] ^= K2[j];
|
||||
}
|
||||
}
|
||||
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
|
||||
last[j] ^= x[j];
|
||||
}
|
||||
return aesEncryptBlock(key, std::span<const uint8_t, BLOCK_SIZE>(
|
||||
last.data(), BLOCK_SIZE));
|
||||
}
|
||||
|
||||
EaxResult eaxEncrypt(ByteView key, ByteView nonce, ByteView header,
|
||||
ByteView plaintext)
|
||||
{
|
||||
auto N = eaxOmac(key, 0, nonce);
|
||||
auto H = eaxOmac(key, 1, header);
|
||||
Bytes ciphertext = aesCtr(
|
||||
key, std::span<const uint8_t, BLOCK_SIZE>(N.data(), BLOCK_SIZE),
|
||||
plaintext);
|
||||
auto C = eaxOmac(key, 2, ciphertext);
|
||||
|
||||
EaxResult res;
|
||||
res.ciphertext = std::move(ciphertext);
|
||||
for (size_t i = 0; i < MAC_LEN; ++i) {
|
||||
res.mac[i] = N[i] ^ H[i] ^ C[i];
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
std::optional<Bytes> eaxDecrypt(ByteView key, ByteView nonce,
|
||||
ByteView header, ByteView ciphertext,
|
||||
ByteView mac)
|
||||
{
|
||||
auto N = eaxOmac(key, 0, nonce);
|
||||
auto H = eaxOmac(key, 1, header);
|
||||
auto C = eaxOmac(key, 2, ciphertext);
|
||||
|
||||
std::array<uint8_t, MAC_LEN> tag{};
|
||||
uint8_t diff = 0;
|
||||
for (size_t i = 0; i < MAC_LEN; ++i) {
|
||||
tag[i] = N[i] ^ H[i] ^ C[i];
|
||||
diff |= static_cast<uint8_t>(tag[i] ^ (i < mac.size() ? mac[i] : 0));
|
||||
}
|
||||
if (diff != 0 || mac.size() < MAC_LEN) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return aesCtr(key,
|
||||
std::span<const uint8_t, BLOCK_SIZE>(N.data(), BLOCK_SIZE),
|
||||
ciphertext);
|
||||
}
|
||||
|
||||
KeyNonce deriveKeyNonce(bool fromServer, uint16_t packetId,
|
||||
uint32_t generationId, uint8_t packetType,
|
||||
ByteView ivStruct)
|
||||
{
|
||||
const size_t tmpLen = ivStruct.size() == 20 ? 26 : 70;
|
||||
Bytes tmp(tmpLen, 0);
|
||||
tmp[0] = fromServer ? 0x30 : 0x31;
|
||||
tmp[1] = packetType;
|
||||
tmp[2] = static_cast<uint8_t>((generationId >> 24) & 0xff);
|
||||
tmp[3] = static_cast<uint8_t>((generationId >> 16) & 0xff);
|
||||
tmp[4] = static_cast<uint8_t>((generationId >> 8) & 0xff);
|
||||
tmp[5] = static_cast<uint8_t>(generationId & 0xff);
|
||||
std::memcpy(tmp.data() + 6, ivStruct.data(), ivStruct.size());
|
||||
|
||||
auto kn = sha256(tmp);
|
||||
KeyNonce out;
|
||||
std::memcpy(out.key.data(), kn.data(), 16);
|
||||
std::memcpy(out.nonce.data(), kn.data() + 16, 16);
|
||||
out.key[0] ^= static_cast<uint8_t>((packetId >> 8) & 0xff);
|
||||
out.key[1] ^= static_cast<uint8_t>(packetId & 0xff);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string hashPassword(const std::string& password)
|
||||
{
|
||||
if (password.empty()) {
|
||||
return "";
|
||||
}
|
||||
auto digest = sha1(ByteView(
|
||||
reinterpret_cast<const uint8_t*>(password.data()), password.size()));
|
||||
return Util::base64Encode(ByteView(digest.data(), digest.size()));
|
||||
}
|
||||
|
||||
} // namespace Echoion::Protocol::Crypto
|
||||
@@ -0,0 +1,426 @@
|
||||
#include "echoion/protocol/Identity.hpp"
|
||||
#include "echoion/protocol/Crypto.hpp"
|
||||
#include "echoion/protocol/Util.hpp"
|
||||
|
||||
#include <openssl/bn.h>
|
||||
#include <openssl/core_names.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/param_build.h>
|
||||
#include <openssl/pem.h>
|
||||
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::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());
|
||||
}
|
||||
|
||||
// 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::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);
|
||||
|
||||
std::ofstream out(path, 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;
|
||||
}
|
||||
|
||||
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 Echoion::Protocol
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
#include "echoion/protocol/License.hpp"
|
||||
#include "echoion/protocol/Crypto.hpp"
|
||||
|
||||
#include <sodium.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Echoion::Protocol
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[noreturn]] void fail(const char* what)
|
||||
{
|
||||
throw std::runtime_error(std::string("License: ") + what);
|
||||
}
|
||||
|
||||
void ensureSodium()
|
||||
{
|
||||
static std::once_flag once;
|
||||
static bool ok = false;
|
||||
std::call_once(once, [] { ok = sodium_init() >= 0; });
|
||||
if (!ok) {
|
||||
fail("libsodium init failed");
|
||||
}
|
||||
}
|
||||
|
||||
// Ed25519 point compressed root key.
|
||||
constexpr std::array<uint8_t, 32> LICENSE_ROOT_KEY = {
|
||||
0xcd, 0x0d, 0xe2, 0xae, 0xd4, 0x63, 0x45, 0x50, 0x9a, 0x7e, 0x3c,
|
||||
0xfd, 0x8f, 0x68, 0xb3, 0xdc, 0x75, 0x55, 0xb2, 0x9d, 0xcc, 0xec,
|
||||
0x73, 0xcd, 0x18, 0x75, 0x0f, 0x99, 0x38, 0x12, 0x40, 0x8a};
|
||||
|
||||
size_t findNullTerminator(ByteView data, size_t start)
|
||||
{
|
||||
for (size_t i = start; i < data.size(); ++i) {
|
||||
if (data[i] == 0) {
|
||||
return i - start;
|
||||
}
|
||||
}
|
||||
fail("non-null-terminated string in license");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::vector<LicenseBlock> parseLicense(ByteView data)
|
||||
{
|
||||
if (data.size() < 1) {
|
||||
fail("license too short");
|
||||
}
|
||||
if (data[0] != 1) {
|
||||
fail("unsupported license version");
|
||||
}
|
||||
|
||||
std::vector<LicenseBlock> blocks;
|
||||
size_t pos = 1;
|
||||
while (pos < data.size()) {
|
||||
if (data.size() - pos < 42) {
|
||||
fail("license block too short");
|
||||
}
|
||||
if (data[pos] != 0) {
|
||||
fail("wrong key kind");
|
||||
}
|
||||
|
||||
LicenseBlock block;
|
||||
std::memcpy(block.key.data(), data.data() + pos + 1, 32);
|
||||
const uint8_t blockType = data[pos + 33];
|
||||
block.type = blockType;
|
||||
|
||||
size_t extraLen = 0;
|
||||
switch (blockType) {
|
||||
case 0: // Intermediate
|
||||
extraLen = findNullTerminator(data, pos + 46) + 5;
|
||||
break;
|
||||
case 2: // Server
|
||||
extraLen = findNullTerminator(data, pos + 47) + 6;
|
||||
break;
|
||||
case 8: { // TS5 Server
|
||||
size_t p = pos + 44;
|
||||
const uint8_t propCount = data[pos + 43];
|
||||
for (uint8_t i = 0; i < propCount; ++i) {
|
||||
const uint8_t propLen = data[p];
|
||||
p += 1 + propLen;
|
||||
}
|
||||
extraLen = p - (pos + 42);
|
||||
break;
|
||||
}
|
||||
case 32: // Ephemeral
|
||||
extraLen = 0;
|
||||
break;
|
||||
default:
|
||||
fail("invalid license block type");
|
||||
}
|
||||
|
||||
const size_t blockLen = 42 + extraLen;
|
||||
if (pos + blockLen > data.size()) {
|
||||
fail("license block overruns buffer");
|
||||
}
|
||||
auto content = data.subspan(pos + 1, blockLen - 1);
|
||||
auto h = Crypto::sha512(content);
|
||||
std::memcpy(block.hash.data(), h.data(), 32);
|
||||
|
||||
blocks.push_back(block);
|
||||
pos += blockLen;
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
std::array<uint8_t, 32>
|
||||
deriveLicenseKey(const std::vector<LicenseBlock>& blocks)
|
||||
{
|
||||
ensureSodium();
|
||||
std::array<uint8_t, 32> parentKey = LICENSE_ROOT_KEY;
|
||||
|
||||
for (const auto& block : blocks) {
|
||||
// Clamp the block hash into an Ed25519 scalar.
|
||||
std::array<uint8_t, 32> scalar = block.hash;
|
||||
scalar[0] &= 0xf8;
|
||||
scalar[31] &= 0x3f;
|
||||
scalar[31] |= 0x40;
|
||||
|
||||
std::array<uint8_t, 32> mul{};
|
||||
if (crypto_scalarmult_ed25519_noclamp(mul.data(), scalar.data(),
|
||||
block.key.data()) != 0) {
|
||||
fail("ed25519 scalarmult failed");
|
||||
}
|
||||
std::array<uint8_t, 32> sum{};
|
||||
if (crypto_core_ed25519_add(sum.data(), mul.data(),
|
||||
parentKey.data()) != 0) {
|
||||
fail("ed25519 point add failed");
|
||||
}
|
||||
parentKey = sum;
|
||||
}
|
||||
return parentKey;
|
||||
}
|
||||
|
||||
TempKey generateTemporaryKey()
|
||||
{
|
||||
ensureSodium();
|
||||
TempKey out;
|
||||
randombytes_buf(out.privateKey.data(), out.privateKey.size());
|
||||
out.privateKey[0] &= 248;
|
||||
out.privateKey[31] &= 127;
|
||||
out.privateKey[31] |= 64;
|
||||
if (crypto_scalarmult_ed25519_base_noclamp(out.publicKey.data(),
|
||||
out.privateKey.data()) != 0) {
|
||||
fail("ed25519 base mult failed");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::array<uint8_t, 64> getSharedSecret2(ByteView serverDerivedKey,
|
||||
ByteView tempPrivateKey)
|
||||
{
|
||||
ensureSodium();
|
||||
if (serverDerivedKey.size() != 32 || tempPrivateKey.size() != 32) {
|
||||
fail("bad key length for shared secret");
|
||||
}
|
||||
std::array<uint8_t, 32> priv{};
|
||||
std::memcpy(priv.data(), tempPrivateKey.data(), 32);
|
||||
priv[31] &= 0x7f;
|
||||
|
||||
std::array<uint8_t, 32> mul{};
|
||||
if (crypto_scalarmult_ed25519_noclamp(mul.data(), priv.data(),
|
||||
serverDerivedKey.data()) != 0) {
|
||||
fail("ed25519 scalarmult failed");
|
||||
}
|
||||
return Crypto::sha512(ByteView(mul.data(), mul.size()));
|
||||
}
|
||||
|
||||
} // namespace Echoion::Protocol
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
#include "echoion/protocol/QuickLz.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Echoion::Protocol
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr int TABLE_SIZE = 4096;
|
||||
constexpr uint32_t MAX_DECOMPRESSED_SIZE = 1024 * 1024;
|
||||
|
||||
uint32_t readU32LE(ByteView b, size_t off)
|
||||
{
|
||||
return static_cast<uint32_t>(b[off]) |
|
||||
(static_cast<uint32_t>(b[off + 1]) << 8) |
|
||||
(static_cast<uint32_t>(b[off + 2]) << 16) |
|
||||
(static_cast<uint32_t>(b[off + 3]) << 24);
|
||||
}
|
||||
|
||||
int32_t readI32LE(ByteView b, size_t off)
|
||||
{
|
||||
return static_cast<int32_t>(readU32LE(b, off));
|
||||
}
|
||||
|
||||
uint32_t read24(const Bytes& b, size_t off)
|
||||
{
|
||||
return static_cast<uint32_t>(b[off]) |
|
||||
(static_cast<uint32_t>(b[off + 1]) << 8) |
|
||||
(static_cast<uint32_t>(b[off + 2]) << 16);
|
||||
}
|
||||
|
||||
int hashVal(uint32_t value)
|
||||
{
|
||||
return static_cast<int>(((value >> 12) ^ value) & 0xfff);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
uint32_t qlzDecompressedSize(ByteView data)
|
||||
{
|
||||
return (data[0] & 0x02) != 0
|
||||
? static_cast<uint32_t>(readI32LE(data, 5))
|
||||
: data[2];
|
||||
}
|
||||
|
||||
uint32_t qlzCompressedSize(ByteView data)
|
||||
{
|
||||
return (data[0] & 0x02) != 0
|
||||
? static_cast<uint32_t>(readI32LE(data, 1))
|
||||
: data[1];
|
||||
}
|
||||
|
||||
Bytes qlzDecompress(ByteView data)
|
||||
{
|
||||
if (data.empty()) {
|
||||
throw std::runtime_error("QuickLZ: empty input");
|
||||
}
|
||||
const uint8_t flags = data[0];
|
||||
const int level = (flags >> 2) & 0x03;
|
||||
if (level != 1) {
|
||||
throw std::runtime_error("QuickLZ level not supported");
|
||||
}
|
||||
|
||||
const size_t headerLen = (flags & 0x02) != 0 ? 9 : 3;
|
||||
const uint32_t decompressedSize = qlzDecompressedSize(data);
|
||||
if (decompressedSize > MAX_DECOMPRESSED_SIZE) {
|
||||
throw std::runtime_error("QuickLZ: decompressed size exceeds max");
|
||||
}
|
||||
|
||||
Bytes dest(decompressedSize, 0);
|
||||
|
||||
if ((flags & 0x01) == 0) {
|
||||
// Stored, not compressed.
|
||||
if (headerLen + decompressedSize > data.size()) {
|
||||
throw std::runtime_error("QuickLZ: truncated stored block");
|
||||
}
|
||||
std::copy_n(data.begin() + headerLen, decompressedSize,
|
||||
dest.begin());
|
||||
return dest;
|
||||
}
|
||||
|
||||
std::vector<int32_t> hashtable(TABLE_SIZE, 0);
|
||||
uint32_t control = 1;
|
||||
size_t sourcePos = headerLen;
|
||||
size_t destPos = 0;
|
||||
size_t nextHashed = 0;
|
||||
|
||||
while (true) {
|
||||
if (control == 1) {
|
||||
control = readU32LE(data, sourcePos);
|
||||
sourcePos += 4;
|
||||
}
|
||||
|
||||
if ((control & 1) != 0) {
|
||||
control >>= 1;
|
||||
const uint8_t next = data[sourcePos++];
|
||||
const int hashIdx = (next >> 4) | (data[sourcePos++] << 4);
|
||||
|
||||
uint32_t matchLen = next & 0x0f;
|
||||
if (matchLen != 0) {
|
||||
matchLen += 2;
|
||||
} else {
|
||||
matchLen = data[sourcePos++];
|
||||
}
|
||||
|
||||
const int32_t offset = hashtable[hashIdx];
|
||||
|
||||
dest[destPos] = dest[offset];
|
||||
dest[destPos + 1] = dest[offset + 1];
|
||||
dest[destPos + 2] = dest[offset + 2];
|
||||
for (uint32_t i = 3; i < matchLen; ++i) {
|
||||
dest[destPos + i] = dest[offset + i];
|
||||
}
|
||||
destPos += matchLen;
|
||||
|
||||
const size_t end = destPos + 1 - matchLen;
|
||||
if (nextHashed < end) {
|
||||
uint32_t nxt = read24(dest, nextHashed);
|
||||
hashtable[hashVal(nxt)] = static_cast<int32_t>(nextHashed);
|
||||
for (size_t i = nextHashed + 1; i < end; ++i) {
|
||||
nxt = (nxt >> 8) |
|
||||
(static_cast<uint32_t>(dest[i + 2]) << 16);
|
||||
hashtable[hashVal(nxt)] = static_cast<int32_t>(i);
|
||||
}
|
||||
}
|
||||
nextHashed = destPos;
|
||||
} else if (destPos >=
|
||||
std::max<size_t>(decompressedSize, 10) - 10) {
|
||||
while (destPos < decompressedSize) {
|
||||
if (control == 1) {
|
||||
sourcePos += 4;
|
||||
}
|
||||
control >>= 1;
|
||||
dest[destPos++] = data[sourcePos++];
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
dest[destPos++] = data[sourcePos++];
|
||||
control >>= 1;
|
||||
|
||||
const size_t end = destPos >= 2 ? destPos - 2 : 0;
|
||||
if (nextHashed < end) {
|
||||
uint32_t nxt = read24(dest, nextHashed);
|
||||
hashtable[hashVal(nxt)] = static_cast<int32_t>(nextHashed);
|
||||
for (size_t i = nextHashed + 1; i < end; ++i) {
|
||||
nxt = (nxt >> 8) |
|
||||
(static_cast<uint32_t>(dest[i + 2]) << 16);
|
||||
hashtable[hashVal(nxt)] = static_cast<int32_t>(i);
|
||||
}
|
||||
}
|
||||
nextHashed = std::max(nextHashed, end);
|
||||
}
|
||||
}
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Protocol
|
||||
@@ -0,0 +1,980 @@
|
||||
#include "echoion/protocol/TsClient.hpp"
|
||||
#include "echoion/protocol/Crypto.hpp"
|
||||
#include "echoion/protocol/License.hpp"
|
||||
#include "echoion/protocol/QuickLz.hpp"
|
||||
#include "echoion/protocol/Util.hpp"
|
||||
|
||||
#include <openssl/bn.h>
|
||||
#include <openssl/rand.h>
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <netdb.h>
|
||||
#include <poll.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Echoion::Protocol
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr uint8_t FLAG_FRAGMENTED = 0x10;
|
||||
constexpr uint8_t FLAG_NEWPROTOCOL = 0x20;
|
||||
constexpr uint8_t FLAG_COMPRESSED = 0x40;
|
||||
constexpr uint8_t FLAG_UNENCRYPTED = 0x80;
|
||||
|
||||
constexpr size_t MAC_LEN = 8;
|
||||
constexpr size_t C2S_HEADER_LEN = 5; // PId(2) + CId(2) + PT(1)
|
||||
constexpr size_t S2C_HEADER_LEN = 3; // PId(2) + PT(1)
|
||||
constexpr size_t MAX_PACKET_SIZE = 500;
|
||||
constexpr size_t MAX_OUT_CONTENT =
|
||||
MAX_PACKET_SIZE - MAC_LEN - C2S_HEADER_LEN;
|
||||
|
||||
constexpr const char* VS_PLATFORM = "Linux";
|
||||
constexpr const char* VS_VERSION = "3.?.? [Build: 5680278000]";
|
||||
constexpr const char* VS_SIGN =
|
||||
"Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2"
|
||||
"gSwRuZi0R+8Laan5ts5CQ==";
|
||||
|
||||
int64_t nowMs()
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
void putU16BE(std::vector<uint8_t>& b, size_t off, uint16_t v)
|
||||
{
|
||||
b[off] = static_cast<uint8_t>((v >> 8) & 0xff);
|
||||
b[off + 1] = static_cast<uint8_t>(v & 0xff);
|
||||
}
|
||||
uint16_t getU16BE(std::span<const uint8_t> b, size_t off)
|
||||
{
|
||||
return static_cast<uint16_t>((b[off] << 8) | b[off + 1]);
|
||||
}
|
||||
|
||||
// y = x^(2^level) mod n, all big-endian 64-byte.
|
||||
std::vector<uint8_t> rsaPuzzle(std::span<const uint8_t> x,
|
||||
std::span<const uint8_t> n, int32_t level)
|
||||
{
|
||||
BN_CTX* ctx = BN_CTX_new();
|
||||
BIGNUM* bx = BN_bin2bn(x.data(), static_cast<int>(x.size()),
|
||||
nullptr);
|
||||
BIGNUM* bn = BN_bin2bn(n.data(), static_cast<int>(n.size()),
|
||||
nullptr);
|
||||
BIGNUM* exp = BN_new();
|
||||
BIGNUM* one = BN_new();
|
||||
BN_one(one);
|
||||
BN_lshift(exp, one, level); // 2^level
|
||||
BIGNUM* y = BN_new();
|
||||
BN_mod_exp(y, bx, exp, bn, ctx);
|
||||
std::vector<uint8_t> out(64, 0);
|
||||
BN_bn2binpad(y, out.data(), 64);
|
||||
BN_free(y);
|
||||
BN_free(exp);
|
||||
BN_free(one);
|
||||
BN_free(bn);
|
||||
BN_free(bx);
|
||||
BN_CTX_free(ctx);
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TsClient::TsClient() = default;
|
||||
|
||||
TsClient::~TsClient()
|
||||
{
|
||||
forceClose();
|
||||
if (thread_.joinable()) {
|
||||
thread_.join();
|
||||
}
|
||||
}
|
||||
|
||||
void TsClient::debug(const std::string& msg)
|
||||
{
|
||||
if (cb_.onDebug) {
|
||||
cb_.onDebug(msg);
|
||||
}
|
||||
}
|
||||
|
||||
TsClient::Counter TsClient::getCounter(PacketType type)
|
||||
{
|
||||
if (type == PacketType::Init1) {
|
||||
return {101, 0};
|
||||
}
|
||||
auto i = static_cast<size_t>(type);
|
||||
return {packetCounter_[i], generationCounter_[i]};
|
||||
}
|
||||
|
||||
void TsClient::incCounter(PacketType type)
|
||||
{
|
||||
if (type == PacketType::Init1) {
|
||||
return;
|
||||
}
|
||||
auto i = static_cast<size_t>(type);
|
||||
if (++packetCounter_[i] == 0) {
|
||||
++generationCounter_[i];
|
||||
}
|
||||
}
|
||||
|
||||
void TsClient::connect(const TsClientOptions& opts)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
||||
if (!opts.identity) {
|
||||
throw std::runtime_error("TsClient: identity is required");
|
||||
}
|
||||
opts_ = opts;
|
||||
|
||||
// Resolve host and open a connected UDP socket.
|
||||
addrinfo hints{};
|
||||
hints.ai_family = AF_INET;
|
||||
hints.ai_socktype = SOCK_DGRAM;
|
||||
hints.ai_protocol = IPPROTO_UDP;
|
||||
addrinfo* res = nullptr;
|
||||
std::string portStr = std::to_string(opts.port);
|
||||
if (getaddrinfo(opts.host.c_str(), portStr.c_str(), &hints, &res) != 0 ||
|
||||
!res) {
|
||||
throw std::runtime_error("TsClient: cannot resolve host " +
|
||||
opts.host);
|
||||
}
|
||||
sock_ = ::socket(res->ai_family, res->ai_socktype, res->ai_protocol);
|
||||
if (sock_ < 0) {
|
||||
freeaddrinfo(res);
|
||||
throw std::runtime_error("TsClient: socket() failed");
|
||||
}
|
||||
if (::connect(sock_, res->ai_addr, res->ai_addrlen) != 0) {
|
||||
freeaddrinfo(res);
|
||||
::close(sock_);
|
||||
sock_ = -1;
|
||||
throw std::runtime_error("TsClient: connect() failed");
|
||||
}
|
||||
freeaddrinfo(res);
|
||||
|
||||
// Reset all per-connection state.
|
||||
state_ = ClientState::Init;
|
||||
clientId_ = 0;
|
||||
cryptoInitComplete_ = false;
|
||||
ivStruct_.clear();
|
||||
fakeSignature_.fill(0);
|
||||
alphaTmp_.clear();
|
||||
packetCounter_.fill(0);
|
||||
generationCounter_.fill(0);
|
||||
resendMap_.clear();
|
||||
initResend_.reset();
|
||||
fragmentBuffer_.clear();
|
||||
fragmenting_ = false;
|
||||
fragmentFlags_ = 0;
|
||||
channelMap_.clear();
|
||||
disconnectDeadline_ = 0;
|
||||
lastMessageTime_ = nowMs();
|
||||
lastPing_ = nowMs();
|
||||
connectStart_ = nowMs();
|
||||
|
||||
// Reserve command counter (old clientinitiv behaviour), then Init0.
|
||||
incCounter(PacketType::Command);
|
||||
sendInitPacket(buildInit0());
|
||||
|
||||
running_ = true;
|
||||
thread_ = std::thread([this] { loopThread(); });
|
||||
}
|
||||
|
||||
void TsClient::loopThread()
|
||||
{
|
||||
while (running_.load()) {
|
||||
pollfd pfd{};
|
||||
pfd.fd = sock_;
|
||||
pfd.events = POLLIN;
|
||||
int rc = ::poll(&pfd, 1, 100);
|
||||
if (!running_.load()) {
|
||||
break;
|
||||
}
|
||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
||||
if (rc > 0 && (pfd.revents & POLLIN)) {
|
||||
uint8_t buf[2048];
|
||||
ssize_t n = ::recv(sock_, buf, sizeof(buf), 0);
|
||||
if (n > 0) {
|
||||
handleIncomingPacket(
|
||||
std::span<const uint8_t>(buf, static_cast<size_t>(n)));
|
||||
}
|
||||
}
|
||||
resendTick();
|
||||
}
|
||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
||||
if (sock_ >= 0) {
|
||||
::close(sock_);
|
||||
sock_ = -1;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Outgoing ----------------------------------------------------------
|
||||
|
||||
std::vector<uint8_t> TsClient::buildInit0()
|
||||
{
|
||||
std::vector<uint8_t> buf(4 + 1 + 4 + 4 + 8, 0);
|
||||
putU16BE(buf, 0, static_cast<uint16_t>((Crypto::INIT_VERSION >> 16)));
|
||||
putU16BE(buf, 2, static_cast<uint16_t>(Crypto::INIT_VERSION & 0xffff));
|
||||
buf[4] = 0x00; // step 0
|
||||
uint32_t ts = static_cast<uint32_t>(
|
||||
std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch())
|
||||
.count());
|
||||
buf[5] = (ts >> 24) & 0xff;
|
||||
buf[6] = (ts >> 16) & 0xff;
|
||||
buf[7] = (ts >> 8) & 0xff;
|
||||
buf[8] = ts & 0xff;
|
||||
RAND_bytes(buf.data() + 9, 4);
|
||||
return buf;
|
||||
}
|
||||
|
||||
void TsClient::sendInitPacket(const std::vector<uint8_t>& data)
|
||||
{
|
||||
auto raw = buildRawPacket(data, PacketType::Init1, 101,
|
||||
FLAG_UNENCRYPTED);
|
||||
std::memcpy(raw.data(), Crypto::INIT_MAC.data(), MAC_LEN);
|
||||
initResend_ = std::make_unique<Resend>(
|
||||
Resend{raw, 101, nowMs(), nowMs()});
|
||||
sendRawLocked(raw);
|
||||
}
|
||||
|
||||
std::vector<uint8_t> TsClient::buildRawPacket(std::span<const uint8_t> data,
|
||||
PacketType type,
|
||||
uint16_t packetId,
|
||||
uint8_t flags)
|
||||
{
|
||||
std::vector<uint8_t> raw(MAC_LEN + C2S_HEADER_LEN + data.size(), 0);
|
||||
putU16BE(raw, MAC_LEN, packetId);
|
||||
putU16BE(raw, MAC_LEN + 2, clientId_.load());
|
||||
raw[MAC_LEN + 4] =
|
||||
static_cast<uint8_t>((flags & 0xf0) |
|
||||
(static_cast<uint8_t>(type) & 0x0f));
|
||||
std::memcpy(raw.data() + MAC_LEN + C2S_HEADER_LEN, data.data(),
|
||||
data.size());
|
||||
return raw;
|
||||
}
|
||||
|
||||
void TsClient::encryptPacket(std::vector<uint8_t>& raw, PacketType type,
|
||||
uint16_t packetId, uint32_t gen, uint8_t flags,
|
||||
std::span<const uint8_t> data)
|
||||
{
|
||||
if (type == PacketType::Init1) {
|
||||
std::memcpy(raw.data(), Crypto::INIT_MAC.data(), MAC_LEN);
|
||||
return;
|
||||
}
|
||||
if (flags & FLAG_UNENCRYPTED) {
|
||||
std::memcpy(raw.data(), fakeSignature_.data(), MAC_LEN);
|
||||
return;
|
||||
}
|
||||
|
||||
Crypto::KeyNonce kn;
|
||||
if (!cryptoInitComplete_ || ivStruct_.empty()) {
|
||||
std::memcpy(kn.key.data(), Crypto::DUMMY_KEY.data(), 16);
|
||||
std::memcpy(kn.nonce.data(), Crypto::DUMMY_NONCE.data(), 16);
|
||||
} else {
|
||||
kn = Crypto::deriveKeyNonce(
|
||||
false, packetId, gen, static_cast<uint8_t>(type),
|
||||
Crypto::ByteView(ivStruct_.data(), ivStruct_.size()));
|
||||
}
|
||||
|
||||
Crypto::ByteView header(raw.data() + MAC_LEN, C2S_HEADER_LEN);
|
||||
auto enc = Crypto::eaxEncrypt(
|
||||
Crypto::ByteView(kn.key.data(), 16),
|
||||
Crypto::ByteView(kn.nonce.data(), 16), header, data);
|
||||
std::memcpy(raw.data(), enc.mac.data(), MAC_LEN);
|
||||
std::memcpy(raw.data() + MAC_LEN + C2S_HEADER_LEN, enc.ciphertext.data(),
|
||||
enc.ciphertext.size());
|
||||
}
|
||||
|
||||
void TsClient::sendOutgoing(std::span<const uint8_t> dataIn, PacketType type,
|
||||
uint8_t extraFlags)
|
||||
{
|
||||
auto ctr = getCounter(type);
|
||||
incCounter(type);
|
||||
|
||||
std::vector<uint8_t> data(dataIn.begin(), dataIn.end());
|
||||
uint8_t flags = extraFlags;
|
||||
switch (type) {
|
||||
case PacketType::Voice:
|
||||
case PacketType::VoiceWhisper:
|
||||
if (data.size() >= 2) {
|
||||
putU16BE(data, 0, ctr.id);
|
||||
}
|
||||
break;
|
||||
case PacketType::Command:
|
||||
case PacketType::CommandLow:
|
||||
flags |= FLAG_NEWPROTOCOL;
|
||||
break;
|
||||
case PacketType::Ping:
|
||||
case PacketType::Pong:
|
||||
flags |= FLAG_UNENCRYPTED;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
auto raw = buildRawPacket(data, type, ctr.id, flags);
|
||||
encryptPacket(raw, type, ctr.id, ctr.gen, flags, data);
|
||||
|
||||
if (type == PacketType::Command || type == PacketType::CommandLow) {
|
||||
resendMap_[ctr.id] = Resend{raw, ctr.id, nowMs(), nowMs()};
|
||||
}
|
||||
sendRawLocked(raw);
|
||||
}
|
||||
|
||||
void TsClient::sendRawLocked(const std::vector<uint8_t>& raw)
|
||||
{
|
||||
if (sock_ < 0) {
|
||||
return;
|
||||
}
|
||||
::send(sock_, raw.data(), raw.size(), 0);
|
||||
}
|
||||
|
||||
void TsClient::sendCommand(const std::string& cmd)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
||||
std::span<const uint8_t> data(
|
||||
reinterpret_cast<const uint8_t*>(cmd.data()), cmd.size());
|
||||
if (data.size() <= MAX_OUT_CONTENT) {
|
||||
sendOutgoing(data, PacketType::Command);
|
||||
return;
|
||||
}
|
||||
// Fragment: FLAG_FRAGMENTED on first and last fragment only.
|
||||
size_t total = data.size();
|
||||
size_t count = (total + MAX_OUT_CONTENT - 1) / MAX_OUT_CONTENT;
|
||||
for (size_t i = 0, idx = 0; i < total; i += MAX_OUT_CONTENT, ++idx) {
|
||||
size_t len = std::min(MAX_OUT_CONTENT, total - i);
|
||||
bool first = idx == 0;
|
||||
bool last = idx == count - 1;
|
||||
uint8_t extra = (first || last) ? FLAG_FRAGMENTED : 0;
|
||||
sendOutgoing(data.subspan(i, len), PacketType::Command, extra);
|
||||
}
|
||||
}
|
||||
|
||||
void TsClient::sendVoice(std::span<const uint8_t> opus)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
||||
if (state_.load() != ClientState::Connected) {
|
||||
return;
|
||||
}
|
||||
std::vector<uint8_t> buf(3 + opus.size(), 0);
|
||||
buf[2] = 5; // CODEC_OPUS_MUSIC
|
||||
std::memcpy(buf.data() + 3, opus.data(), opus.size());
|
||||
sendOutgoing(buf, PacketType::Voice);
|
||||
}
|
||||
|
||||
void TsClient::sendVoiceStop()
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
||||
if (state_.load() != ClientState::Connected) {
|
||||
return;
|
||||
}
|
||||
std::vector<uint8_t> buf(3, 0);
|
||||
buf[2] = 5;
|
||||
sendOutgoing(buf, PacketType::Voice);
|
||||
}
|
||||
|
||||
void TsClient::sendWhisper(std::span<const uint8_t> opus,
|
||||
const std::vector<uint64_t>& channelIds,
|
||||
const std::vector<uint16_t>& clientIds)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
||||
if (state_.load() != ClientState::Connected) {
|
||||
return;
|
||||
}
|
||||
if (channelIds.empty() && clientIds.empty()) {
|
||||
sendVoice(opus);
|
||||
return;
|
||||
}
|
||||
// VoiceWhisper C2S: voiceId(2) + codec(1) + nChan(1) + nClient(1)
|
||||
// + channelIds(u64 BE each) + clientIds(u16 BE each)
|
||||
// + opus. voiceId filled by sendOutgoing.
|
||||
std::vector<uint8_t> buf;
|
||||
buf.resize(3 + 2 + channelIds.size() * 8 + clientIds.size() * 2 +
|
||||
opus.size());
|
||||
size_t p = 0;
|
||||
p += 2; // voiceId placeholder
|
||||
buf[p++] = 5; // codec
|
||||
buf[p++] = static_cast<uint8_t>(channelIds.size());
|
||||
buf[p++] = static_cast<uint8_t>(clientIds.size());
|
||||
for (uint64_t cid : channelIds) {
|
||||
for (int s = 56; s >= 0; s -= 8) {
|
||||
buf[p++] = static_cast<uint8_t>((cid >> s) & 0xff);
|
||||
}
|
||||
}
|
||||
for (uint16_t clid : clientIds) {
|
||||
buf[p++] = static_cast<uint8_t>((clid >> 8) & 0xff);
|
||||
buf[p++] = static_cast<uint8_t>(clid & 0xff);
|
||||
}
|
||||
std::memcpy(buf.data() + p, opus.data(), opus.size());
|
||||
sendOutgoing(buf, PacketType::VoiceWhisper);
|
||||
}
|
||||
|
||||
// ---- Incoming ----------------------------------------------------------
|
||||
|
||||
std::vector<uint8_t> TsClient::decryptPacket(std::span<const uint8_t> raw,
|
||||
PacketType type,
|
||||
uint16_t packetId,
|
||||
uint32_t gen, uint8_t flags,
|
||||
bool& ok)
|
||||
{
|
||||
ok = false;
|
||||
if (type == PacketType::Init1) {
|
||||
if (std::memcmp(raw.data(), Crypto::INIT_MAC.data(), MAC_LEN) != 0) {
|
||||
return {};
|
||||
}
|
||||
ok = true;
|
||||
return std::vector<uint8_t>(raw.begin() + MAC_LEN + S2C_HEADER_LEN,
|
||||
raw.end());
|
||||
}
|
||||
if (flags & FLAG_UNENCRYPTED) {
|
||||
if (cryptoInitComplete_ &&
|
||||
std::memcmp(raw.data(), fakeSignature_.data(), MAC_LEN) != 0) {
|
||||
return {};
|
||||
}
|
||||
ok = true;
|
||||
return std::vector<uint8_t>(raw.begin() + MAC_LEN + S2C_HEADER_LEN,
|
||||
raw.end());
|
||||
}
|
||||
|
||||
Crypto::ByteView header(raw.data() + MAC_LEN, S2C_HEADER_LEN);
|
||||
Crypto::ByteView mac(raw.data(), MAC_LEN);
|
||||
Crypto::ByteView ct(raw.data() + MAC_LEN + S2C_HEADER_LEN,
|
||||
raw.size() - MAC_LEN - S2C_HEADER_LEN);
|
||||
|
||||
for (bool dummy : {!cryptoInitComplete_, cryptoInitComplete_}) {
|
||||
Crypto::KeyNonce kn;
|
||||
if (dummy || ivStruct_.empty()) {
|
||||
std::memcpy(kn.key.data(), Crypto::DUMMY_KEY.data(), 16);
|
||||
std::memcpy(kn.nonce.data(), Crypto::DUMMY_NONCE.data(), 16);
|
||||
} else {
|
||||
kn = Crypto::deriveKeyNonce(
|
||||
true, packetId, gen, static_cast<uint8_t>(type),
|
||||
Crypto::ByteView(ivStruct_.data(), ivStruct_.size()));
|
||||
}
|
||||
auto dec = Crypto::eaxDecrypt(Crypto::ByteView(kn.key.data(), 16),
|
||||
Crypto::ByteView(kn.nonce.data(), 16),
|
||||
header, ct, mac);
|
||||
if (dec) {
|
||||
ok = true;
|
||||
return *dec;
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
void TsClient::handleIncomingPacket(std::span<const uint8_t> raw)
|
||||
{
|
||||
if (raw.size() < MAC_LEN + S2C_HEADER_LEN) {
|
||||
return;
|
||||
}
|
||||
uint16_t packetId = getU16BE(raw, MAC_LEN);
|
||||
uint8_t ptByte = raw[MAC_LEN + 2];
|
||||
auto type = static_cast<PacketType>(ptByte & 0x0f);
|
||||
uint8_t flags = ptByte & 0xf0;
|
||||
lastMessageTime_ = nowMs();
|
||||
|
||||
bool ok = false;
|
||||
auto data = decryptPacket(raw, type, packetId, 0, flags, ok);
|
||||
if (!ok) {
|
||||
debug("failed to decrypt packet");
|
||||
return;
|
||||
}
|
||||
std::span<const uint8_t> d(data.data(), data.size());
|
||||
|
||||
switch (type) {
|
||||
case PacketType::Init1:
|
||||
handleInit(d);
|
||||
break;
|
||||
case PacketType::Command:
|
||||
case PacketType::CommandLow:
|
||||
sendAck(packetId, type == PacketType::Command ? PacketType::Ack
|
||||
: PacketType::AckLow);
|
||||
handleCommandData(d, flags);
|
||||
break;
|
||||
case PacketType::Ack:
|
||||
if (data.size() >= 2) {
|
||||
resendMap_.erase(getU16BE(d, 0));
|
||||
}
|
||||
break;
|
||||
case PacketType::Ping:
|
||||
handlePing(packetId);
|
||||
break;
|
||||
case PacketType::Voice:
|
||||
case PacketType::VoiceWhisper:
|
||||
if (cb_.onVoice) {
|
||||
cb_.onVoice(d);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void TsClient::sendAck(uint16_t ackId, PacketType ackType)
|
||||
{
|
||||
std::vector<uint8_t> buf(2, 0);
|
||||
putU16BE(buf, 0, ackId);
|
||||
sendOutgoing(buf, ackType);
|
||||
}
|
||||
|
||||
void TsClient::handlePing(uint16_t packetId)
|
||||
{
|
||||
std::vector<uint8_t> buf(2, 0);
|
||||
putU16BE(buf, 0, packetId);
|
||||
sendOutgoing(buf, PacketType::Pong);
|
||||
}
|
||||
|
||||
// ---- Handshake ---------------------------------------------------------
|
||||
|
||||
void TsClient::handleInit(std::span<const uint8_t> data)
|
||||
{
|
||||
if (data.empty()) {
|
||||
return;
|
||||
}
|
||||
uint8_t step = data[0];
|
||||
debug("init step " + std::to_string(step));
|
||||
|
||||
if (step == 1) {
|
||||
if (data.size() < 21) {
|
||||
return;
|
||||
}
|
||||
std::vector<uint8_t> init2(4 + 1 + 16 + 4, 0);
|
||||
putU16BE(init2, 0,
|
||||
static_cast<uint16_t>(Crypto::INIT_VERSION >> 16));
|
||||
putU16BE(init2, 2,
|
||||
static_cast<uint16_t>(Crypto::INIT_VERSION & 0xffff));
|
||||
init2[4] = 0x02;
|
||||
std::memcpy(init2.data() + 5, data.data() + 1, 20);
|
||||
initResend_.reset();
|
||||
sendInitPacket(init2);
|
||||
} else if (step == 3) {
|
||||
if (data.size() < 1 + 64 + 64 + 4 + 100) {
|
||||
return;
|
||||
}
|
||||
state_ = ClientState::Handshake;
|
||||
initResend_.reset();
|
||||
|
||||
std::span<const uint8_t> x = data.subspan(1, 64);
|
||||
std::span<const uint8_t> n = data.subspan(65, 64);
|
||||
int32_t level = static_cast<int32_t>(
|
||||
(data[129] << 24) | (data[130] << 16) | (data[131] << 8) |
|
||||
data[132]);
|
||||
std::span<const uint8_t> serverData = data.subspan(133, 100);
|
||||
debug("RSA puzzle level=" + std::to_string(level));
|
||||
|
||||
auto y = rsaPuzzle(x, n, level);
|
||||
|
||||
// alpha = 10 random bytes (base64); omega = identity pubkey string.
|
||||
alphaTmp_.assign(10, 0);
|
||||
RAND_bytes(alphaTmp_.data(), 10);
|
||||
std::string alpha = Util::base64Encode(
|
||||
Crypto::ByteView(alphaTmp_.data(), alphaTmp_.size()));
|
||||
|
||||
CommandParams p;
|
||||
p["alpha"] = alpha;
|
||||
p["omega"] = opts_.identity->publicKeyString();
|
||||
p["ot"] = "1";
|
||||
p["ip"] = "";
|
||||
std::string initAdd = buildCommand("clientinitiv", p);
|
||||
std::span<const uint8_t> textBytes(
|
||||
reinterpret_cast<const uint8_t*>(initAdd.data()),
|
||||
initAdd.size());
|
||||
|
||||
std::vector<uint8_t> init4(4 + 1 + 64 + 64 + 4 + 100 + 64 +
|
||||
textBytes.size(),
|
||||
0);
|
||||
putU16BE(init4, 0,
|
||||
static_cast<uint16_t>(Crypto::INIT_VERSION >> 16));
|
||||
putU16BE(init4, 2,
|
||||
static_cast<uint16_t>(Crypto::INIT_VERSION & 0xffff));
|
||||
init4[4] = 0x04;
|
||||
std::memcpy(init4.data() + 5, x.data(), 64);
|
||||
std::memcpy(init4.data() + 69, n.data(), 64);
|
||||
init4[133] = (level >> 24) & 0xff;
|
||||
init4[134] = (level >> 16) & 0xff;
|
||||
init4[135] = (level >> 8) & 0xff;
|
||||
init4[136] = level & 0xff;
|
||||
std::memcpy(init4.data() + 137, serverData.data(), 100);
|
||||
std::memcpy(init4.data() + 237, y.data(), 64);
|
||||
std::memcpy(init4.data() + 301, textBytes.data(), textBytes.size());
|
||||
|
||||
sendInitPacket(init4);
|
||||
} else if (step == 0x7f) {
|
||||
debug("server requested restart");
|
||||
initResend_.reset();
|
||||
sendInitPacket(buildInit0());
|
||||
}
|
||||
}
|
||||
|
||||
void TsClient::handleCommandData(std::span<const uint8_t> data,
|
||||
uint8_t flags)
|
||||
{
|
||||
if (flags & FLAG_FRAGMENTED) {
|
||||
if (!fragmenting_) {
|
||||
fragmenting_ = true;
|
||||
fragmentFlags_ = flags;
|
||||
fragmentBuffer_.assign(data.begin(), data.end());
|
||||
} else {
|
||||
fragmentBuffer_.insert(fragmentBuffer_.end(), data.begin(),
|
||||
data.end());
|
||||
uint8_t saved = fragmentFlags_;
|
||||
fragmenting_ = false;
|
||||
fragmentFlags_ = 0;
|
||||
auto merged = std::move(fragmentBuffer_);
|
||||
fragmentBuffer_.clear();
|
||||
processCommand(
|
||||
std::span<const uint8_t>(merged.data(), merged.size()),
|
||||
saved);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (fragmenting_) {
|
||||
fragmentBuffer_.insert(fragmentBuffer_.end(), data.begin(),
|
||||
data.end());
|
||||
return;
|
||||
}
|
||||
processCommand(data, flags);
|
||||
}
|
||||
|
||||
void TsClient::processCommand(std::span<const uint8_t> data, uint8_t flags)
|
||||
{
|
||||
std::vector<uint8_t> decompressed;
|
||||
if (flags & FLAG_COMPRESSED) {
|
||||
try {
|
||||
decompressed = qlzDecompress(data);
|
||||
data = std::span<const uint8_t>(decompressed.data(),
|
||||
decompressed.size());
|
||||
} catch (const std::exception& e) {
|
||||
debug(std::string("decompression failed: ") + e.what());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
std::string cmdStr(reinterpret_cast<const char*>(data.data()),
|
||||
data.size());
|
||||
auto parsed = parseCommand(cmdStr);
|
||||
if (cb_.onCommand) {
|
||||
cb_.onCommand(parsed);
|
||||
}
|
||||
|
||||
const std::string& name = parsed.name;
|
||||
if (name == "initivexpand") {
|
||||
handleInitIvExpand(parsed.params);
|
||||
} else if (name == "initivexpand2") {
|
||||
handleInitIvExpand2(parsed.params);
|
||||
} else if (name == "initserver") {
|
||||
handleInitServer(parsed.params);
|
||||
} else if (name == "channellist") {
|
||||
handleChannelList(parsed);
|
||||
} else if (name == "channellistfinished") {
|
||||
handleChannelListFinished();
|
||||
} else if (name == "notifyclientleftview") {
|
||||
auto it = parsed.params.find("clid");
|
||||
if (it != parsed.params.end() &&
|
||||
static_cast<uint16_t>(std::stoul(it->second)) ==
|
||||
clientId_.load()) {
|
||||
cleanup();
|
||||
}
|
||||
} else if (name == "notifytextmessage") {
|
||||
if (cb_.onTextMessage) {
|
||||
cb_.onTextMessage(parsed.params);
|
||||
}
|
||||
} else if (name == "error") {
|
||||
int errId = 0;
|
||||
auto it = parsed.params.find("id");
|
||||
if (it != parsed.params.end()) {
|
||||
errId = std::stoi(it->second);
|
||||
}
|
||||
if (errId == 2568 || errId == 3329 || errId == 1796) {
|
||||
std::string msg = "unknown error";
|
||||
auto m = parsed.params.find("msg");
|
||||
if (m != parsed.params.end()) {
|
||||
msg = m->second;
|
||||
}
|
||||
if (cb_.onError) {
|
||||
cb_.onError("TS3 error " + std::to_string(errId) + ": " +
|
||||
msg);
|
||||
}
|
||||
disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TsClient::handleInitIvExpand(const CommandParams& params)
|
||||
{
|
||||
initResend_.reset();
|
||||
auto ai = params.find("alpha");
|
||||
auto bi = params.find("beta");
|
||||
auto oi = params.find("omega");
|
||||
if (ai == params.end() || bi == params.end() || oi == params.end()) {
|
||||
if (cb_.onError) {
|
||||
cb_.onError("missing initivexpand parameters");
|
||||
}
|
||||
return;
|
||||
}
|
||||
auto beta = Util::base64Decode(bi->second);
|
||||
auto omega = Util::base64Decode(oi->second);
|
||||
auto sharedKey = opts_.identity->sharedSecret(
|
||||
Crypto::ByteView(omega.data(), omega.size()));
|
||||
|
||||
ivStruct_.assign(10 + beta.size(), 0);
|
||||
for (size_t i = 0; i < 10; ++i) {
|
||||
ivStruct_[i] = sharedKey[i] ^ alphaTmp_[i];
|
||||
}
|
||||
for (size_t i = 0; i < beta.size(); ++i) {
|
||||
ivStruct_[10 + i] = sharedKey[10 + i] ^ beta[i];
|
||||
}
|
||||
auto sig = Crypto::sha1(
|
||||
Crypto::ByteView(ivStruct_.data(), ivStruct_.size()));
|
||||
std::memcpy(fakeSignature_.data(), sig.data(), MAC_LEN);
|
||||
cryptoInitComplete_ = true;
|
||||
alphaTmp_.clear();
|
||||
sendClientInit();
|
||||
}
|
||||
|
||||
void TsClient::handleInitIvExpand2(const CommandParams& params)
|
||||
{
|
||||
if (cryptoInitComplete_ || alphaTmp_.empty()) {
|
||||
return;
|
||||
}
|
||||
initResend_.reset();
|
||||
auto li = params.find("l");
|
||||
auto bi = params.find("beta");
|
||||
auto oi = params.find("omega");
|
||||
if (li == params.end() || bi == params.end() || oi == params.end()) {
|
||||
if (cb_.onError) {
|
||||
cb_.onError("missing initivexpand2 parameters");
|
||||
}
|
||||
return;
|
||||
}
|
||||
try {
|
||||
auto beta = Util::base64Decode(bi->second);
|
||||
auto license = Util::base64Decode(li->second);
|
||||
auto blocks =
|
||||
parseLicense(ByteView(license.data(), license.size()));
|
||||
auto serverKey = deriveLicenseKey(blocks);
|
||||
auto temp = generateTemporaryKey();
|
||||
|
||||
std::string ek = Util::base64Encode(
|
||||
Crypto::ByteView(temp.publicKey.data(), 32));
|
||||
std::vector<uint8_t> toSign(temp.publicKey.begin(),
|
||||
temp.publicKey.end());
|
||||
toSign.insert(toSign.end(), beta.begin(), beta.end());
|
||||
auto sigBuf = opts_.identity->sign(
|
||||
Crypto::ByteView(toSign.data(), toSign.size()));
|
||||
std::string proof = Util::base64Encode(
|
||||
Crypto::ByteView(sigBuf.data(), sigBuf.size()));
|
||||
|
||||
CommandParams ck;
|
||||
ck["ek"] = ek;
|
||||
ck["proof"] = proof;
|
||||
sendCommand(buildCommand("clientek", ck));
|
||||
|
||||
auto shared = getSharedSecret2(
|
||||
ByteView(serverKey.data(), serverKey.size()),
|
||||
ByteView(temp.privateKey.data(), 32));
|
||||
|
||||
ivStruct_.assign(shared.begin(), shared.end());
|
||||
for (size_t i = 0; i < 10 && i < ivStruct_.size(); ++i) {
|
||||
ivStruct_[i] ^= alphaTmp_[i];
|
||||
}
|
||||
for (size_t i = 0; i < beta.size() && (10 + i) < ivStruct_.size();
|
||||
++i) {
|
||||
ivStruct_[10 + i] ^= beta[i];
|
||||
}
|
||||
auto sig = Crypto::sha1(
|
||||
Crypto::ByteView(ivStruct_.data(), ivStruct_.size()));
|
||||
std::memcpy(fakeSignature_.data(), sig.data(), MAC_LEN);
|
||||
cryptoInitComplete_ = true;
|
||||
alphaTmp_.clear();
|
||||
sendClientInit();
|
||||
} catch (const std::exception& e) {
|
||||
if (cb_.onError) {
|
||||
cb_.onError(std::string("initivexpand2 failed: ") + e.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TsClient::sendClientInit()
|
||||
{
|
||||
debug("sending clientinit");
|
||||
CommandParams p;
|
||||
p["client_nickname"] = opts_.nickname;
|
||||
p["client_version"] = VS_VERSION;
|
||||
p["client_platform"] = VS_PLATFORM;
|
||||
p["client_input_hardware"] = "1";
|
||||
p["client_output_hardware"] = "1";
|
||||
p["client_default_channel"] = opts_.defaultChannel;
|
||||
p["client_default_channel_password"] =
|
||||
opts_.channelPassword.empty()
|
||||
? ""
|
||||
: Crypto::hashPassword(opts_.channelPassword);
|
||||
p["client_server_password"] =
|
||||
opts_.serverPassword.empty()
|
||||
? ""
|
||||
: Crypto::hashPassword(opts_.serverPassword);
|
||||
p["client_meta_data"] = "";
|
||||
p["client_version_sign"] = VS_SIGN;
|
||||
p["client_key_offset"] = std::to_string(opts_.identity->keyOffset());
|
||||
p["client_nickname_phonetic"] = "";
|
||||
p["client_default_token"] = "";
|
||||
p["hwid"] = "";
|
||||
sendCommand(buildCommand("clientinit", p));
|
||||
}
|
||||
|
||||
void TsClient::handleInitServer(const CommandParams& params)
|
||||
{
|
||||
auto it = params.find("aclid");
|
||||
uint16_t id = 0;
|
||||
if (it != params.end()) {
|
||||
id = static_cast<uint16_t>(std::stoul(it->second));
|
||||
}
|
||||
clientId_ = id;
|
||||
state_ = ClientState::Connected;
|
||||
lastPing_ = nowMs();
|
||||
debug("connected, clientId=" + std::to_string(id));
|
||||
if (cb_.onConnected) {
|
||||
cb_.onConnected();
|
||||
}
|
||||
}
|
||||
|
||||
void TsClient::handleChannelList(const ParsedCommand& parsed)
|
||||
{
|
||||
const auto& entries =
|
||||
parsed.groups.empty()
|
||||
? std::vector<CommandParams>{parsed.params}
|
||||
: parsed.groups;
|
||||
for (const auto& e : entries) {
|
||||
auto ci = e.find("cid");
|
||||
auto ni = e.find("channel_name");
|
||||
if (ci != e.end() && ni != e.end()) {
|
||||
channelMap_[ni->second] =
|
||||
static_cast<uint64_t>(std::stoull(ci->second));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TsClient::handleChannelListFinished()
|
||||
{
|
||||
const std::string& target = opts_.defaultChannel;
|
||||
if (target.empty() || clientId_.load() == 0) {
|
||||
return;
|
||||
}
|
||||
uint64_t cid = 0;
|
||||
bool numeric = !target.empty() &&
|
||||
target.find_first_not_of("0123456789") ==
|
||||
std::string::npos;
|
||||
if (numeric) {
|
||||
cid = std::stoull(target);
|
||||
} else {
|
||||
auto it = channelMap_.find(target);
|
||||
if (it != channelMap_.end()) {
|
||||
cid = it->second;
|
||||
}
|
||||
}
|
||||
if (cid == 0) {
|
||||
debug("default channel not found: " + target);
|
||||
return;
|
||||
}
|
||||
CommandParams p;
|
||||
p["cid"] = std::to_string(cid);
|
||||
p["clid"] = std::to_string(clientId_.load());
|
||||
p["cpw"] = opts_.channelPassword;
|
||||
sendCommand(buildCommand("clientmove", p));
|
||||
}
|
||||
|
||||
// ---- Timers / teardown -------------------------------------------------
|
||||
|
||||
void TsClient::resendTick()
|
||||
{
|
||||
int64_t now = nowMs();
|
||||
|
||||
if (disconnectDeadline_ != 0 && now >= disconnectDeadline_) {
|
||||
cleanup();
|
||||
return;
|
||||
}
|
||||
|
||||
if (initResend_) {
|
||||
if (now - initResend_->firstSend > 30000) {
|
||||
if (cb_.onError) {
|
||||
cb_.onError("init timeout");
|
||||
}
|
||||
cleanup();
|
||||
return;
|
||||
}
|
||||
if (now - initResend_->lastSend > 1000) {
|
||||
initResend_->lastSend = now;
|
||||
sendRawLocked(initResend_->raw);
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& [id, pkt] : resendMap_) {
|
||||
if (now - pkt.firstSend > 30000) {
|
||||
if (cb_.onError) {
|
||||
cb_.onError("packet " + std::to_string(id) + " timeout");
|
||||
}
|
||||
cleanup();
|
||||
return;
|
||||
}
|
||||
if (now - pkt.lastSend > 1000) {
|
||||
pkt.lastSend = now;
|
||||
sendRawLocked(pkt.raw);
|
||||
}
|
||||
}
|
||||
|
||||
if (state_.load() == ClientState::Connected &&
|
||||
now - lastPing_ >= 1000) {
|
||||
lastPing_ = now;
|
||||
std::vector<uint8_t> empty;
|
||||
sendOutgoing(empty, PacketType::Ping);
|
||||
}
|
||||
|
||||
if (now - lastMessageTime_ > 30000) {
|
||||
if (cb_.onError) {
|
||||
cb_.onError("connection timeout - no response");
|
||||
}
|
||||
cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
void TsClient::disconnect()
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
||||
if (state_.load() == ClientState::Connected) {
|
||||
state_ = ClientState::Disconnecting;
|
||||
CommandParams p;
|
||||
p["reasonid"] = "8";
|
||||
p["reasonmsg"] = "leaving";
|
||||
sendCommand(buildCommand("clientdisconnect", p));
|
||||
}
|
||||
disconnectDeadline_ = nowMs() + 500;
|
||||
}
|
||||
|
||||
void TsClient::forceClose()
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
||||
if (state_.load() == ClientState::Disconnected && !running_.load()) {
|
||||
return;
|
||||
}
|
||||
state_ = ClientState::Disconnected;
|
||||
running_ = false;
|
||||
if (sock_ >= 0) {
|
||||
::shutdown(sock_, SHUT_RDWR);
|
||||
}
|
||||
}
|
||||
|
||||
void TsClient::cleanup()
|
||||
{
|
||||
if (state_.load() == ClientState::Disconnected) {
|
||||
return;
|
||||
}
|
||||
state_ = ClientState::Disconnected;
|
||||
running_ = false;
|
||||
if (cb_.onDisconnected) {
|
||||
cb_.onDisconnected();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Echoion::Protocol
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
#include "echoion/protocol/Util.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Echoion::Protocol::Util
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr char kEnc[] =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
std::array<int8_t, 256> makeDecodeTable()
|
||||
{
|
||||
std::array<int8_t, 256> t{};
|
||||
t.fill(-1);
|
||||
for (int i = 0; i < 64; ++i) {
|
||||
t[static_cast<uint8_t>(kEnc[i])] = static_cast<int8_t>(i);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
const std::array<int8_t, 256> kDec = makeDecodeTable();
|
||||
} // namespace
|
||||
|
||||
std::string base64Encode(ByteView data)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve((data.size() + 2) / 3 * 4);
|
||||
size_t i = 0;
|
||||
for (; i + 3 <= data.size(); i += 3) {
|
||||
uint32_t n = (static_cast<uint32_t>(data[i]) << 16) |
|
||||
(static_cast<uint32_t>(data[i + 1]) << 8) |
|
||||
static_cast<uint32_t>(data[i + 2]);
|
||||
out.push_back(kEnc[(n >> 18) & 0x3f]);
|
||||
out.push_back(kEnc[(n >> 12) & 0x3f]);
|
||||
out.push_back(kEnc[(n >> 6) & 0x3f]);
|
||||
out.push_back(kEnc[n & 0x3f]);
|
||||
}
|
||||
const size_t rem = data.size() - i;
|
||||
if (rem == 1) {
|
||||
uint32_t n = static_cast<uint32_t>(data[i]) << 16;
|
||||
out.push_back(kEnc[(n >> 18) & 0x3f]);
|
||||
out.push_back(kEnc[(n >> 12) & 0x3f]);
|
||||
out.push_back('=');
|
||||
out.push_back('=');
|
||||
} else if (rem == 2) {
|
||||
uint32_t n = (static_cast<uint32_t>(data[i]) << 16) |
|
||||
(static_cast<uint32_t>(data[i + 1]) << 8);
|
||||
out.push_back(kEnc[(n >> 18) & 0x3f]);
|
||||
out.push_back(kEnc[(n >> 12) & 0x3f]);
|
||||
out.push_back(kEnc[(n >> 6) & 0x3f]);
|
||||
out.push_back('=');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Bytes base64Decode(const std::string& text)
|
||||
{
|
||||
Bytes out;
|
||||
out.reserve(text.size() / 4 * 3);
|
||||
uint32_t buf = 0;
|
||||
int bits = 0;
|
||||
for (char c : text) {
|
||||
if (c == '=' || c == '\n' || c == '\r' || c == ' ') {
|
||||
continue;
|
||||
}
|
||||
int8_t v = kDec[static_cast<uint8_t>(c)];
|
||||
if (v < 0) {
|
||||
throw std::runtime_error("invalid base64 character");
|
||||
}
|
||||
buf = (buf << 6) | static_cast<uint32_t>(v);
|
||||
bits += 6;
|
||||
if (bits >= 8) {
|
||||
bits -= 8;
|
||||
out.push_back(static_cast<uint8_t>((buf >> bits) & 0xff));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string toHex(ByteView data)
|
||||
{
|
||||
static const char* h = "0123456789abcdef";
|
||||
std::string out;
|
||||
out.reserve(data.size() * 2);
|
||||
for (uint8_t b : data) {
|
||||
out.push_back(h[b >> 4]);
|
||||
out.push_back(h[b & 0x0f]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Bytes fromHex(const std::string& hex)
|
||||
{
|
||||
auto nib = [](char c) -> int {
|
||||
if (c >= '0' && c <= '9')
|
||||
return c - '0';
|
||||
if (c >= 'a' && c <= 'f')
|
||||
return c - 'a' + 10;
|
||||
if (c >= 'A' && c <= 'F')
|
||||
return c - 'A' + 10;
|
||||
throw std::runtime_error("invalid hex character");
|
||||
};
|
||||
if (hex.size() % 2 != 0) {
|
||||
throw std::runtime_error("odd-length hex string");
|
||||
}
|
||||
Bytes out;
|
||||
out.reserve(hex.size() / 2);
|
||||
for (size_t i = 0; i < hex.size(); i += 2) {
|
||||
out.push_back(static_cast<uint8_t>((nib(hex[i]) << 4) |
|
||||
nib(hex[i + 1])));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Protocol::Util
|
||||
Reference in new issue
Block a user