Unmodified copy of the tsclientlib workspace crates (MIT OR Apache-2.0)
with the tsdeclarations submodule (83cb8a9) flattened into plain files.
See crates/proto/UPSTREAM.md for the path mapping.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-25 12:46:11 +00:00
commit 1cb7b0bdf2
119 files changed
+24322

No files matched your search

+452
View File
@@ -0,0 +1,452 @@
//! Handle packet splitting and cryptography
use curve25519_dalek_ng::edwards::EdwardsPoint;
use eax::aead::consts::{U16, U8};
use eax::{AeadInPlace, Eax, KeyInit};
use generic_array::GenericArray;
use num_bigint::BigUint;
use num_traits::ToPrimitive;
use omnom::WriteExt;
use quicklz::CompressionLevel;
use sha1::Sha1;
use sha2::{Digest, Sha256, Sha512};
use tsproto_types::crypto::{EccKeyPrivEd25519, EccKeyPubP256};
use crate::connection::CachedKey;
use crate::{Error, Result};
use tsproto_packets::packets::*;
pub fn must_encrypt(t: PacketType) -> bool {
match t {
PacketType::Command | PacketType::CommandLow => true,
PacketType::Voice
| PacketType::Ack
| PacketType::AckLow
| PacketType::VoiceWhisper
| PacketType::Ping
| PacketType::Pong
| PacketType::Init => false,
}
}
pub fn should_encrypt(t: PacketType, voice_encryption: bool) -> bool {
must_encrypt(t)
|| t == PacketType::Ack
|| t == PacketType::AckLow
|| (voice_encryption && t.is_voice())
}
/// Compresses and splits the packet data of a `Command` or `CommandLow` packet.
///
/// Returns the splitted packet data and their headers.
/// The headers have their type and the compressed and fragmented flag set
/// to the right value.
///
/// Returns an error if the packet is too large but cannot be splitted.
/// Only `Command` and `CommandLow` packets can be compressed and splitted.
pub fn compress_and_split(is_client: bool, packet: OutPacket) -> Vec<OutPacket> {
// Everything except whisper packets has to be less than 500 bytes
let header_size =
if is_client { tsproto_packets::C2S_HEADER_LEN } else { tsproto_packets::S2C_HEADER_LEN };
let data = packet.content();
// The maximum packet size (including header) is 500 bytes.
let max_size = 500 - header_size;
// Split the data if it is necessary.
let compressed;
let datas = if data.len() > max_size {
// Compress with QuickLZ
let cdata = ::quicklz::compress(data, CompressionLevel::Lvl1);
// Use only if it is efficient
let mut data = if cdata.len() > data.len() {
compressed = false;
data
} else {
compressed = true;
&cdata
};
// Ignore size limit for whisper packets
if data.len() <= max_size || packet.header().packet_type() == PacketType::VoiceWhisper {
let mut v = vec![0; header_size + data.len()];
v[header_size..].copy_from_slice(data);
vec![v]
} else {
// Split
let count = (data.len() + max_size - 1) / max_size;
let mut splitted = Vec::with_capacity(count);
while data.len() > max_size {
let (first, last) = data.split_at(max_size);
let mut v = vec![0; header_size + max_size];
v[header_size..].copy_from_slice(first);
splitted.push(v);
data = last;
}
// Rest
let mut v = vec![0; header_size + data.len()];
v[header_size..].copy_from_slice(data);
splitted.push(v);
splitted
}
} else {
return vec![packet];
};
let len = datas.len();
let fragmented = len > 1;
let orig_header = packet.header_bytes();
let dir = packet.direction();
let mut packets = Vec::with_capacity(datas.len());
for (i, mut d) in datas.into_iter().enumerate() {
d[..header_size].copy_from_slice(orig_header);
let mut packet = OutPacket::new_from_data(dir, d);
// Only set flags on first fragment
if i == 0 && compressed {
packet.flags(packet.header().flags() | Flags::COMPRESSED);
}
// Set fragmented flag on first and last part
if fragmented && (i == 0 || i == len - 1) {
packet.flags(packet.header().flags() | Flags::FRAGMENTED);
}
packets.push(packet);
}
packets
}
fn create_key_nonce(
p_type: PacketType, c_id: Option<u16>, p_id: u16, generation_id: u32, iv: &[u8; 64],
cache: &mut [[CachedKey; 2]; 8],
) -> (GenericArray<u8, U16>, GenericArray<u8, U16>) {
// Check if this generation is cached
let cache = &mut cache[p_type.to_usize().unwrap()][if c_id.is_some() { 1 } else { 0 }];
if cache.generation_id != generation_id {
// Update the cache
let mut temp = [0; 70];
if c_id.is_some() {
temp[0] = 0x31;
} else {
temp[0] = 0x30;
}
temp[1] = p_type.to_u8().unwrap();
(&mut temp[2..6]).write_be(generation_id).unwrap();
temp[6..].copy_from_slice(iv);
let keynonce = Sha256::digest(&temp[..]);
let keynonce = keynonce.as_slice();
cache.generation_id = generation_id;
cache.key.copy_from_slice(&keynonce[..16]);
cache.nonce.copy_from_slice(&keynonce[16..]);
}
// Use the cached version
let mut key = cache.key;
let nonce = cache.nonce;
key[0] ^= (p_id >> 8) as u8;
key[1] ^= (p_id & 0xff) as u8;
(key, nonce)
}
pub fn encrypt_key_nonce(
packet: &mut OutPacket, key: &GenericArray<u8, U16>, nonce: &GenericArray<u8, U16>,
) -> Result<()> {
let meta = packet.header().get_meta().to_vec();
let cipher = Eax::<aes::Aes128, U8>::new(key);
let mac = cipher
.encrypt_in_place_detached(nonce, &meta, packet.content_mut())
.map_err(|_| Error::MaxLengthExceeded("encryption data"))?;
packet.mac().copy_from_slice(mac.as_slice());
Ok(())
}
pub fn encrypt_fake(packet: &mut OutPacket) -> Result<()> {
encrypt_key_nonce(packet, &crate::FAKE_KEY.into(), &crate::FAKE_NONCE.into())
}
pub fn encrypt(
packet: &mut OutPacket, generation_id: u32, iv: &[u8; 64], cache: &mut [[CachedKey; 2]; 8],
) -> Result<()> {
let header = packet.header();
let (key, nonce) = create_key_nonce(
header.packet_type(),
header.client_id(),
header.packet_id(),
generation_id,
iv,
cache,
);
encrypt_key_nonce(packet, &key, &nonce)
}
pub fn decrypt_key_nonce(
packet: &InPacket, key: &GenericArray<u8, U16>, nonce: &GenericArray<u8, U16>,
) -> Result<Vec<u8>> {
let header = packet.header();
let meta = header.get_meta();
// TODO decrypt in-place in packet
let mut content = packet.content().to_vec();
let cipher = Eax::<aes::Aes128, U8>::new(key);
cipher
.decrypt_in_place_detached(nonce, meta, &mut content, header.mac().into())
.map(|()| content)
.map_err(|_| Error::WrongMac {
p_type: header.packet_type(),
generation_id: 0,
packet_id: header.packet_id(),
})
}
pub fn decrypt_fake(packet: &InPacket) -> Result<Vec<u8>> {
decrypt_key_nonce(packet, &crate::FAKE_KEY.into(), &crate::FAKE_NONCE.into())
}
pub fn decrypt(
packet: &InPacket, generation_id: u32, iv: &[u8; 64], cache: &mut [[CachedKey; 2]; 8],
) -> Result<Vec<u8>> {
let header = packet.header();
let (key, nonce) = create_key_nonce(
header.packet_type(),
header.client_id(),
header.packet_id(),
generation_id,
iv,
cache,
);
decrypt_key_nonce(packet, &key, &nonce).map_err(|e| {
if let Error::WrongMac { p_type, packet_id, .. } = e {
Error::WrongMac { p_type, generation_id, packet_id }
} else {
e
}
})
}
/// Compute shared iv and shared mac.
pub fn compute_iv_mac(
alpha: &[u8; 10], beta: &[u8; 54], our_key: &EccKeyPrivEd25519, other_key: &EdwardsPoint,
) -> ([u8; 64], [u8; 8]) {
let shared_secret = our_key.create_shared_secret(other_key);
let mut shared_iv = [0; 64];
shared_iv.copy_from_slice(Sha512::digest(shared_secret).as_slice());
for i in 0..10 {
shared_iv[i] ^= alpha[i];
}
for i in 0..54 {
shared_iv[i + 10] ^= beta[i];
}
let mut shared_mac = [0; 8];
shared_mac.copy_from_slice(&Sha1::digest(shared_iv).as_slice()[..8]);
(shared_iv, shared_mac)
}
pub fn hash_cash(key: &EccKeyPubP256, level: u8) -> u64 {
let omega = key.to_ts();
let mut offset = 0;
while offset < u64::MAX && get_hash_cash_level(&omega, offset) < level {
offset += 1;
}
offset
}
#[inline]
pub fn get_hash_cash_level(omega: &str, offset: u64) -> u8 {
let data = Sha1::digest(format!("{}{}", omega, offset).as_bytes());
let mut res = 0;
for &d in data.as_slice() {
if d == 0 {
res += 8;
} else {
res += d.trailing_zeros() as u8;
break;
}
}
res
}
pub fn biguint_to_array(i: &BigUint) -> [u8; 64] {
let mut v = i.to_bytes_le();
// Extend with zeroes until 64 bytes
let len = v.len();
v.append(&mut vec![0; 64 - len]);
v.reverse();
let mut a = [0; 64];
a.copy_from_slice(&v);
a
}
pub fn array_to_biguint(i: &[u8; 64]) -> BigUint { BigUint::from_bytes_be(i) }
#[cfg(test)]
mod tests {
use base64::prelude::*;
use super::*;
use crate::license::Licenses;
use crate::packets::PacketType;
use crate::utils;
use tsproto_types::crypto::EccKeyPubEd25519;
#[test]
fn test_fake_crypt() {
let data = (0..100).into_iter().collect::<Vec<_>>();
let mut packet = OutPacket::new_with_dir(Direction::C2S, Flags::empty(), PacketType::Ack);
packet.data_mut().extend_from_slice(&data);
encrypt_fake(&mut packet).unwrap();
let packet =
InPacket::try_new(Direction::C2S, packet.data_mut().as_slice().into()).unwrap();
let dec_data = decrypt_fake(&packet).unwrap();
assert_eq!(&data, &dec_data);
}
#[test]
fn test_fake_encrypt() {
let mut packet = OutAck::new(Direction::C2S, PacketType::Command, 0);
encrypt_fake(&mut packet).unwrap();
let real_res: &[u8] =
&[0xa4, 0x7b, 0x47, 0x94, 0xdb, 0xa9, 0x6a, 0xc5, 0, 0, 0, 0, 0x6, 0xfe, 0x18];
assert_eq!(real_res, packet.data_mut().as_slice());
}
#[test]
fn shared_iv31() {
let licenses = Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs\
0wFXkYuPUJVcDa6XCrZTcsvkB0Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAAC\
4R+5mos+UQ/KCbkpQLMI5WRp4wkQu8e5PZY4zU+/FlyAJwaE8CcJJ/A==")
.unwrap()).unwrap();
let derived_key =
licenses.derive_public_key(EccKeyPubEd25519::from_bytes(crate::ROOT_KEY)).unwrap();
let client_ek = [
0xb0, 0x4e, 0xa1, 0xd9, 0x5c, 0x72, 0x64, 0xdf, 0x0d, 0xe8, 0xb3, 0x6b, 0xaa, 0x7c,
0xa1, 0x5f, 0x75, 0x71, 0xf5, 0x1f, 0xa0, 0x54, 0xb5, 0x51, 0x27, 0x08, 0x8e, 0xdd,
0x96, 0x3d, 0x6e, 0x79,
];
let priv_key = EccKeyPrivEd25519::from_bytes(client_ek);
let alpha_b64 = BASE64_STANDARD.decode("Jkxq1wIvvhzaCA==").unwrap();
let mut alpha = [0; 10];
alpha.copy_from_slice(&alpha_b64);
let beta_b64 = BASE64_STANDARD
.decode("wU5T/MM6toW6Wge9th7VlTlzVZ9JDWypw2P9migfc25pjGP2Tj7Hm6rJpmKeHRr08Ch7BEAR")
.unwrap();
let mut beta = [0; 54];
beta.copy_from_slice(&beta_b64);
let expected_shared_shared_iv: [u8; 64] = [
0x58, 0x78, 0xae, 0x08, 0x08, 0x72, 0x05, 0xb0, 0x13, 0x27, 0x10, 0xe9, 0x81, 0xb4,
0xaf, 0x14, 0x14, 0x71, 0xad, 0xcd, 0x82, 0x98, 0xf3, 0xd1, 0x1d, 0x07, 0x20, 0x72,
0x7e, 0xb2, 0x1b, 0x89, 0x47, 0x82, 0x1e, 0xfb, 0x02, 0x53, 0x5a, 0x8a, 0x52, 0x4d,
0x9a, 0x7a, 0x09, 0x2c, 0x1b, 0xe7, 0x1f, 0xd1, 0x9d, 0x2a, 0x9d, 0x4f, 0xbd, 0xe3,
0x22, 0x09, 0xe4, 0x86, 0x7d, 0x63, 0x49, 0x07,
];
let expected_xored_shared_shared_iv: [u8; 64] = [
0x7e, 0x34, 0xc4, 0xdf, 0x0a, 0x5d, 0xbb, 0xac, 0xc9, 0x2f, 0xd1, 0xa7, 0xd2, 0x48,
0x6c, 0x2e, 0xa2, 0xf4, 0x17, 0x97, 0x85, 0x25, 0x45, 0xcf, 0xc8, 0x92, 0x19, 0x01,
0x2b, 0x2d, 0x52, 0x84, 0x2b, 0x2b, 0xdd, 0x98, 0xff, 0xc9, 0x72, 0x95, 0x21, 0x23,
0xf3, 0xf6, 0x6a, 0xda, 0x55, 0xd9, 0xd8, 0x4a, 0x37, 0xe3, 0x3b, 0x2d, 0x23, 0xfe,
0x38, 0xfd, 0x14, 0xae, 0x06, 0x67, 0x09, 0x16,
];
let (mut shared_iv, _shared_mac) = compute_iv_mac(&alpha, &beta, &priv_key, &derived_key);
assert_eq!(&shared_iv as &[u8], &expected_xored_shared_shared_iv as &[u8]);
for i in 0..10 {
shared_iv[i] ^= alpha[i];
}
for i in 0..54 {
shared_iv[i + 10] ^= beta[i];
}
assert_eq!(&shared_iv as &[u8], &expected_shared_shared_iv as &[u8]);
let mut temp = [0; 70];
temp[0] = 0x31;
temp[1] = 0x2 & 0xf;
temp[6..].copy_from_slice(&expected_xored_shared_shared_iv);
let temporary: [u8; 70] = [
0x31, 0x02, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x34, 0xc4, 0xdf, 0x0a, 0x5d, 0xbb, 0xac,
0xc9, 0x2f, 0xd1, 0xa7, 0xd2, 0x48, 0x6c, 0x2e, 0xa2, 0xf4, 0x17, 0x97, 0x85, 0x25,
0x45, 0xcf, 0xc8, 0x92, 0x19, 0x01, 0x2b, 0x2d, 0x52, 0x84, 0x2b, 0x2b, 0xdd, 0x98,
0xff, 0xc9, 0x72, 0x95, 0x21, 0x23, 0xf3, 0xf6, 0x6a, 0xda, 0x55, 0xd9, 0xd8, 0x4a,
0x37, 0xe3, 0x3b, 0x2d, 0x23, 0xfe, 0x38, 0xfd, 0x14, 0xae, 0x06, 0x67, 0x09, 0x16,
];
assert!(&temp as &[u8] == &temporary as &[u8]);
let keynonce = Sha256::digest(&temp);
let expected_keynonce: [u8; 32] = [
0xf3, 0x70, 0xd3, 0x43, 0xe7, 0x78, 0x15, 0x70, 0x7a, 0xff, 0x60, 0x48, 0xfb, 0xd9,
0xac, 0x6b, 0xb6, 0x33, 0x35, 0x79, 0x31, 0x9b, 0x88, 0x0e, 0x2d, 0x25, 0xef, 0x9c,
0xe9, 0x9e, 0x77, 0x5c,
];
assert!(keynonce.as_slice() == &expected_keynonce as &[u8]);
}
#[test]
fn test_new_decrypt() {
let shared_iv = utils::read_hex(
"C2 45 6F CB FC 22 08 AE 44 2B 7D E7 3A 67 1B DA 93 09 B2 00 F2 CD 10 49 08 CD 3A B0 \
7B DD 58 AD",
)
.unwrap();
let mut shared_iv = Sha512::digest(&shared_iv).as_slice().to_vec();
assert_eq!(
utils::read_hex(
"4D 3F DA B7 D8 B0 2C 82 70 6A 39 3E 97 17 61 09 FA 03 AB 30 5C BB 78 7A 9A 82 D5 \
39 9A 60 FD A9 F6 7A D9 04 52 F2 AE 00 3E 35 E8 19 10 89 40 43 80 58 27 1F 0A E0 \
E0 3D E0 9C F0 A3 4D 15 6B F0"
)
.unwrap()
.as_slice(),
shared_iv.as_slice()
);
let alpha = [0; 10];
let beta = BASE64_STANDARD
.decode("I4onb0zMyAD6bd24QANDls40eOES7qmjonBFtt5wRWzAfIIQWTSxjEas6TGTZIJ8QSJNX+Pl")
.unwrap();
for i in 0..10 {
shared_iv[i] ^= alpha[i];
}
for i in 0..54 {
shared_iv[i + 10] ^= beta[i];
}
let mut temp = [0; 70];
temp[0] = 0x31;
temp[1] = 0x2 & 0xf;
temp[6..].copy_from_slice(&shared_iv);
let keynonce = Sha256::digest(&temp);
let keynonce = keynonce.as_slice();
let all = utils::read_hex("2b982443ab38be6b00020000329abf64d4572e1349897b5e1e96fbc4a763a4c4ce1f64f0c1e3febd0a5f04a82ab1f2bc2344bb374fd16181beb8233b5b06944280470e9b6893290a1da0776ffcd89f3beec2ce23b9694930c09efaaea0d88a6895a08ede4d5cbfea61291fc553ac651f1e2bc1d2bd277a8bd9ab5386415579a9e56fac46d8b6b119f454bebd99179cd317dec60af205341d11f274d02bbacdd7e9773f72a426358ca1d39016dd95bde2409cd81bf99b340887e997ea982370c6790cf4d23150460820224766838ea4ec4d71dd102ede701ea0001f392623aa410dd9ab0e45874da82e29e6e370515ec30a37dd73f5a364c233ff014384beab5f1708c9f48dfba33a520f8fcdcef055789c54693c3fe72c5bfaca7cb4ca1fed77b8624660b8abc882f4b95b1284cb6dc55019c6082dd6dd146fa50383662d7298bef04ababaf1af80e15cd4c1f81326f085788e2918e00324147dce39b23db71326abc3de4b94df10f1531e9cce202bba71fa3ebeefd77b21fa3260a62e92eeee2183421d384a8c48777e2f9efbc58d4f442c5f0529c7c0e27e81b2b6b1b05eb8fa19256886248d553582dfd24c7cfab3c3f7317a5cebc6504b53fa0e86fc8c1100fc1d506fcf96caa76a7c0b6a27e577f2efdecd4070e847a559bf37d75bfdbe9e814c702426ce696d8645bc300b5f28f9e7f1ce").unwrap();
let packet = InPacket::try_new(Direction::C2S, &all).unwrap();
println!("Packet: {:?}", packet);
let mut key = [0; 16];
let mut nonce = [0; 16];
key.copy_from_slice(&keynonce[..16]);
nonce.copy_from_slice(&keynonce[16..]);
let expected_key =
utils::read_hex("D2 42 75 71 9C EE 83 35 EF 8A CE E0 B7 28 40 B8").unwrap();
let expected_nonce =
utils::read_hex("9C D9 30 B7 58 FE 50 23 64 66 11 C5 36 0E A2 5F").unwrap();
assert_eq!(&expected_nonce, &nonce);
assert_eq!(&expected_key, &key);
key[1] ^= 2; // packet id
let dec = decrypt_key_nonce(&packet, &key.into(), &nonce.into()).unwrap();
println!("Decrypted: {:?}", String::from_utf8_lossy(&dec));
}
}
File diff suppressed because it is too large. Load diff
+449
View File
@@ -0,0 +1,449 @@
use std::collections::VecDeque;
use std::io;
use std::mem;
use std::net::SocketAddr;
use std::pin::Pin;
use std::task::{Context, Poll};
use futures::prelude::*;
use generic_array::GenericArray;
use generic_array::typenum::consts::U16;
use num_traits::ToPrimitive;
use tokio::io::ReadBuf;
use tokio::net::UdpSocket;
use tracing::{Span, info_span};
use tsproto_packets::packets::*;
use tsproto_types::crypto::EccKeyPubP256;
use crate::packet_codec::PacketCodec;
use crate::resend::{PacketId, PartialPacketId, Resender, ResenderState};
use crate::{Error, MAX_UDP_PACKET_LENGTH, Result, UDP_SINK_CAPACITY};
/// The needed functions, this can be used to abstract from the underlying
/// transport and allows simulation.
pub trait Socket {
fn poll_recv_from(&self, cx: &mut Context, buf: &mut ReadBuf) -> Poll<io::Result<SocketAddr>>;
fn poll_send_to(
&self, cx: &mut Context, buf: &[u8], target: SocketAddr,
) -> Poll<io::Result<usize>>;
fn local_addr(&self) -> io::Result<SocketAddr>;
}
/// A cache for the key and nonce for a generation id.
/// This has to be stored for each packet type.
#[derive(Debug)]
pub struct CachedKey {
pub generation_id: u32,
pub key: GenericArray<u8, U16>,
pub nonce: GenericArray<u8, U16>,
}
/// Data that has to be stored for a connection when it is connected.
pub struct ConnectedParams {
/// The client id of this connection.
pub c_id: u16,
/// If voice packets should be encrypted
pub voice_encryption: bool,
/// The public key of the other side.
pub public_key: EccKeyPubP256,
/// The iv used to encrypt and decrypt packets.
pub shared_iv: [u8; 64],
/// The mac used for unencrypted packets.
pub shared_mac: [u8; 8],
/// Cached key and nonce per packet type and for server to client (without
/// client id inside the packet) and client to server communication.
pub key_cache: [[CachedKey; 2]; 8],
}
/// An event that originates from a tsproto raw connection.
#[derive(Debug)]
pub enum Event<'a> {
ReceiveUdpPacket(&'a InUdpPacket<'a>),
ReceivePacket(&'a InPacket<'a>),
SendUdpPacket(&'a OutUdpPacket),
SendPacket(&'a OutPacket),
}
/// An item that originates from a tsproto raw event stream.
///
/// The disconnected event is signaled by returning `None` from the stream.
#[derive(Debug)]
pub enum StreamItem {
Command(InCommandBuf),
Audio(InAudioBuf),
C2SInit(InC2SInitBuf),
S2CInit(InS2CInitBuf),
/// All packets with an id less or equal to this id were acknowledged.
AckPacket(PacketId),
/// The network statistics were updated.
NetworkStatsUpdated,
Error(Error),
}
type EventListener = Box<dyn for<'a> Fn(&'a Event<'a>) + Send>;
/// Represents a currently alive connection.
pub struct Connection {
pub is_client: bool,
pub span: Span,
/// The parameters of this connection, if it is already established.
pub params: Option<ConnectedParams>,
/// The address of the other side, where packets are coming from and going
/// to.
pub address: SocketAddr,
pub resender: Resender,
pub codec: PacketCodec,
pub udp_socket: Box<dyn Socket + Send>,
udp_buffer: Vec<u8>,
/// A buffer of packets that should be returned from the stream.
///
/// If a new udp packet is received and we already received the following
/// ids, we can get multiple packets back at once. As we can only return one
/// from the stream, the rest is stored here.
pub(crate) stream_items: VecDeque<StreamItem>,
/// The queue of non-command packets that should be sent.
///
/// These packets are not influenced by congestion control.
/// If it gets too long, we don't poll from the `udp_socket` anymore.
acks_to_send: VecDeque<OutUdpPacket>,
pub event_listeners: Vec<EventListener>,
}
impl Socket for UdpSocket {
fn poll_recv_from(&self, cx: &mut Context, buf: &mut ReadBuf) -> Poll<io::Result<SocketAddr>> {
self.poll_recv_from(cx, buf)
}
fn poll_send_to(
&self, cx: &mut Context, buf: &[u8], target: SocketAddr,
) -> Poll<io::Result<usize>> {
self.poll_send_to(cx, buf, target)
}
fn local_addr(&self) -> io::Result<SocketAddr> { self.local_addr() }
}
impl Default for CachedKey {
fn default() -> Self {
CachedKey { generation_id: u32::MAX, key: [0; 16].into(), nonce: [0; 16].into() }
}
}
impl ConnectedParams {
/// Fills the parameters for a connection with their default state.
pub fn new(public_key: EccKeyPubP256, shared_iv: [u8; 64], shared_mac: [u8; 8]) -> Self {
Self {
c_id: 0,
voice_encryption: true,
public_key,
shared_iv,
shared_mac,
key_cache: Default::default(),
}
}
}
impl Connection {
pub fn new(is_client: bool, address: SocketAddr, udp_socket: Box<dyn Socket + Send>) -> Self {
let span = info_span!("connection", local_addr = %udp_socket.local_addr().unwrap(),
remote_addr = %address);
let mut res = Self {
is_client,
span,
params: None,
address,
resender: Default::default(),
codec: Default::default(),
udp_socket,
udp_buffer: Default::default(),
stream_items: Default::default(),
acks_to_send: Default::default(),
event_listeners: Default::default(),
};
if is_client {
// The first command is sent as part of the C2SInit::Init4 packet
// so it does not get registered automatically.
res.codec.outgoing_p_ids[PacketType::Command.to_usize().unwrap()] =
PartialPacketId { generation_id: 0, packet_id: 1 };
} else {
res.codec.incoming_p_ids[PacketType::Command.to_usize().unwrap()] =
PartialPacketId { generation_id: 0, packet_id: 1 };
}
res
}
/// Check if a given id is in the receive window.
///
/// Returns
/// 1. If the packet id is inside the receive window
/// 1. The generation of the packet
/// 1. The minimum accepted packet id
/// 1. The maximum accepted packet id
pub(crate) fn in_receive_window(&self, p_type: PacketType, p_id: u16) -> (bool, u32, u16, u16) {
if p_type == PacketType::Init {
return (true, 0, 0, 0);
}
let type_i = p_type.to_usize().unwrap();
// Receive window is the next half of ids
let cur_next = self.codec.incoming_p_ids[type_i].packet_id;
let (limit, next_gen) = cur_next.overflowing_add(u16::MAX / 2);
let gen = self.codec.incoming_p_ids[type_i].generation_id;
let in_recv_win = (!next_gen && p_id >= cur_next && p_id < limit)
|| (next_gen && (p_id >= cur_next || p_id < limit));
let gen_id = if in_recv_win {
if next_gen && p_id < limit { gen + 1 } else { gen }
} else if p_id < cur_next {
gen
} else {
gen - 1
};
(in_recv_win, gen_id, cur_next, limit)
}
pub fn send_event(&self, event: &Event) {
for l in &self.event_listeners {
l(event)
}
}
pub fn hand_back_buffer(&mut self, buffer: Vec<u8>) {
if self.udp_buffer.capacity() < MAX_UDP_PACKET_LENGTH
&& buffer.capacity() >= MAX_UDP_PACKET_LENGTH
{
self.udp_buffer = buffer;
}
}
fn poll_send_acks(&mut self, cx: &mut Context) -> Result<()> {
// Poll acks_to_send
while let Some(packet) = self.acks_to_send.front() {
match self.poll_send_udp_packet(cx, packet) {
Poll::Ready(Ok(())) => {
self.resender.handle_loss_outgoing(packet);
}
Poll::Ready(Err(e)) => return Err(e),
Poll::Pending => break,
}
self.acks_to_send.pop_front();
}
Ok(())
}
fn poll_incoming_udp_packet(&mut self, cx: &mut Context) -> Poll<Result<StreamItem>> {
if self.acks_to_send.len() >= UDP_SINK_CAPACITY {
return Poll::Pending;
}
loop {
// Poll udp_socket
if self.udp_buffer.len() != MAX_UDP_PACKET_LENGTH {
self.udp_buffer.resize(MAX_UDP_PACKET_LENGTH, 0);
}
let mut read_buf = ReadBuf::new(&mut self.udp_buffer);
match self.udp_socket.poll_recv_from(cx, &mut read_buf) {
Poll::Ready(Ok(addr)) => {
let size = read_buf.filled().len();
let mut udp_buffer = mem::take(&mut self.udp_buffer);
udp_buffer.truncate(size);
match self.handle_udp_packet(cx, udp_buffer, addr) {
Ok(()) => {
if let Some(item) = self.stream_items.pop_front() {
return Poll::Ready(Ok(item));
}
}
Err(e) => {
return Poll::Ready(Err(e));
}
}
}
// Udp socket closed
Poll::Ready(Err(e)) => return Poll::Ready(Err(Error::Network(e))),
Poll::Pending => return Poll::Pending,
}
}
}
fn handle_udp_packet(
&mut self, cx: &mut Context, udp_buffer: Vec<u8>, addr: SocketAddr,
) -> Result<()> {
let _span = self.span.clone().entered();
if addr != self.address {
self.stream_items.push_back(StreamItem::Error(Error::WrongAddress));
return Ok(());
}
let dir = if self.is_client { Direction::S2C } else { Direction::C2S };
let packet = InUdpPacket(match InPacket::try_new(dir, &udp_buffer) {
Ok(r) => r,
Err(e) => {
self.stream_items.push_back(StreamItem::Error(Error::PacketParse("udp", e)));
return Ok(());
}
});
let event = Event::ReceiveUdpPacket(&packet);
self.send_event(&event);
self.resender.received_packet();
PacketCodec::handle_udp_packet(self, cx, udp_buffer)?;
Ok(())
}
/// Try to send an ack packet.
///
/// If it does not work, add it to the ack queue.
pub(crate) fn send_ack_packet(&mut self, cx: &mut Context, packet: OutPacket) -> Result<()> {
self.send_event(&Event::SendPacket(&packet));
let mut udp_packets = PacketCodec::encode_packet(self, packet)?;
assert_eq!(
udp_packets.len(),
1,
"Encoding an ack packet should only yield a single packet"
);
let packet = udp_packets.pop().unwrap();
match self.poll_send_udp_packet(cx, &packet) {
Poll::Ready(r) => {
if r.is_ok() {
self.resender.handle_loss_outgoing(&packet);
}
r
}
Poll::Pending => {
self.acks_to_send.push_back(packet);
Ok(())
}
}
}
/// Add a packet to the send queue.
///
/// This function buffers indefinitely, to prevent using a large amount of
/// memory, check `is_send_queue_full` first and only send a packet if this
/// function returns `false`.
///
/// When the `PacketId` which is returned by this function is acknowledged,
/// the packet was successfully received by the other side of the
/// connection.
pub fn send_packet(&mut self, packet: OutPacket) -> Result<PacketId> {
self.send_event(&Event::SendPacket(&packet));
let udp_packets = PacketCodec::encode_packet(self, packet)?;
let id = udp_packets.last().unwrap().into();
for p in udp_packets {
self.send_udp_packet(p);
}
Ok(id)
}
/// Add an udp packet to the send queue.
pub fn send_udp_packet(&mut self, packet: OutUdpPacket) {
let _span = self.span.clone().entered();
match packet.packet_type() {
PacketType::Init | PacketType::Command | PacketType::CommandLow => {
Resender::send_packet(self, packet);
}
_ => self.acks_to_send.push_back(packet),
}
}
pub fn poll_send_udp_packet(
&self, cx: &mut Context, packet: &OutUdpPacket,
) -> Poll<Result<()>> {
Self::static_poll_send_udp_packet(
&*self.udp_socket,
self.address,
&self.event_listeners,
cx,
packet,
)
}
/// Remember to add the size of the sent packet to the stats in the resender.
pub fn static_poll_send_udp_packet(
udp_socket: &dyn Socket, address: SocketAddr, event_listeners: &[EventListener],
cx: &mut Context, packet: &OutUdpPacket,
) -> Poll<Result<()>> {
let data = packet.data().data();
match udp_socket.poll_send_to(cx, data, address).map_err(Error::Network)? {
Poll::Pending => Poll::Pending,
Poll::Ready(size) => {
let event = Event::SendUdpPacket(packet);
for l in event_listeners {
l(&event)
}
if size != data.len() {
Poll::Ready(Err(Error::Network(std::io::Error::new(
std::io::ErrorKind::Other,
"Failed to send whole udp packet",
))))
} else {
Poll::Ready(Ok(()))
}
}
}
}
pub fn is_send_queue_full(&self) -> bool { self.resender.is_full() }
pub fn is_send_queue_empty(&self) -> bool { self.resender.is_empty() }
}
/// Pull for events.
///
/// `Ok(StreamItem::Error)` is recoverable, `Err()` is not.
///
/// Polling does a few things in round robin fashion:
/// 1. Check for new udp packets
/// 2. Use the resender to resend packets if necessary
/// 3. Use the resender to send ping packets if necessary
impl Stream for Connection {
type Item = Result<StreamItem>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let _span = self.span.clone().entered();
if let Err(e) = self.poll_send_acks(cx) {
return Poll::Ready(Some(Err(e)));
}
if self.resender.get_state() == ResenderState::Disconnected {
// Send all ack packets and return `None` afterwards
if self.acks_to_send.is_empty() {
return Poll::Ready(None);
}
}
// Use the resender to resend packets
match Resender::poll_resend(&mut self, cx) {
Ok(()) => {}
Err(e) => return Poll::Ready(Some(Err(e))),
}
// Use the resender to send pings
match Resender::poll_ping(&mut self, cx) {
Ok(()) => {}
Err(e) => return Poll::Ready(Some(Err(e))),
}
// Return existing stream_items
if let Some(item) = self.stream_items.pop_front() {
return Poll::Ready(Some(Ok(item)));
}
// Check for new udp packets
match self.poll_incoming_udp_packet(cx) {
Poll::Ready(r) => return Poll::Ready(Some(r)),
Poll::Pending => {}
}
Poll::Pending
}
}
+253
View File
@@ -0,0 +1,253 @@
//! This library implements the TeamSpeak3 protocol.
//!
//! For a usable library to build clients and bots, you should take a look at
//! [`tsclientlib`](https://github.com/ReSpeak/tsclientlib), which provides a
//! convenient interface to this library.
//!
//! If you are searching for a usable client, [Qint](https://github.com/ReSpeak/Qint)
//! is a cross-platform TeamSpeak client, which is using this library (more
//! correctly, it is using `tsclientlib`).
//!
//! For more info on this project, take a look at the
//! [tsclientlib README](https://github.com/ReSpeak/tsclientlib).
use std::fmt;
use std::num::ParseIntError;
use base64::prelude::*;
use serde::de::{Unexpected, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;
use tsproto_packets::packets;
use tsproto_types::crypto::EccKeyPrivP256;
pub mod algorithms;
pub mod client;
pub mod connection;
pub mod license;
pub mod log;
pub mod packet_codec;
pub mod resend;
pub mod utils;
use algorithms as algs;
// The build environment of tsproto.
git_testament::git_testament!(TESTAMENT);
#[doc(hidden)]
pub fn get_testament() -> &'static git_testament::GitTestament<'static> { &TESTAMENT }
type Result<T> = std::result::Result<T, Error>;
/// The maximum number of bytes for a fragmented packet.
///
/// The maximum packet size is 500 bytes, as used by
/// `algorithms::compress_and_split`.
/// We pick the ethernet MTU for possible future compatibility, it is unlikely
/// that a packet will get bigger.
pub const MAX_UDP_PACKET_LENGTH: usize = 1500;
/// The maximum number of bytes for a fragmented packet.
#[allow(clippy::unreadable_literal)]
const MAX_FRAGMENTS_LENGTH: usize = 40960;
/// The maximum number of packets which are stored, if they are received
/// out-of-order.
const MAX_QUEUE_LEN: u16 = 200;
/// The maximum decompressed size of a packet.
#[allow(clippy::unreadable_literal)]
/// On large servers with more than 2000 channels, the notifychannelsubscribed packet can be
/// 50 kB large (uncompressed). A maximum size to 2 MiB should allow for even larger servers.
const MAX_DECOMPRESSED_SIZE: u32 = 2 * 1024 * 1024;
const FAKE_KEY: [u8; 16] = *b"c:\\windows\\syste";
const FAKE_NONCE: [u8; 16] = *b"m\\firewall32.cpl";
/// The root key in the TeamSpeak license system.
pub const ROOT_KEY: [u8; 32] = [
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,
];
/// The maximum amount of ack pachets that a connection intermediately stores.
///
/// When this amount is stored, no new packets will be polled from the UDP
/// connection.
const UDP_SINK_CAPACITY: usize = 50;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error("Failed to create ack packet: {0}")]
CreateAck(#[source] tsproto_packets::Error),
#[error("Failed to decompress packet: {0}")]
DecompressPacket(#[source] quicklz::Error),
#[error(transparent)]
IdentityCrypto(tsproto_types::crypto::Error),
#[error("Failed to parse int: {0}")]
InvalidHex(#[source] ParseIntError),
#[error("Maximum length exceeded for {0}")]
MaxLengthExceeded(&'static str),
#[error("Network error: {0}")]
Network(#[source] std::io::Error),
#[error("Packet {id} not in receive window [{next};{limit}) for type {p_type:?}")]
NotInReceiveWindow { id: u16, next: u16, limit: u16, p_type: packets::PacketType },
#[error("Failed to parse {0} packet: {1}")]
PacketParse(&'static str, #[source] tsproto_packets::Error),
#[error("Connection timed out: {0}")]
Timeout(&'static str),
#[error("Got unallowed unencrypted packet")]
UnallowedUnencryptedPacket,
#[error("Got unexpected init packet")]
UnexpectedInitPacket,
#[error("Packet has wrong client id {0}")]
WrongClientId(u16),
#[error("Received udp packet from wrong address")]
WrongAddress,
#[error("{p_type:?} Packet {generation_id}:{packet_id} has a wrong mac")]
WrongMac { p_type: packets::PacketType, generation_id: u32, packet_id: u16 },
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Identity {
#[serde(serialize_with = "serialize_id_key", deserialize_with = "deserialize_id_key")]
key: EccKeyPrivP256,
/// The `client_key_offset`/counter for hash cash.
counter: u64,
/// The maximum counter that was tried, this is greater or equal to
/// `counter` but may yield a lower level.
max_counter: u64,
}
struct IdKeyVisitor;
impl<'de> Visitor<'de> for IdKeyVisitor {
type Value = EccKeyPrivP256;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "a P256 private ecc key")
}
fn visit_str<E: serde::de::Error>(self, s: &str) -> std::result::Result<Self::Value, E> {
EccKeyPrivP256::import_str(s)
.map_err(|_| serde::de::Error::invalid_value(Unexpected::Str(s), &self))
}
}
fn serialize_id_key<S: Serializer>(
key: &EccKeyPrivP256, s: S,
) -> std::result::Result<S::Ok, S::Error> {
s.serialize_str(&BASE64_STANDARD.encode(key.to_short()))
}
fn deserialize_id_key<'de, D: Deserializer<'de>>(
d: D,
) -> std::result::Result<EccKeyPrivP256, D::Error> {
d.deserialize_str(IdKeyVisitor)
}
impl Identity {
#[inline]
pub fn create() -> Self {
let mut res = Self::new(EccKeyPrivP256::create(), 0);
res.upgrade_level(8);
res
}
#[inline]
pub fn new(key: EccKeyPrivP256, counter: u64) -> Self {
Self::new_with_max_counter(key, counter, counter)
}
#[inline]
pub fn new_with_max_counter(key: EccKeyPrivP256, counter: u64, max_counter: u64) -> Self {
Self { key, counter, max_counter }
}
#[inline]
pub fn new_from_str(key: &str) -> Result<Self> {
if let Ok(identity) = Identity::new_from_ts_str(key) {
return Ok(identity);
}
let mut res = Self::new(EccKeyPrivP256::import_str(key).map_err(Error::IdentityCrypto)?, 0);
res.upgrade_level(8);
Ok(res)
}
pub fn new_from_ts_str(key: &str) -> Result<Self> {
let counter_separator = key
.find('V')
.ok_or(Error::IdentityCrypto(tsproto_types::crypto::Error::NoCounterBlock))?;
let counter = key[..counter_separator]
.parse::<u64>()
.map_err(|_| Error::IdentityCrypto(tsproto_types::crypto::Error::NoCounterBlock))?;
let ecc_key = EccKeyPrivP256::import_str(&key[(counter_separator + 1)..])
.map_err(Error::IdentityCrypto)?;
Ok(Self::new(ecc_key, counter))
}
#[inline]
pub fn new_from_bytes(key: &[u8]) -> Result<Self> {
let mut res = Self::new(EccKeyPrivP256::import(key).map_err(Error::IdentityCrypto)?, 0);
res.upgrade_level(8);
Ok(res)
}
#[inline]
pub fn key(&self) -> &EccKeyPrivP256 { &self.key }
#[inline]
pub fn counter(&self) -> u64 { self.counter }
#[inline]
pub fn max_counter(&self) -> u64 { self.max_counter }
#[inline]
pub fn set_key(&mut self, key: EccKeyPrivP256) { self.key = key }
#[inline]
pub fn set_counter(&mut self, counter: u64) { self.counter = counter; }
#[inline]
pub fn set_max_counter(&mut self, max_counter: u64) { self.max_counter = max_counter; }
/// Compute the current hash cash level.
#[inline]
pub fn level(&self) -> u8 {
let omega = self.key.to_pub().to_ts();
algs::get_hash_cash_level(&omega, self.counter)
}
/// Compute a better hash cash level.
pub fn upgrade_level(&mut self, target: u8) {
let omega = self.key.to_pub().to_ts();
let mut offset = self.max_counter;
while offset < u64::MAX && algs::get_hash_cash_level(&omega, offset) < target {
offset += 1;
}
self.counter = offset;
self.max_counter = offset;
}
}
#[cfg(test)]
mod identity_tests {
use super::*;
const TEST_PRIV_KEY: &str =
"MG8DAgeAAgEgAiEA6rtKxDn/o/Bo50rNtAE5Ph3h2RKLHQ0gbFkvm2yA79kCIQCrfzAZts/\
vHP+3MOetKLjNnpZXt4c6U3UB4gWLKR4H9AIgYTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=";
const TEST_UID: &str = "test/9PZ9vww/Bpf5vJxtJhpz80=";
#[test]
fn parse_ts_base64() {
let identity = Identity::new_from_str(TEST_PRIV_KEY).unwrap();
let uid = identity.key().to_pub().get_uid();
assert_eq!(TEST_UID, &uid);
}
#[test]
fn parse_ts_base64_with_offset() {
let ident_str = String::from("2792354V") + TEST_PRIV_KEY;
let identity = Identity::new_from_str(&ident_str).unwrap();
let uid = identity.key().to_pub().get_uid();
assert_eq!(TEST_UID, &uid);
assert_eq!(identity.level(), 21u8);
}
}
+932
View File
@@ -0,0 +1,932 @@
use std::convert::{TryFrom, TryInto};
use std::fmt;
use std::io::Cursor;
use std::str;
use curve25519_dalek_ng::edwards::EdwardsPoint;
use curve25519_dalek_ng::scalar::Scalar;
use num_derive::{FromPrimitive, ToPrimitive};
use num_traits::{FromPrimitive as _, ToPrimitive as _};
use omnom::{ReadExt, WriteExt};
use sha2::{Digest, Sha512};
use thiserror::Error;
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
use tracing::trace;
use tsproto_packets::HexSlice;
use tsproto_types::{
LicenseType,
crypto::{EccKeyPrivEd25519, EccKeyPubEd25519},
};
pub const TIMESTAMP_OFFSET: i64 = 0x50e2_2700;
const BLOCK_MIN_LEN: usize = 42;
const BLOCK_TYPE_OFFSET: usize = 33;
const BLOCK_NOT_VALID_BEFORE_OFFSET: usize = 34;
const BLOCK_NOT_VALID_AFTER_OFFSET: usize = 38;
type Result<T> = std::result::Result<T, Error>;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error(
"License must not exceed bounds {outer_start} - {outer_end} but has {inner_start} - \
{inner_end}"
)]
Bounds {
outer_start: OffsetDateTime,
outer_end: OffsetDateTime,
inner_start: OffsetDateTime,
inner_end: OffsetDateTime,
},
#[error("Failed to deserialize license: {0}")]
Deserialize(#[source] std::io::Error),
#[error("Failed to deserialize license: {0}")]
DeserializeString(#[source] std::str::Utf8Error),
#[error("Failed to deserialize date: {0}")]
DeserializeDate(#[source] time::error::ComponentRange),
#[error("License is only valid between {start} and {end}")]
Expired { start: OffsetDateTime, end: OffsetDateTime },
#[error("Cannot uncompress license public key")]
InvalidPublicKey,
#[error("Invalid data {0:#x} in intermediate license")]
IntermediateInvalidData(u32),
#[error("Invalid public root key for license")]
InvalidRootKey,
#[error("Non-null-terminated string")]
NonterminatedString,
#[error("License contains no private key")]
NoPrivateKey,
#[error("Too many license blocks: {0}")]
TooManyBlocks(usize),
#[error("License too short ({0}): {1}")]
TooShort(usize, &'static str),
#[error("Unknown license block type {0}")]
UnknownBlockType(u8),
#[error("Unknown license type {0}")]
UnknownLicenseType(u8),
#[error("Unsupported license version {0}")]
UnsupportedVersion(u8),
#[error("Wrong key kind {0} in license")]
WrongKeyKind(u8),
#[error("There is no {0} in this block")]
NoSuchProperty(&'static str),
#[error("Wrong property type for id {id}: Expected type {expected} but got type {actual}")]
WrongPropertyType { id: u8, expected: u8, actual: u8 },
#[error(
"Property with id {id} and type {typ} has wrong length: Expected length {expected} but \
got length {actual}"
)]
WrongPropertyLength { id: u8, typ: u8, expected: u8, actual: u8 },
}
/// A single block of a license
#[derive(Clone, Debug)]
pub struct License {
/// Length of the block
pub len: usize,
/// A private key for the block to derive a private key
pub private_key: Option<EccKeyPrivEd25519>,
pub inner: InnerLicense,
}
/// Helper struct to debug print a license block.
pub struct DebugLicense<'a>(&'a License, &'a [u8]);
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq, FromPrimitive, ToPrimitive)]
pub enum LicenseBlockType {
Intermediate,
Website,
/// Ts3_Server
Server,
Code,
// Not existing in the license parameter:
// 4: Token, 5: License_Sign, 6: MyTsId_Sign, 7: Updater
/// Ts_Server_License
Ts5Server = 8,
/// 32, Ephemeral_Key
Ephemeral = 32,
}
#[derive(Debug, Clone)]
pub enum InnerLicense {
Ts5Server {
/// Properties from the license, offset from the start of properties for every field
properties: Vec<usize>,
},
Other,
}
/// A list of blocks, forming a complete license
#[derive(Clone)]
pub struct Licenses {
pub data: Vec<u8>,
pub blocks: Vec<License>,
}
#[derive(Clone, Debug)]
pub enum LicenseProperty<'a> {
/// Unknown property with id 1 and type 1
Unknown1(u32),
Issuer(&'a str),
MaxClients(u32),
Unknown {
id: u8,
typ: u8,
data: &'a [u8],
},
}
#[derive(Debug)]
pub struct LicenseBuilder<'a> {
licenses: &'a mut Licenses,
}
#[derive(Debug)]
pub struct LicenseBlockBuilder<'a, 'b> {
builder: &'b mut LicenseBuilder<'a>,
/// The start offset for the new block
offset: usize,
typ: LicenseBlockType,
}
type LicenseTimeBounds = (OffsetDateTime, OffsetDateTime);
impl Licenses {
pub fn new() -> Self { Self::default() }
/// Parse a license but ignore expired licenses.
///
/// This is useful for tests but should not be used otherwise.
pub fn parse_ignore_expired(data: Vec<u8>) -> Result<Self> { Self::parse_internal(data, false) }
pub fn parse(data: Vec<u8>) -> Result<Self> { Self::parse_internal(data, true) }
pub fn parse_internal(data: Vec<u8>, check_expired: bool) -> Result<Self> {
let version = data[0];
if version != 0 && version != 1 {
return Err(Error::UnsupportedVersion(version));
}
// Read licenses
let mut blocks = Vec::new();
let now = OffsetDateTime::now_utc();
let mut offset = 1;
let mut bounds = None;
while data.len() > offset {
if blocks.len() >= 8 {
// Accept only 8 blocks
return Err(Error::TooManyBlocks(blocks.len()));
}
// Read next license
let (license, b) = Self::parse_block(&data[offset..], check_expired, now, bounds)?;
offset += license.len;
bounds = Some(b);
blocks.push(license);
}
Ok(Licenses { data, blocks })
}
fn parse_block(
data: &[u8], check_expired: bool, now: OffsetDateTime, bounds: Option<LicenseTimeBounds>,
) -> Result<(License, LicenseTimeBounds)> {
let license = License::parse(data)?;
let license_data = &data[..license.len];
// Check if the certificate is valid
let new_bounds = (
license.get_not_valid_before(license_data)?,
license.get_not_valid_after(license_data)?,
);
if new_bounds.0 > now && check_expired {
return Err(Error::Expired { start: new_bounds.0, end: new_bounds.1 });
}
if new_bounds.1 < now && check_expired {
return Err(Error::Expired { start: new_bounds.0, end: new_bounds.1 });
}
if let Some((start, end)) = bounds {
// The inner license must not have wider bounds
if new_bounds.0 < start || new_bounds.1 > end {
return Err(Error::Bounds {
outer_start: start,
outer_end: end,
inner_start: new_bounds.0,
inner_end: new_bounds.1,
});
}
}
Ok((license, new_bounds))
}
pub fn derive_public_key(&self, root: EccKeyPubEd25519) -> Result<EdwardsPoint> {
let mut last_round = root.0.decompress().ok_or(Error::InvalidRootKey)?;
let mut offset = 1;
trace!("Deriving public key for license");
for l in &self.blocks {
trace!(current_key = %HexSlice((&last_round.compress().0) as &[u8]));
last_round = l.derive_public_key(&self.data[offset..offset + l.len], &last_round)?;
offset += l.len;
}
trace!(
final_key = %HexSlice((&last_round.compress().0) as &[u8]),
"Finished deriving public key"
);
Ok(last_round)
}
/// Derive the private key of this license, starting with a specific block.
///
/// The keys which are stored inside the licenses from the starting block on
/// have to be private keys.
///
/// # Arguments
///
/// `starting_block`: The index of the first block for the key computation.
/// `first_key`: The starting private key (the key of a parent block or the
/// root private key).
///
/// # Panics
///
/// Panics if `starting_block` is not a valid license block index.
pub fn derive_private_key(
&self, starting_block: usize, first_key: EccKeyPrivEd25519,
) -> Result<EccKeyPrivEd25519> {
let mut res = first_key;
let mut offset = 1;
for (i, l) in self.blocks.iter().enumerate() {
if i >= starting_block {
res = l.derive_private_key(&self.data[offset..offset + l.len], &res)?;
}
offset += l.len;
}
Ok(res)
}
pub fn build<F: FnOnce(LicenseBuilder)>(mut self, f: F) -> Result<Self> {
let len = self.data.len();
f(LicenseBuilder { licenses: &mut self });
// Parse new blocks
let now = OffsetDateTime::now_utc();
let mut offset = len;
let mut bounds = self
.blocks
.last()
.map(|b| {
let b_offset = len - b.len;
let b_data = &self.data[b_offset..len];
Ok((b.get_not_valid_before(b_data)?, b.get_not_valid_after(b_data)?))
})
.transpose()?;
while self.data.len() > offset {
if self.blocks.len() >= 8 {
// Accept only 8 blocks
return Err(Error::TooManyBlocks(self.blocks.len()));
}
// Read next license
let (license, b) = Self::parse_block(&self.data[offset..], false, now, bounds)?;
offset += license.len;
bounds = Some(b);
self.blocks.push(license);
}
Ok(self)
}
pub fn is_valid(&self) -> Result<()> {
let mut offset = 1;
for b in &self.blocks {
b.is_valid(&self.data[offset..offset + b.len])?;
offset += b.len;
}
Ok(())
}
}
impl Default for Licenses {
fn default() -> Self { Self { data: vec![1], blocks: Default::default() } }
}
impl fmt::Debug for Licenses {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Licenses ")?;
let mut offset = 1;
f.debug_list()
.entries(self.blocks.iter().map(|b| {
let o = offset;
offset += b.len;
DebugLicense(b, &self.data[o..o + b.len])
}))
.finish()?;
Ok(())
}
}
impl License {
/// Parse license and return read length.
pub fn parse(data: &[u8]) -> Result<Self> {
let len = data.len();
if data.len() < BLOCK_MIN_LEN {
return Err(Error::TooShort(len, "less than minimum block length"));
}
if data[0] != 0 {
return Err(Error::WrongKeyKind(data[0]));
}
let typ_i = data[BLOCK_TYPE_OFFSET];
let typ = LicenseBlockType::from_u8(typ_i).ok_or(Error::UnknownBlockType(typ_i))?;
let data = &data[BLOCK_MIN_LEN..];
let (inner, extra_len) = match typ {
LicenseBlockType::Intermediate => {
if data.len() < 5 {
return Err(Error::TooShort(
len,
"less than minimum length of intermediate license",
));
}
// 4 byte unknown
// Issuer string
let len = if let Some(len) = data[4..].iter().position(|&b| b == 0) {
len
} else {
return Err(Error::NonterminatedString);
};
(InnerLicense::Other, 5 + len)
}
LicenseBlockType::Server => {
if data.len() < 6 {
return Err(Error::TooShort(
len,
"less than minimum length of TS3 server license",
));
}
// 1 byte server license type
// 4 byte max clients
// Issuer string
let len = if let Some(len) = data[5..].iter().position(|&b| b == 0) {
len
} else {
return Err(Error::NonterminatedString);
};
(InnerLicense::Other, 6 + len)
}
LicenseBlockType::Ts5Server => {
if data.len() < 2 {
return Err(Error::TooShort(
len,
"less than minimum length of TS5 server license",
));
}
// 1 byte server license type
// Property count and properties
let property_count = data[1];
let mut pos = 2;
let properties = (0..property_count)
.map(|_| {
let p = pos - 2;
if pos >= data.len() {
return Err(Error::TooShort(len, "missing TS5 license property"));
}
let len = usize::from(data[pos]);
pos += 1;
if pos + len >= data.len() {
return Err(Error::TooShort(len, "cut off TS5 license property"));
}
pos += len;
Ok(p)
})
.collect::<Result<_>>()?;
(InnerLicense::Ts5Server { properties }, pos)
}
LicenseBlockType::Ephemeral => (InnerLicense::Other, 0),
_ => {
return Err(Error::UnknownBlockType(typ_i));
}
};
Ok(License { len: BLOCK_MIN_LEN + extra_len, private_key: None, inner })
}
pub fn get_type(&self, data: &[u8]) -> Result<LicenseBlockType> {
let typ_i = data[BLOCK_TYPE_OFFSET];
LicenseBlockType::from_u8(typ_i).ok_or(Error::UnknownBlockType(typ_i))
}
pub fn get_public_key(&self, data: &[u8]) -> Result<EdwardsPoint> {
let k = EccKeyPubEd25519::from_bytes(data[1..33].try_into().unwrap());
k.0.decompress().ok_or(Error::InvalidPublicKey)
}
fn get_timestamp(&self, data: &[u8], block_offset: usize) -> Result<OffsetDateTime> {
let num: u32 = (&data[block_offset..]).read_be().map_err(Error::Deserialize)?;
OffsetDateTime::from_unix_timestamp(i64::from(num) + TIMESTAMP_OFFSET)
.map_err(Error::DeserializeDate)
}
pub fn get_not_valid_before(&self, data: &[u8]) -> Result<OffsetDateTime> {
self.get_timestamp(data, BLOCK_NOT_VALID_BEFORE_OFFSET)
}
pub fn get_not_valid_after(&self, data: &[u8]) -> Result<OffsetDateTime> {
self.get_timestamp(data, BLOCK_NOT_VALID_AFTER_OFFSET)
}
pub fn get_license_type(&self, data: &[u8]) -> Result<LicenseType> {
if ![LicenseBlockType::Server, LicenseBlockType::Ts5Server].contains(&self.get_type(data)?)
{
return Err(Error::NoSuchProperty("license type"));
}
LicenseType::from_u8(data[BLOCK_MIN_LEN])
.ok_or(Error::UnknownLicenseType(data[BLOCK_MIN_LEN]))
}
pub fn get_issuer<'a>(&self, data: &'a [u8]) -> Result<&'a str> {
let typ = self.get_type(data)?;
if typ == LicenseBlockType::Ts5Server {
// Search in properties
let res = self
.get_properties(data)?
.find_map(|p| if let Ok(LicenseProperty::Issuer(i)) = p { Some(i) } else { None })
.ok_or(Error::NoSuchProperty("issuer"));
return res;
}
let offset = BLOCK_MIN_LEN
+ match typ {
LicenseBlockType::Intermediate => 4,
LicenseBlockType::Website | LicenseBlockType::Code => 0,
LicenseBlockType::Server => 5,
_ => return Err(Error::NoSuchProperty("issuer")),
};
let len = match typ {
LicenseBlockType::Intermediate
| LicenseBlockType::Website
| LicenseBlockType::Code
| LicenseBlockType::Server => self.len - offset - 1,
_ => return Err(Error::NoSuchProperty("issuer")),
};
str::from_utf8(&data[offset..offset + len]).map_err(Error::DeserializeString)
}
pub fn get_max_clients(&self, data: &[u8]) -> Result<u32> {
let typ = self.get_type(data)?;
if typ == LicenseBlockType::Ts5Server {
// Search in properties
let res = self
.get_properties(data)?
.find_map(
|p| if let Ok(LicenseProperty::MaxClients(i)) = p { Some(i) } else { None },
)
.ok_or(Error::NoSuchProperty("max clients"));
return res;
}
let offset = BLOCK_MIN_LEN
+ match typ {
LicenseBlockType::Intermediate => 0,
LicenseBlockType::Server => 1,
_ => return Err(Error::NoSuchProperty("max clients")),
};
(&data[offset..offset + 4]).read_be().map_err(Error::Deserialize)
}
pub fn get_properties<'a: 'b, 'b>(
&'b self, data: &'a [u8],
) -> Result<impl Iterator<Item = Result<LicenseProperty<'a>>> + 'b> {
if let InnerLicense::Ts5Server { properties } = &self.inner {
Ok(properties.iter().map(move |p| {
let o = BLOCK_MIN_LEN + 2 + p;
let len = data[o];
let len_usize = len as usize;
let id = data[o + 1];
let typ = data[o + 2];
// Check length
if let Some(expected) = match typ {
// String, check that it is null-terminated
0 => {
if data[o + len_usize] != 0 {
return Err(Error::NonterminatedString);
}
None
}
1 | 3 => Some(4),
2 | 4 => Some(8),
_ => None,
} {
if len != expected {
return Err(Error::WrongPropertyLength { id, typ, expected, actual: len });
}
}
match id {
1 => {
if typ != 1 {
return Err(Error::WrongPropertyType { id, expected: 1, actual: typ });
}
Ok(LicenseProperty::Unknown1(
(&data[o + 3..o + 3 + 4]).read_be().map_err(Error::Deserialize)?,
))
}
2 => {
if typ != 0 {
return Err(Error::WrongPropertyType { id, expected: 0, actual: typ });
}
let s = str::from_utf8(&data[o + 3..o + len_usize])
.map_err(Error::DeserializeString)?;
Ok(LicenseProperty::Issuer(s))
}
3 => {
if typ != 1 {
return Err(Error::WrongPropertyType { id, expected: 1, actual: typ });
}
Ok(LicenseProperty::MaxClients(
(&data[o + 3..o + 3 + 4]).read_be().map_err(Error::Deserialize)?,
))
}
_ => {
Ok(LicenseProperty::Unknown { id, typ, data: &data[o + 3..o + len_usize] })
}
}
}))
} else {
Err(Error::NoSuchProperty("properties"))
}
}
/// Get the private key from the hash of this license block.
pub fn get_hash_key(&self, data: &[u8]) -> Scalar {
// Make a valid private key from the hash
let mut hash_key = Sha512::digest(&data[1..]);
hash_key[0] &= 248;
hash_key[31] &= 63;
hash_key[31] |= 64;
Scalar::from_bytes_mod_order(hash_key.as_slice()[..32].try_into().unwrap())
}
pub fn derive_public_key(
&self, data: &[u8], parent_key: &EdwardsPoint,
) -> Result<EdwardsPoint> {
let pub_key = self.get_public_key(data)?;
let hash_key = self.get_hash_key(data);
Ok(pub_key * hash_key + parent_key)
}
/// Derive the private key of this license block.
///
/// The key which is stored inside this license has to be a private key.
///
/// # Arguments
///
/// `parent_key`: The resulting private key of the previous block.
pub fn derive_private_key(
&self, data: &[u8], parent_key: &EccKeyPrivEd25519,
) -> Result<EccKeyPrivEd25519> {
let priv_key = if let Some(k) = &self.private_key {
&k.0
} else {
return Err(Error::NoPrivateKey);
};
let hash_key = self.get_hash_key(data);
Ok(EccKeyPrivEd25519(priv_key * hash_key + parent_key.0))
}
/// Check if this is a valid license.
///
/// Does some sanity checking on fields. Does not need to be called for correctness.
pub fn is_valid(&self, data: &[u8]) -> Result<()> {
self.get_public_key(data)?;
self.get_not_valid_before(data)?;
self.get_not_valid_after(data)?;
if let Err(e) = self.get_license_type(data) {
if !matches!(e, Error::NoSuchProperty(_)) {
return Err(e);
}
}
if let Err(e) = self.get_issuer(data) {
if !matches!(e, Error::NoSuchProperty(_)) {
return Err(e);
}
}
match self.get_properties(data) {
Ok(ps) => {
for p in ps {
p?;
}
}
Err(e) => {
if !matches!(e, Error::NoSuchProperty(_)) {
return Err(e);
}
}
}
Ok(())
}
}
impl fmt::Debug for DebugLicense<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let from = self
.0
.get_not_valid_before(self.1)
.ok()
.and_then(|d| d.format(&Rfc3339).ok())
.unwrap_or_else(|| "error".to_string());
let to = self
.0
.get_not_valid_after(self.1)
.ok()
.and_then(|d| d.format(&Rfc3339).ok())
.unwrap_or_else(|| "error".to_string());
let mut d = f.debug_struct("License");
let typ = self.0.get_type(self.1).unwrap();
d.field("type", &typ);
if let Some(key) = &self.0.private_key {
d.field("private_key", key);
}
d.field("not_valid_before", &from).field("not_valid_after", &to);
match typ {
LicenseBlockType::Intermediate => {
if let Ok(num) = self.0.get_max_clients(self.1) {
d.field("data", &num);
} else {
d.field("data", &"error");
}
}
LicenseBlockType::Website | LicenseBlockType::Code => {
if let Ok(issuer) = self.0.get_issuer(self.1) {
d.field("issuer", &issuer);
} else {
d.field("issuer", &"error");
}
}
LicenseBlockType::Server => {
if let Ok(license_type) = self.0.get_license_type(self.1) {
d.field("license_type", &license_type);
} else {
d.field("license_type", &"error");
}
if let Ok(issuer) = self.0.get_issuer(self.1) {
d.field("issuer", &issuer);
} else {
d.field("issuer", &"error");
}
if let Ok(max_clients) = self.0.get_max_clients(self.1) {
d.field("max_clients", &max_clients);
} else {
d.field("max_clients", &"error");
}
}
LicenseBlockType::Ts5Server => {
if let Ok(props) =
self.0.get_properties(self.1).and_then(|ps| ps.collect::<Result<Vec<_>>>())
{
d.field("properties", &props);
} else {
d.field("properties", &"error");
}
}
LicenseBlockType::Ephemeral => {}
}
d.finish()?;
Ok(())
}
}
impl LicenseBlockType {
fn min_len(&self) -> usize {
BLOCK_MIN_LEN
+ match self {
Self::Intermediate => 5,
Self::Website | Self::Code => 1,
Self::Server => 6,
Self::Ts5Server => 2,
Self::Ephemeral => 0,
}
}
}
impl<'a> LicenseBuilder<'a> {
pub fn add_block<'b>(&'b mut self, typ: LicenseBlockType) -> LicenseBlockBuilder<'a, 'b> {
let len = self.licenses.data.len();
self.licenses.data.resize(len + typ.min_len(), 0);
self.licenses.data[len + BLOCK_TYPE_OFFSET] = typ.to_u8().unwrap();
LicenseBlockBuilder { builder: self, offset: len, typ }
}
}
impl LicenseBlockBuilder<'_, '_> {
pub fn public_key(&mut self, key: &EccKeyPubEd25519) -> &mut Self {
let o = self.offset + 1;
self.builder.licenses.data[o..o + 32].copy_from_slice(&key.0.0);
self
}
fn write_timestamp(&mut self, offset: usize, time: OffsetDateTime) -> &mut Self {
let o = self.offset + offset;
Cursor::new(&mut self.builder.licenses.data[o..o + 4])
.write_be((time.unix_timestamp() - TIMESTAMP_OFFSET) as u32)
.unwrap();
self
}
pub fn not_valid_before(&mut self, time: OffsetDateTime) -> &mut Self {
self.write_timestamp(BLOCK_NOT_VALID_BEFORE_OFFSET, time)
}
pub fn not_valid_after(&mut self, time: OffsetDateTime) -> &mut Self {
self.write_timestamp(BLOCK_NOT_VALID_AFTER_OFFSET, time)
}
/// Only valid for Server and Ts5Server license types
pub fn server_license_type(&mut self, typ: LicenseType) -> &mut Self {
if ![LicenseBlockType::Server, LicenseBlockType::Ts5Server].contains(&self.typ) {
panic!(
"Setting the license type is only allowed for Server and Ts5Server license types, \
but this is a {:?}",
self.typ
);
}
self.builder.licenses.data[self.offset + BLOCK_MIN_LEN] = typ.to_u8().unwrap();
self
}
/// Add a property in a TS5 license block.
///
/// `len` is the length of the content, excluding id, type and length field.
/// Return the byte offset to where the contents of the property starts.
fn ts5_add_property(&mut self, id: u8, typ: u8, len: usize) -> usize {
let o = self.builder.licenses.data.len();
self.builder.licenses.data.resize(o + len + 3, 0);
// Increment property count
self.builder.licenses.data[self.offset + BLOCK_MIN_LEN + 1] += 1;
self.builder.licenses.data[o] = u8::try_from(len).unwrap() + 2;
self.builder.licenses.data[o + 1] = id;
self.builder.licenses.data[o + 2] = typ;
o + 3
}
/// Only valid for Intermediate, Server and Ts5Server license types
pub fn max_clients(&mut self, max_clients: u32) -> &mut Self {
let o = if self.typ == LicenseBlockType::Ts5Server {
self.ts5_add_property(3, 1, 4)
} else {
self.offset
+ BLOCK_MIN_LEN
+ match self.typ {
LicenseBlockType::Intermediate => 0,
LicenseBlockType::Server => 1,
_ => panic!(
"Setting max clients is only allowed for Intermediate, Server and \
Ts5Server license types, but this is a {:?}",
self.typ
),
}
};
Cursor::new(&mut self.builder.licenses.data[o..o + 4]).write_be(max_clients).unwrap();
self
}
/// Only valid for Intermediate, Server and Ts5Server license types
pub fn issuer(&mut self, issuer: &str) -> &mut Self {
// Check that the issuer does not contain null bytes
assert!(
!issuer.contains('\0'),
"The issuer is written as a null-terminated string so it cannot contain null bytes"
);
let o = if self.typ == LicenseBlockType::Ts5Server {
self.ts5_add_property(2, 0, issuer.len() + 1)
} else {
if ![LicenseBlockType::Intermediate, LicenseBlockType::Server].contains(&self.typ) {
panic!(
"Setting the issuer is only allowed for Intermediate, Server and Ts5Server \
license types, but this is a {:?}",
self.typ
);
}
// Check that no issuer was written so far
assert!(
self.builder.licenses.data.len() - self.offset == self.typ.min_len(),
"Only a single issuer can be written into a license block"
);
let o = self.builder.licenses.data.len();
self.builder.licenses.data.resize(o + issuer.len(), 0);
o - 1
};
self.builder.licenses.data[o..o + issuer.len()].copy_from_slice(issuer.as_bytes());
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use base64::prelude::*;
#[test]
fn parse_standard_license() {
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0\
Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAACiIBip9hQaK6P3QhwOJs/BkPn0i\
oyIDPaNgzJ6M8x0kiAJf4hxCYAxMQ==").unwrap()).unwrap();
}
#[test]
fn parse_standard_license_expired() {
assert!(Licenses::parse(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0\
Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAACiIBip9hQaK6P3QhwOJs/BkPn0i\
oyIDPaNgzJ6M8x0kiAJf4hxCYAxMQ==").unwrap()).is_err());
}
#[test]
fn parse_aal_license() {
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQCvbHFTQDY/terPeilrp/ECU9xCH5U3xC92lY\
TNaY/0KQAJFueAazbsgAAAACVUZWFtU3BlYWsgU3lzdGVtcyBHbWJIAABhl9gwla/UJ\
p2Eszst9TRVXO/PeE6a6d+CTI6Pg7OEVgAJc5CrL4Nh8gAAACRUZWFtU3BlYWsgc3lz\
dGVtcyBHbWJIAACvTQIgpv6zmLZq3znh7ygmOSokGFkFjz4bTigrOnetrgIJdIIACdS\
/gAYAAAAAU29zc2VuU3lzdGVtcy5iaWQAADY7+uV1CQ1niOvYSdGzsu83kPTNWijovr\
3B78eHGeePIAm98vQJvpu0").unwrap()).unwrap();
}
#[test]
fn parse_ts5_server_license_long() {
// Slightly older format having a block with a Ts5 license block in it
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQDVsMGbcrMmGif1vSXPWWXNW2CB5\
Fe9oZ/2uxP29j1EXQAQSfiAazbsgAAAASVUZWFtU3BlYWsgU3lzdGVtcyBHbWJIAAALB6Qfbe\
JyN+9foJhe+/KPFwyU+i++4MAA0q1/WCnizwARRuEPN1aeBQAAASBUZWFtU3BlYWsgc3lzdGV\
tcyBHbWJIAADrhbI5gUR3thsS7FqKV5P5h7djnwMSJfF2vi58lm1VcwgRUFMAE0P7gAUCGQIA\
VGVhbVNwZWFrIFN5c3RlbXMgR21iSAAGAwEAAAAFAAf2KhQ7WLjOvwwY0Bi7LxAcWmQeT+LQt\
uaOzjhYoA+YIBGNq1kRjlQZ").unwrap()).unwrap();
}
#[test]
fn parse_ts5_server_license_long2() {
// Also slightly older, has 3 properties
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQDVsMGbcrMmGif1vSXPWWXNW2CB5\
Fe9oZ/2uxP29j1EXQAQSfiAazbsgAAAASVUZWFtU3BlYWsgU3lzdGVtcyBHbWJIAAAtXG5p2n\
iXlDfpVAGuD88w8hetKYL4vqHRkB5xB8ASRwAR2t/MN+ttjAAAASBUZWFtU3BlYWsgc3lzdGV\
tcyBHbWJIAAAdZYGtwkeZFhzqnoV1uk+Tcphe8GgcqiPVtELF9y4wOAgR4qmAF4jnAAkDGQIA\
VGVhbVNwZWFrIFN5c3RlbXMgR21iSAAGAwEAAAAFBgEBAAGGoADzyFvD+9G6uhIxmh0jK+Uo8\
z8fYGJVH81vWFULDS0l8yATKe4cEyqW3A==").unwrap()).unwrap();
}
#[test]
fn parse_ts5_server_license_single_block_with_issuer() {
Licenses::parse_ignore_expired(
BASE64_STANDARD
.decode(
"AQBgjAAqtcBUrw5futTtkl3+EM3OW4Lal6OTPlwuv4xV/\
gIRFlEAG0NlAAcAAAAgQW5vbnltb3VzAACKNY+/\
9qCbonCSxG18vBb7y7zPIgDdjTmcZoAHHclnJSATPa69Ez5XfQ==",
)
.unwrap(),
)
.unwrap();
}
#[test]
fn parse_ts5_server_license_single_block() {
// Only a single server block and the ephemeral block
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQAuio9ZxThXKE+hmzQyzBRedysp9\
79JBTv2xP3s2oCkiAgQI70AE+YkAAcBBgMBAAAABQBoazM313063zaipPTH06zrXc91ch3huB\
YrUET9sEbz1CATKgK8EyqrfA==").unwrap()).unwrap();
}
#[test]
fn derive_public_key() {
let licenses = Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAAC4R+5mos+UQ/KCbkpQLMI5WRp4wkQu8e5PZY4zU+/FlyAJwaE8CcJJ/A==").unwrap()).unwrap();
let derived_key =
licenses.derive_public_key(EccKeyPubEd25519::from_bytes(crate::ROOT_KEY)).unwrap();
let expected_key = [
0x40, 0xe9, 0x50, 0xc4, 0x61, 0xba, 0x18, 0x3a, 0x1e, 0xb7, 0xcb, 0xb1, 0x9a, 0xc3,
0xd8, 0xd9, 0xc4, 0xd5, 0x24, 0xdb, 0x38, 0xf7, 0x2d, 0x3d, 0x66, 0x75, 0x77, 0x2a,
0xc5, 0x9c, 0xc5, 0xc6,
];
let derived_key = derived_key.compress().0;
assert_eq!(derived_key, expected_key);
}
}
+111
View File
@@ -0,0 +1,111 @@
use std::fmt::Debug;
use std::str;
use tracing::{debug, debug_span, Span};
use tsproto_packets::packets::{InUdpPacket, OutUdpPacket, PacketType};
use tsproto_packets::HexSlice;
use crate::connection::{Connection, Event};
fn prepare_span(is_client: bool, incoming: bool) -> Span {
let dir = if incoming {
if !cfg!(windows) { "\x1b[1;32mIN\x1b[0m" } else { "IN" }
} else if !cfg!(windows) {
"\x1b[1;31mOUT\x1b[0m"
} else {
"OUT"
};
let to = if is_client { "S" } else { "C" };
debug_span!("packet", to, %dir)
}
pub fn log_udp_packet(is_client: bool, incoming: bool, packet: &InUdpPacket) {
let _span = prepare_span(is_client, incoming).entered();
debug!(header = ?packet.0.header(), content = %HexSlice(packet.0.content()), "UdpPacket");
}
pub fn log_out_udp_packet(is_client: bool, incoming: bool, packet: &OutUdpPacket) {
let _span = prepare_span(is_client, incoming).entered();
debug!(
generation = packet.generation_id(),
header = ?packet.data().header(),
content = %HexSlice(packet.data().content()),
"UdpPacket"
);
}
pub fn log_packet<P: Debug>(is_client: bool, incoming: bool, packet: &P) {
// packet.header.c_id is not set for newly created packets so we cannot
// detect if a packet is incoming or not.
let _span = prepare_span(is_client, incoming).entered();
debug!(content = ?packet, "Packet");
}
pub fn log_command(is_client: bool, incoming: bool, p_type: PacketType, cmd: &str) {
// packet.header.c_id is not set for newly created packets so we cannot
// detect if a packet is incoming or not.
let _span = prepare_span(is_client, incoming).entered();
if p_type == PacketType::Command {
debug!(content = cmd, "Command");
} else {
debug!(content = cmd, "CommandLow");
}
}
/// Print the content of all packets
///
/// 0 - Print commands
/// 1 - Print packets
/// 2 - Print udp packets
pub fn add_logger_with_verbosity(verbosity: u8, con: &mut Connection) {
let log_commands = verbosity > 0;
let log_packets = verbosity > 1;
let log_udp_packets = verbosity > 2;
add_logger(log_commands, log_packets, log_udp_packets, con);
}
pub fn add_logger(
log_commands: bool, log_packets: bool, log_udp_packets: bool, con: &mut Connection,
) {
if log_commands || log_packets || log_udp_packets {
let is_client = con.is_client;
let listener = Box::new(move |event: &Event| match event {
Event::ReceiveUdpPacket(packet) => {
if log_udp_packets {
log_udp_packet(is_client, true, packet);
}
}
Event::ReceivePacket(packet) => {
if log_packets {
log_packet(is_client, true, packet);
} else if log_commands {
let p_type = packet.header().packet_type();
if p_type.is_command() {
if let Ok(s) = str::from_utf8(packet.content()) {
log_command(is_client, true, p_type, s);
}
}
}
}
Event::SendUdpPacket(packet) => {
if log_udp_packets {
log_out_udp_packet(is_client, false, packet);
}
}
Event::SendPacket(packet) => {
if log_packets {
log_packet(is_client, false, &packet.packet());
} else if log_commands {
let p_type = packet.header().packet_type();
if p_type.is_command() {
if let Ok(s) = str::from_utf8(packet.content()) {
log_command(is_client, false, p_type, s);
}
}
}
}
});
con.event_listeners.push(listener);
}
}
+461
View File
@@ -0,0 +1,461 @@
use std::io::Cursor;
use std::task::Context;
use num_traits::ToPrimitive;
use omnom::WriteExt;
use tracing::warn;
use tsproto_packets::packets::*;
use crate::algorithms as algs;
use crate::connection::{Connection, Event, StreamItem};
use crate::resend::{PartialPacketId, Resender};
use crate::{Error, Result, MAX_FRAGMENTS_LENGTH, MAX_QUEUE_LEN};
/// Encodes outgoing packets.
///
/// This part does the compression, encryption and fragmentation.
#[derive(Clone, Debug, Default)]
pub struct PacketCodec {
/// The next packet id that should be sent.
///
/// This list is indexed by the `PacketType`, `PacketType::Init` is an
/// invalid index.
pub outgoing_p_ids: [PartialPacketId; 8],
/// Used for incoming out-of-order packets.
///
/// Only used for `Command` and `CommandLow` packets.
pub receive_queue: [Vec<Vec<u8>>; 2],
/// Used for incoming fragmented packets.
///
/// Contains the accumulated data from fragmented packets, the header of the
/// first packet is at the beginning, all other headers are stripped away.
/// Only used for `Command` and `CommandLow` packets.
pub fragmented_queue: [Option<Vec<u8>>; 2],
/// The next packet id that is expected.
///
/// Works like the `outgoing_p_ids`.
pub incoming_p_ids: [PartialPacketId; 8],
}
impl PacketCodec {
/// Handle a packet for a specific connection.
///
/// This part does the defragmentation, decryption and decompression.
pub fn handle_udp_packet(
con: &mut Connection, cx: &mut Context, mut packet_data: Vec<u8>,
) -> Result<()> {
let mut ack = false;
let dir = if con.is_client { Direction::S2C } else { Direction::C2S };
let packet = InPacket::new(dir, &packet_data);
let p_type = packet.header().packet_type();
let type_i = p_type.to_usize().unwrap();
let id = packet.header().packet_id();
let (in_recv_win, gen_id, cur_next, limit) = con.in_receive_window(p_type, id);
con.resender.handle_loss_incoming(&packet, in_recv_win, cur_next);
if let Some(params) = &con.params {
if p_type == PacketType::Init {
con.stream_items.push_back(StreamItem::Error(Error::UnexpectedInitPacket));
return Ok(());
}
if !con.is_client {
let c_id = packet.header().client_id().unwrap();
// Accept any client id for the first few acks
let is_first_ack = gen_id == 0 && id <= 3 && p_type == PacketType::Ack;
if c_id != params.c_id && !is_first_ack {
con.stream_items.push_back(StreamItem::Error(Error::WrongClientId(c_id)));
return Ok(());
}
}
}
// Ignore range for acks and audio packets
if [PacketType::Ack, PacketType::AckLow, PacketType::Voice, PacketType::VoiceWhisper]
.contains(&p_type)
|| in_recv_win
{
if !packet.header().flags().contains(Flags::UNENCRYPTED) {
if p_type == PacketType::Ack && id == 1 && con.is_client {
// This is the ack packet for the clientinit, we take the
// initserver as ack instead.
return Ok(());
}
// If it is the first ack packet of a client, try to fake
// decrypt it.
let new_content = if (p_type == PacketType::Ack && id <= 1 && con.is_client)
|| con.params.is_none()
{
match algs::decrypt_fake(&packet).or_else(|_| {
if let Some(params) = &mut con.params {
// Decrypt the packet
algs::decrypt(&packet, gen_id, &params.shared_iv, &mut params.key_cache)
} else {
// Failed to fake decrypt the packet
Err(Error::WrongMac { p_type, generation_id: gen_id, packet_id: id })
}
}) {
Ok(r) => r,
Err(e) => {
con.stream_items.push_back(StreamItem::Error(e));
return Ok(());
}
}
} else if let Some(params) = &mut con.params {
// Decrypt the packet
match algs::decrypt(&packet, gen_id, &params.shared_iv, &mut params.key_cache) {
Ok(r) => r,
Err(e) => {
con.stream_items.push_back(StreamItem::Error(e));
return Ok(());
}
}
} else {
// Failed to fake decrypt the packet
con.stream_items.push_back(StreamItem::Error(Error::WrongMac {
p_type,
generation_id: gen_id,
packet_id: id,
}));
return Ok(());
};
let start = packet.header().data().len();
packet_data[start..].copy_from_slice(&new_content);
} else if algs::must_encrypt(p_type) {
// Check if it is ok for the packet to be unencrypted
con.stream_items.push_back(StreamItem::Error(Error::UnallowedUnencryptedPacket));
return Ok(());
}
let packet = InPacket::new(dir, &packet_data);
match p_type {
PacketType::Command | PacketType::CommandLow => {
ack = true;
let commands = Self::handle_command_packet(con, packet_data)?;
// Be careful with command packets, they are guaranteed to
// be in the right order now.
for c in commands {
// Send again
let packet = InPacket::new(dir, &c);
let event = Event::ReceivePacket(&packet);
con.send_event(&event);
let item = match InCommandBuf::try_new(dir, c) {
Ok(c) => {
// initivexpand2 is the ack for the last init packet
if con.is_client
&& c.data().packet().content().starts_with(b"initivexpand2 ")
{
Resender::ack_packet(con, cx, PacketType::Init, 4);
} else if con.is_client
&& c.data().packet().content().starts_with(b"initserver ")
{
// initserver acks clientinit
Resender::ack_packet(con, cx, PacketType::Command, 2);
} else if !con.is_client
&& c.data().packet().content().starts_with(b"clientek ")
{
// clientek acks initivexpand2
Resender::ack_packet(con, cx, PacketType::Command, 0);
}
StreamItem::Command(c)
}
Err(e) => return Err(Error::PacketParse("command", e)),
};
con.stream_items.push_back(item);
}
}
_ => {
if p_type == PacketType::Ping {
ack = true;
}
// Update packet ids
let in_ids = &mut con.codec.incoming_p_ids;
if p_type != PacketType::Init {
let (id, next_gen) = id.overflowing_add(1);
let generation_id = if next_gen { gen_id + 1 } else { gen_id };
in_ids[type_i] = PartialPacketId { generation_id, packet_id: id };
}
match packet.ack_packet() {
Ok(Some(ack_id)) => {
// Remove command packet from send queue if the fitting ack is received.
let p_type = if p_type == PacketType::Ack {
PacketType::Command
} else if p_type == PacketType::AckLow {
PacketType::CommandLow
} else if p_type == PacketType::Pong {
PacketType::Ping
} else {
p_type
};
Resender::ack_packet(con, cx, p_type, ack_id);
}
Ok(None) => {}
Err(e) => {
con.stream_items.push_back(StreamItem::Error(Error::CreateAck(e)));
return Ok(());
}
}
// Send event after handling acks
let event = Event::ReceivePacket(&packet);
con.send_event(&event);
if p_type.is_voice() {
con.stream_items.push_back(match InAudioBuf::try_new(dir, packet_data) {
Ok(r) => StreamItem::Audio(r),
Err(e) => StreamItem::Error(Error::PacketParse("audio", e)),
});
} else if p_type == PacketType::Init {
con.stream_items.push_back(if con.is_client {
match InS2CInitBuf::try_new(dir, packet_data) {
Ok(r) => StreamItem::S2CInit(r),
Err(e) => StreamItem::Error(Error::PacketParse("s2cinit", e)),
}
} else {
match InC2SInitBuf::try_new(dir, packet_data) {
Ok(r) => StreamItem::C2SInit(r),
Err(e) => StreamItem::Error(Error::PacketParse("c2sinit", e)),
}
});
}
}
}
} else {
// Send an ack for the case when it was lost
if p_type == PacketType::Command || p_type == PacketType::CommandLow {
ack = true;
con.resender.handle_loss_resend_ack();
}
con.stream_items.push_back(StreamItem::Error(Error::NotInReceiveWindow {
id,
next: cur_next,
limit,
p_type,
}));
}
// Send ack
if ack {
con.send_ack_packet(cx, OutAck::new(dir.reverse(), p_type, id))?;
}
Ok(())
}
/// Handle `Command` and `CommandLow` packets.
///
/// They have to be handled in the right order.
fn handle_command_packet(
con: &mut Connection, mut packet_data: Vec<u8>,
) -> Result<Vec<Vec<u8>>> {
let dir = if con.is_client { Direction::S2C } else { Direction::C2S };
let mut packet = InPacket::new(dir, &packet_data);
let header = packet.header();
let p_type = header.packet_type();
let mut id = header.packet_id();
let type_i = p_type.to_usize().unwrap();
let cmd_i = if p_type == PacketType::Command { 0 } else { 1 };
let r_queue = &mut con.codec.receive_queue[cmd_i];
let frag_queue = &mut con.codec.fragmented_queue[cmd_i];
let in_ids = &mut con.codec.incoming_p_ids[type_i];
let cur_next = in_ids.packet_id;
if cur_next == id {
// In order
let mut packets = Vec::new();
loop {
// Update next packet id
*in_ids = *in_ids + 1;
let flags = packet.header().flags();
let res_packet = if flags.contains(Flags::FRAGMENTED) {
if let Some(mut frag_queue) = frag_queue.take() {
// Last fragmented packet
frag_queue.extend_from_slice(packet.content());
let header = InPacket::new(dir, &frag_queue);
// Decompress
if header.header().flags().contains(Flags::COMPRESSED) {
let decompressed = quicklz::decompress(
&mut Cursor::new(header.content()),
crate::MAX_DECOMPRESSED_SIZE,
)
.map_err(Error::DecompressPacket)?;
let start = header.header().data().len();
frag_queue.truncate(start);
frag_queue.extend_from_slice(&decompressed);
}
Some(frag_queue)
} else {
// Enqueue
*frag_queue = Some(packet_data);
None
}
} else if let Some(frag_queue) = frag_queue {
// The packet is fragmented
if frag_queue.len() < MAX_FRAGMENTS_LENGTH {
frag_queue.extend_from_slice(packet.content());
None
} else {
return Err(Error::MaxLengthExceeded("fragment queue"));
}
} else {
// Decompress
if flags.contains(Flags::COMPRESSED) {
let decompressed = quicklz::decompress(
&mut Cursor::new(packet.content()),
crate::MAX_DECOMPRESSED_SIZE,
)
.map_err(Error::DecompressPacket)?;
let start = packet.header().data().len();
packet_data.truncate(start);
packet_data.extend_from_slice(&decompressed);
};
Some(packet_data)
};
if let Some(p) = res_packet {
packets.push(p);
}
// Check if there are following packets in the receive queue.
id = id.wrapping_add(1);
if let Some(pos) =
r_queue.iter().position(|p| InHeader::new(dir, p).packet_id() == id)
{
packet_data = r_queue.remove(pos);
packet = InPacket::new(dir, &packet_data);
} else {
break;
}
}
Ok(packets)
} else {
// Out of order
warn!(got = id, expected = cur_next, "Out of order command packet");
let (limit, next_gen) = cur_next.overflowing_add(MAX_QUEUE_LEN);
if (!next_gen && id >= cur_next && id < limit)
|| (next_gen && (id >= cur_next || id < limit))
{
r_queue.push(packet_data);
Ok(vec![])
} else {
Err(Error::MaxLengthExceeded("command queue"))
}
}
}
pub fn encode_packet(con: &mut Connection, mut packet: OutPacket) -> Result<Vec<OutUdpPacket>> {
let p_type = packet.header().packet_type();
let type_i = p_type.to_usize().unwrap();
// TODO Needed, commands should set their own flag?
if (p_type == PacketType::Command || p_type == PacketType::CommandLow) && con.is_client {
// Set newprotocol flag
packet.flags(packet.header().flags() | Flags::NEWPROTOCOL);
}
let p_id = if p_type == PacketType::Init {
PartialPacketId { generation_id: 0, packet_id: 0 }
} else {
con.codec.outgoing_p_ids[type_i]
};
// We fake encrypt the first command packet of the server (id 0) and the
// first command packet of the client (id 1, clientek).
let mut fake_encrypt = p_type == PacketType::Command
&& p_id.generation_id == 0
&& ((!con.is_client && p_id.packet_id == 0)
|| (con.is_client && p_id.packet_id == 1 && {
// Test if it is a clientek packet
packet.content().starts_with(b"clientek")
}));
// Also fake encrypt the first ack of the client, which is the response
// for the initivexpand2 packet.
fake_encrypt |= con.is_client
&& p_type == PacketType::Ack
&& p_id.generation_id == 0
&& p_id.packet_id == 0;
// Get values from parameters
let should_encrypt;
let c_id;
if let Some(params) = con.params.as_mut() {
should_encrypt = algs::should_encrypt(p_type, params.voice_encryption);
c_id = params.c_id;
} else {
should_encrypt = algs::should_encrypt(p_type, false);
if should_encrypt {
fake_encrypt = true;
}
c_id = 0;
}
// Client id for clients
if con.is_client {
packet.client_id(c_id);
}
if !should_encrypt && !fake_encrypt {
packet.flags(packet.header().flags() | Flags::UNENCRYPTED);
if let Some(params) = con.params.as_mut() {
packet.mac().copy_from_slice(&params.shared_mac);
}
}
// Compress and split packet
let packets = if p_type == PacketType::Command || p_type == PacketType::CommandLow {
algs::compress_and_split(con.is_client, packet)
} else {
// Set the inner packet id for voice packets
if con.is_client && (p_type == PacketType::Voice || p_type == PacketType::VoiceWhisper)
{
(&mut packet.content_mut()[..2])
.write_be(con.codec.outgoing_p_ids[type_i].packet_id)
.unwrap();
}
vec![packet]
};
let packets = packets
.into_iter()
.map(|mut packet| -> Result<_> {
// Get packet id
let p_id = if p_type == PacketType::Init {
PartialPacketId { generation_id: 0, packet_id: 0 }
} else {
packet.packet_id(con.codec.outgoing_p_ids[type_i].packet_id);
con.codec.outgoing_p_ids[type_i]
};
// Encrypt if necessary
if fake_encrypt {
algs::encrypt_fake(&mut packet)?;
} else if should_encrypt {
// The params are set
let params = con.params.as_mut().unwrap();
algs::encrypt(
&mut packet,
p_id.generation_id,
&params.shared_iv,
&mut params.key_cache,
)?;
}
// Increment outgoing_p_ids
let p_id = p_id + 1;
if p_type != PacketType::Init {
con.codec.outgoing_p_ids[type_i] = p_id;
}
Ok(OutUdpPacket::new(p_id.generation_id, packet))
})
.collect::<Result<Vec<_>>>()?;
Ok(packets)
}
}
File diff suppressed because it is too large. Load diff
+47
View File
@@ -0,0 +1,47 @@
use std::net::IpAddr;
use crate::{Error, Result};
/// Try to approximate the not stabilized ip.is_global().
pub fn is_global_ip(ip: &IpAddr) -> bool {
if !ip.is_unspecified() && !ip.is_loopback() && !ip.is_multicast() {
match *ip {
IpAddr::V4(ref ip) => !ip.is_broadcast() && !ip.is_link_local() && !ip.is_private(),
IpAddr::V6(_) => true,
}
} else {
false
}
}
pub fn read_hex(s: &str) -> Result<Vec<u8>> {
// Detect hex format
if s.chars().nth(2) == Some(':') {
// Wireshark
Ok(s.split(':')
.map(|s| u8::from_str_radix(s, 16))
.collect::<::std::result::Result<Vec<_>, _>>()
.map_err(Error::InvalidHex)?)
} else if s.chars().nth(2) == Some(' ') {
// Wireshark
Ok(s.split(' ')
.map(|s| u8::from_str_radix(s, 16))
.collect::<::std::result::Result<Vec<_>, _>>()
.map_err(Error::InvalidHex)?)
} else if s.starts_with("0x") {
let s: String = s.chars().filter(|c| !c.is_whitespace()).collect();
// Own dumps
Ok(s[2..]
.split(',')
.map(|s| u8::from_str_radix(s.trim_start_matches("0x"), 16))
.collect::<::std::result::Result<Vec<_>, _>>()
.map_err(Error::InvalidHex)?)
} else {
let s: String = s.chars().filter(|c| !c.is_whitespace()).collect();
Ok(s.as_bytes()
.chunks(2)
.map(|s| u8::from_str_radix(::std::str::from_utf8(s).unwrap(), 16))
.collect::<::std::result::Result<Vec<_>, _>>()
.map_err(Error::InvalidHex)?)
}
}