myTS avatar, badges and User Tag from a saved session; banners; gateway logs and speed
Own account on TeamSpeak 6 servers:
- With only a saved session, the account's avatar and its certificate come
from myTeamSpeak's avatar service (requestContactsAvatar for the own myTS
ID), the signed badges from getSignedBadges and the User Tag's token from
/tschat requestSignedAllowedIdentifierList; no password sign-in needed.
- tsproto::myts::Certificate checks a certificate chain as the server does
(block types 4-7, leaf type 6, validity, key from the root, cofactorless
Ed25519); each part is sent with a certificate that verifies it, in
separate updatemytsdata commands when they differ, and cleared on sign-out.
- client_user_tag is set as the official client sets it
({"myts_token","tag","updated"}) on TeamSpeak 6 servers, after a
self-check of the token; cleared on sign-out or an account change.
- Settings -> My Account shows the User Tag and lets the user choose up to
three badges to show. The log says what the server published.
Banners:
- The URL (without query) is logged on the first failure; stalls, connect
failures and missing answers are named; 400/404/410 are retried after
15 minutes, then hourly; 429/503 honour Retry-After.
- Cached pictures are revalidated (ETag, Last-Modified); at most 6
downloads per host; a User-Agent with the app version.
- The desktop portal's proxy (Linux) and the system proxy (Windows, macOS)
are used, SOCKS included; redirects are followed hop by hop.
Gateway, client side:
- Only a refused login stops observing; retries after 1, 2, 5, 10, 20, then
30 s with jitter, at once when voice connects; a 30 s keepalive.
- Discovery asks DNS and the well-known endpoints at once; observing is not
restarted when the found list still holds the gateway in use.
- Info logs for discovery, attempts (with the stage that hung), connections,
losses and the first presence.
tsgw:
- Logging setup (log.level, log.file with size rotation, colour only on a
terminal) and lifecycle logs: startup summary, the address the server
sees for queries, WebSocket connections, logins, refusals, slow requests,
ServerQuery failures, relays and the observer.
- The lookup query connection reconnects after a TeamSpeak restart; query
connects time out after 10 s; a silent server cannot wedge a connection;
SIGTERM, startup while TeamSpeak is down and /health are handled.
- TCP_QUICKACK and one write per line: ~45 ms -> <2 ms per SSH command.
- One flood guard shared by all query connections (9 per 3 s, SSH auth
counted, every connection holds on a 524).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
This commit is contained in:
1 parent
1c2d5efd3a
commit
79a12654c8
56 files changed
+7405
-672
No files matched your search
@@ -129,3 +129,17 @@ against or offered back to upstream.
|
||||
Tests cover an independent signature vector, persistence validation/redaction,
|
||||
wire field names, clearing and reconnect snapshot replacement. The account
|
||||
UUID and the ordinary server identity remain separate.
|
||||
15. **myTeamSpeak presentation, TeamSpeak 6** (`tsproto/src/license.rs`,
|
||||
`tsproto/src/myts.rs`, `tsclientlib/src/myts.rs`, `tsclientlib/src/lib.rs`,
|
||||
`tsproto-packets/src/packets.rs`, `tsproto-structs/declarations/Book.toml`).
|
||||
License block types 4–7 (Token, License_Sign, MyTsId_Sign, Updater), which
|
||||
carry nothing after the header. `myts::Certificate` checks a myTeamSpeak
|
||||
certificate chain as a TeamSpeak 6 server does: leaf type, validity window,
|
||||
key derived from a given root, cofactorless Ed25519 with a reduced S;
|
||||
`Identity::id_bytes` and `public_signature_certificate`. `MytsData` holds the
|
||||
avatar and the badges, each with the certificate that verifies it, and the
|
||||
User Tag; `MytsData::updates` builds `updatemytsdata` (split by certificate,
|
||||
bare parameters to clear) and `clientupdate client_user_tag`, which
|
||||
`Connection::send_myts_update` and `send_user_tag` send. The escaped writer
|
||||
also escapes `\a` and `\b`, as TeamSpeak does for binary values. Book:
|
||||
`Client::my_team_speak_avatar`, `my_team_speak_id` and `signed_badges`.
|
||||
@@ -61,7 +61,7 @@ pub use ts_bookkeeping::messages::s2c::InMessage;
|
||||
pub use ts_bookkeeping::*;
|
||||
pub use tsproto::resend::{ConnectionStats, PacketStat};
|
||||
pub use tsproto::Identity;
|
||||
pub use myts::MytsData;
|
||||
pub use myts::{MytsData, MytsUpdate, Signed, UserTag};
|
||||
pub use tsproto_types::errors::Error as TsError;
|
||||
|
||||
/// Wait this time for initserver, in seconds.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Voelin patch: connection-bound myTeamSpeak proof and live account changes.
|
||||
|
||||
use base64::prelude::*;
|
||||
use tsproto::myts::Identity;
|
||||
use tsproto_packets::packets::{Direction, Flags, OutCommand, PacketType};
|
||||
|
||||
@@ -14,36 +15,182 @@ impl ConnectOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a voice server is shown of the myTeamSpeak account (TeamSpeak 6),
|
||||
/// as myTeamSpeak signed it: the account's certificate and its avatar
|
||||
/// (`LoginSession.user_avatar` as it came). The server shows the avatar to
|
||||
/// everyone (`client_myteamspeak_avatar`).
|
||||
/// What a voice server is shown of the myTeamSpeak account (TeamSpeak 6)
|
||||
/// besides its myTS ID, as myTeamSpeak signed it for that ID: its avatar,
|
||||
/// its badges and its User Tag. The server checks the avatar and the badges
|
||||
/// with the one certificate of each `updatemytsdata` and shows nothing of
|
||||
/// what does not verify, so each comes with the certificate that verifies
|
||||
/// it. Viewers check the User Tag's token themselves.
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct MytsData {
|
||||
/// The raw myTS ID all of it is signed for: shown only on a connection
|
||||
/// that presents it.
|
||||
pub myts_id: Vec<u8>,
|
||||
/// An `AvatarData` as it came (`client_myteamspeak_avatar`).
|
||||
pub avatar: Signed,
|
||||
/// A `UserBadgesSignedList`, the badges chosen to show, in order
|
||||
/// (`client_signed_badges`).
|
||||
pub badges: Signed,
|
||||
/// The ids of those badges, as in the list: the server publishes the
|
||||
/// ones that verify.
|
||||
pub badge_ids: Vec<String>,
|
||||
pub user_tag: Option<UserTag>,
|
||||
}
|
||||
|
||||
/// Something signed and the certificate that verifies it; empty: nothing.
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct Signed {
|
||||
pub certificate: Vec<u8>,
|
||||
/// Empty: none.
|
||||
pub avatar: Vec<u8>,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// The User Tag (`client_user_tag`): the account's primary chat identifier
|
||||
/// and the token that proves it (a `MatrixIdentifierToken` as it came).
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct UserTag {
|
||||
pub tag: String,
|
||||
pub token: Vec<u8>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for MytsData {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("MytsData")
|
||||
.field("certificate", &self.certificate.len())
|
||||
.field("avatar", &self.avatar.len())
|
||||
.field("avatar", &self.avatar.data.len())
|
||||
.field("badges", &self.badge_ids)
|
||||
.field("user_tag", &self.user_tag.as_ref().map(|t| &t.tag))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Signed {
|
||||
pub fn is_empty(&self) -> bool { self.data.is_empty() }
|
||||
}
|
||||
|
||||
impl UserTag {
|
||||
/// `client_user_tag` as the official client sets it: compact JSON with
|
||||
/// the token (standard base64), the tag and when it was set (`updated`,
|
||||
/// milliseconds since 1970), in this order.
|
||||
pub fn value(&self, updated_ms: i64) -> String {
|
||||
let mut tag = String::with_capacity(self.tag.len());
|
||||
for c in self.tag.chars() {
|
||||
match c {
|
||||
'"' => tag.push_str("\\\""),
|
||||
'\\' => tag.push_str("\\\\"),
|
||||
'\n' => tag.push_str("\\n"),
|
||||
'\r' => tag.push_str("\\r"),
|
||||
'\t' => tag.push_str("\\t"),
|
||||
'\u{8}' => tag.push_str("\\b"),
|
||||
'\u{c}' => tag.push_str("\\f"),
|
||||
c if u32::from(c) < 0x20 => tag.push_str(&format!("\\u{:04x}", u32::from(c))),
|
||||
c => tag.push(c),
|
||||
}
|
||||
}
|
||||
format!(
|
||||
"{{\"myts_token\":\"{}\",\"tag\":\"{}\",\"updated\":{}}}",
|
||||
BASE64_STANDARD.encode(&self.token),
|
||||
tag,
|
||||
updated_ms
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// One `updatemytsdata`: a value is shown (checked with `certificate`), an
|
||||
/// empty one clears what is shown, `None` leaves it as it is.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct MytsUpdate {
|
||||
pub certificate: Vec<u8>,
|
||||
pub badges: Option<Vec<u8>>,
|
||||
pub avatar: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// What to do about one part of what is shown.
|
||||
enum Part<'a> {
|
||||
Keep,
|
||||
Show(&'a Signed),
|
||||
Clear,
|
||||
}
|
||||
|
||||
fn part<'a>(wanted: &'a Signed, shown: &Signed, again: bool) -> Part<'a> {
|
||||
if wanted.is_empty() {
|
||||
if shown.is_empty() { Part::Keep } else { Part::Clear }
|
||||
} else if again || wanted != shown {
|
||||
Part::Show(wanted)
|
||||
} else {
|
||||
Part::Keep
|
||||
}
|
||||
}
|
||||
|
||||
impl MytsData {
|
||||
/// The `updatemytsdata` commands that make a server that shows `shown`
|
||||
/// show `self`. `again`: everything once more, after a new account proof
|
||||
/// (`updatemytsid`), which the server does not check them for again.
|
||||
/// The avatar and the badges go together when one certificate verifies
|
||||
/// both (certificate, badges, avatar, as the official client sends
|
||||
/// them), apart otherwise; clearing needs no certificate.
|
||||
pub fn updates(&self, shown: &MytsData, again: bool) -> Vec<MytsUpdate> {
|
||||
let avatar = part(&self.avatar, &shown.avatar, again);
|
||||
let badges = part(&self.badges, &shown.badges, again);
|
||||
let mut updates = Vec::new();
|
||||
match (&badges, &avatar) {
|
||||
(Part::Show(badges), Part::Show(avatar)) if badges.certificate == avatar.certificate => {
|
||||
updates.push(MytsUpdate {
|
||||
certificate: avatar.certificate.clone(),
|
||||
badges: Some(badges.data.clone()),
|
||||
avatar: Some(avatar.data.clone()),
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
if let Part::Show(avatar) = avatar {
|
||||
updates.push(MytsUpdate {
|
||||
certificate: avatar.certificate.clone(),
|
||||
avatar: Some(avatar.data.clone()),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
if let Part::Show(badges) = badges {
|
||||
updates.push(MytsUpdate {
|
||||
certificate: badges.certificate.clone(),
|
||||
badges: Some(badges.data.clone()),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let clear_badges = matches!(badges, Part::Clear);
|
||||
let clear_avatar = matches!(avatar, Part::Clear);
|
||||
if clear_badges || clear_avatar {
|
||||
updates.push(MytsUpdate {
|
||||
certificate: Vec::new(),
|
||||
badges: if clear_badges { Some(Vec::new()) } else { None },
|
||||
avatar: if clear_avatar { Some(Vec::new()) } else { None },
|
||||
});
|
||||
}
|
||||
updates
|
||||
}
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
/// Show the server the account's certificate and avatar
|
||||
/// Show the server the account's avatar or badges, or clear them
|
||||
/// (`updatemytsdata`), as the official client does once connected and
|
||||
/// after a sign-in, after the account proof (`updatemytsid`).
|
||||
/// Await the returned handle's `StreamItem::MessageResult` for the answer.
|
||||
pub fn send_myts_data(&mut self, data: &MytsData) -> Result<MessageHandle> {
|
||||
/// after a sign-in, after the account proof (`updatemytsid`). The server
|
||||
/// answers before the result: the own client's
|
||||
/// `client_myteamspeak_avatar` and `client_signed_badges`, empty for what
|
||||
/// did not verify. Await the returned handle's
|
||||
/// `StreamItem::MessageResult` for the answer.
|
||||
pub fn send_myts_update(&mut self, update: &MytsUpdate) -> Result<MessageHandle> {
|
||||
if !matches!(self.state, ConnectionState::Connected { .. }) {
|
||||
return Err(Error::NotConnected);
|
||||
}
|
||||
self.send_command_with_result(data_packet(data))
|
||||
self.send_command_with_result(data_packet(update))
|
||||
}
|
||||
|
||||
/// Set the User Tag (`clientupdate client_user_tag`), as built by
|
||||
/// [`UserTag::value`]; empty clears it. TeamSpeak 6 servers only.
|
||||
pub fn send_user_tag(&mut self, value: &str) -> Result<MessageHandle> {
|
||||
if !matches!(self.state, ConnectionState::Connected { .. }) {
|
||||
return Err(Error::NotConnected);
|
||||
}
|
||||
self.send_command_with_result(user_tag_packet(value))
|
||||
}
|
||||
|
||||
/// Publish a connection-bound account proof, or clear the account identity.
|
||||
@@ -66,14 +213,25 @@ impl Connection {
|
||||
}
|
||||
|
||||
/// The values are the raw bytes with TeamSpeak's escaping only (no
|
||||
/// base64), as the official client sends them; an empty avatar is left out.
|
||||
fn data_packet(data: &MytsData) -> OutCommand {
|
||||
/// base64), as the official client sends them; an empty one is the bare
|
||||
/// name, which clears.
|
||||
fn data_packet(update: &MytsUpdate) -> OutCommand {
|
||||
let mut packet =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "updatemytsdata");
|
||||
packet.write_bin_arg("myts_certificate", &data.certificate);
|
||||
if !data.avatar.is_empty() {
|
||||
packet.write_bin_arg("myts_avatar", &data.avatar);
|
||||
packet.write_bin_arg("myts_certificate", &update.certificate);
|
||||
if let Some(badges) = &update.badges {
|
||||
packet.write_bin_arg("myts_signed_badge", badges);
|
||||
}
|
||||
if let Some(avatar) = &update.avatar {
|
||||
packet.write_bin_arg("myts_avatar", avatar);
|
||||
}
|
||||
packet
|
||||
}
|
||||
|
||||
fn user_tag_packet(value: &str) -> OutCommand {
|
||||
let mut packet =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientupdate");
|
||||
packet.write_arg("client_user_tag", &value);
|
||||
packet
|
||||
}
|
||||
|
||||
@@ -93,20 +251,97 @@ fn update_packet(identity: Option<&Identity>, iv: &[u8; 64]) -> OutCommand {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn signed(certificate: &[u8], data: &[u8]) -> Signed {
|
||||
Signed { certificate: certificate.to_vec(), data: data.to_vec() }
|
||||
}
|
||||
|
||||
fn wire(update: &MytsUpdate) -> Vec<u8> { data_packet(update).into_packet().content().to_vec() }
|
||||
|
||||
#[test]
|
||||
fn account_data_goes_raw_and_escaped() {
|
||||
let data = MytsData {
|
||||
let update = MytsUpdate {
|
||||
certificate: b"a b/c|d\\\x07\x08\x00\xff".to_vec(),
|
||||
avatar: vec![0x0a, 0x02, b'h', b'i'],
|
||||
badges: Some(vec![0x0a, 0x01, b' ']),
|
||||
avatar: Some(vec![0x0a, 0x02, b'h', b'i']),
|
||||
};
|
||||
let packet = data_packet(&data).into_packet();
|
||||
assert_eq!(
|
||||
wire(&update),
|
||||
b"updatemytsdata myts_certificate=a\\sb\\/c\\pd\\\\\\a\\b\x00\xff \
|
||||
myts_signed_badge=\\n\x01\\s myts_avatar=\\n\x02hi"
|
||||
);
|
||||
// Without badges: the certificate and the avatar.
|
||||
let update = MytsUpdate { badges: None, ..update };
|
||||
assert!(!wire(&update).windows(17).any(|w| w == b"myts_signed_badge"));
|
||||
// Clearing: bare names, no certificate needed.
|
||||
let clear = MytsUpdate {
|
||||
certificate: Vec::new(),
|
||||
badges: Some(Vec::new()),
|
||||
avatar: Some(Vec::new()),
|
||||
};
|
||||
assert_eq!(wire(&clear), b"updatemytsdata myts_certificate myts_signed_badge myts_avatar");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_one_certificate_verifies_goes_together() {
|
||||
let data = MytsData {
|
||||
myts_id: vec![1; 33],
|
||||
avatar: signed(b"C", b"avatar"),
|
||||
badges: signed(b"C", b"badges"),
|
||||
badge_ids: vec!["b1".into()],
|
||||
user_tag: None,
|
||||
};
|
||||
let none = MytsData::default();
|
||||
assert_eq!(data.updates(&none, false), [MytsUpdate {
|
||||
certificate: b"C".to_vec(),
|
||||
badges: Some(b"badges".to_vec()),
|
||||
avatar: Some(b"avatar".to_vec()),
|
||||
}]);
|
||||
assert_eq!(
|
||||
wire(&data.updates(&none, false)[0]),
|
||||
b"updatemytsdata myts_certificate=C myts_signed_badge=badges myts_avatar=avatar"
|
||||
);
|
||||
// Unchanged: nothing, unless after a new account proof.
|
||||
assert!(data.updates(&data, false).is_empty());
|
||||
assert_eq!(data.updates(&data, true).len(), 1);
|
||||
// Two certificates: two commands, each with its own.
|
||||
let apart = MytsData { badges: signed(b"D", b"badges"), ..data.clone() };
|
||||
let updates: Vec<_> = apart.updates(&none, false).iter().map(wire).collect();
|
||||
assert_eq!(updates, [
|
||||
b"updatemytsdata myts_certificate=C myts_avatar=avatar".to_vec(),
|
||||
b"updatemytsdata myts_certificate=D myts_signed_badge=badges".to_vec(),
|
||||
]);
|
||||
// Only what changed.
|
||||
let newer = MytsData { avatar: signed(b"C", b"newer"), ..data.clone() };
|
||||
let updates: Vec<_> = newer.updates(&data, false).iter().map(wire).collect();
|
||||
assert_eq!(updates, [b"updatemytsdata myts_certificate=C myts_avatar=newer".to_vec()]);
|
||||
// What is no longer there is cleared; what never was is left alone.
|
||||
let fewer = MytsData { badges: Signed::default(), ..data.clone() };
|
||||
let updates: Vec<_> = fewer.updates(&data, true).iter().map(wire).collect();
|
||||
assert_eq!(updates, [
|
||||
b"updatemytsdata myts_certificate=C myts_avatar=avatar".to_vec(),
|
||||
b"updatemytsdata myts_certificate myts_signed_badge".to_vec(),
|
||||
]);
|
||||
let updates: Vec<_> = none.updates(&data, true).iter().map(wire).collect();
|
||||
assert_eq!(updates, [b"updatemytsdata myts_certificate myts_signed_badge myts_avatar".to_vec()]);
|
||||
assert!(none.updates(&none, true).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_user_tag_is_set_as_the_official_client_sets_it() {
|
||||
let tag = UserTag { tag: "alex@myteamspeak.com".into(), token: vec![0xfb, 0xff, 0x01, 0x02] };
|
||||
assert_eq!(
|
||||
tag.value(1_759_740_000_123),
|
||||
r#"{"myts_token":"+/8BAg==","tag":"alex@myteamspeak.com","updated":1759740000123}"#
|
||||
);
|
||||
let odd = UserTag { tag: "a\"b\\c\n\u{1}é".into(), token: Vec::new() };
|
||||
assert_eq!(odd.value(1), r#"{"myts_token":"","tag":"a\"b\\c\n\u0001é","updated":1}"#);
|
||||
// TeamSpeak's escaping on the wire; empty clears.
|
||||
let packet = user_tag_packet(&tag.value(5)).into_packet();
|
||||
assert_eq!(
|
||||
packet.content(),
|
||||
b"updatemytsdata myts_certificate=a\\sb\\/c\\pd\\\\\\a\\b\x00\xff myts_avatar=\\n\x02hi"
|
||||
&br#"clientupdate client_user_tag={"myts_token":"+\/8BAg==","tag":"alex@myteamspeak.com","updated":5}"#[..]
|
||||
);
|
||||
// Without an avatar: the certificate alone.
|
||||
let packet = data_packet(&MytsData { avatar: Vec::new(), ..data }).into_packet();
|
||||
assert!(!packet.content().windows(11).any(|w| w == b"myts_avatar"));
|
||||
assert_eq!(user_tag_packet("").into_packet().content(), b"clientupdate client_user_tag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -193,6 +193,8 @@ properties = [
|
||||
{ name="Badges", type="str" },
|
||||
{ name="UserTag", type="str", opt=true },
|
||||
{ name="MyTeamSpeakAvatar", type="str", opt=true, doc="`<state>,<url>;…` of the myTeamSpeak avatar (TeamSpeak 6)" },
|
||||
{ name="MyTeamSpeakId", type="str", opt=true, doc="The myTeamSpeak ID the server accepted (base64), empty without one" },
|
||||
{ name="SignedBadges", type="str", opt=true, doc="Comma-separated ids of the myTeamSpeak badges the server verified (TeamSpeak 6)" },
|
||||
{ name="PermissionHints", type="ClientPermissionHint", opt=true },
|
||||
{ name="OptionalData", type="OptionalClientData", opt=true },
|
||||
{ name="ConnectionData", type="ConnectionClientData", opt=true },
|
||||
|
||||
@@ -102,8 +102,17 @@ pub enum LicenseBlockType {
|
||||
/// Ts3_Server
|
||||
Server,
|
||||
Code,
|
||||
// Not existing in the license parameter:
|
||||
// 4: Token, 5: License_Sign, 6: MyTsId_Sign, 7: Updater
|
||||
// Not existing in the license parameter. Like `Ephemeral`, these blocks
|
||||
// carry nothing after the header.
|
||||
/// 4, Token
|
||||
Token,
|
||||
/// 5, License_Sign
|
||||
LicenseSign,
|
||||
/// 6, MyTsId_Sign: the key that signs myTeamSpeak data (avatars, badges,
|
||||
/// identifier tokens).
|
||||
MytsIdSign,
|
||||
/// 7, Updater
|
||||
Updater,
|
||||
/// Ts_Server_License
|
||||
Ts5Server = 8,
|
||||
/// 32, Ephemeral_Key
|
||||
@@ -413,8 +422,12 @@ impl License {
|
||||
|
||||
(InnerLicense::Ts5Server { properties }, pos)
|
||||
}
|
||||
LicenseBlockType::Ephemeral => (InnerLicense::Other, 0),
|
||||
_ => {
|
||||
LicenseBlockType::Token
|
||||
| LicenseBlockType::LicenseSign
|
||||
| LicenseBlockType::MytsIdSign
|
||||
| LicenseBlockType::Updater
|
||||
| LicenseBlockType::Ephemeral => (InnerLicense::Other, 0),
|
||||
LicenseBlockType::Website | LicenseBlockType::Code => {
|
||||
return Err(Error::UnknownBlockType(typ_i));
|
||||
}
|
||||
};
|
||||
@@ -710,7 +723,11 @@ impl fmt::Debug for DebugLicense<'_> {
|
||||
d.field("properties", &"error");
|
||||
}
|
||||
}
|
||||
LicenseBlockType::Ephemeral => {}
|
||||
LicenseBlockType::Token
|
||||
| LicenseBlockType::LicenseSign
|
||||
| LicenseBlockType::MytsIdSign
|
||||
| LicenseBlockType::Updater
|
||||
| LicenseBlockType::Ephemeral => {}
|
||||
}
|
||||
|
||||
d.finish()?;
|
||||
@@ -727,7 +744,11 @@ impl LicenseBlockType {
|
||||
Self::Website | Self::Code => 1,
|
||||
Self::Server => 6,
|
||||
Self::Ts5Server => 2,
|
||||
Self::Ephemeral => 0,
|
||||
Self::Token
|
||||
| Self::LicenseSign
|
||||
| Self::MytsIdSign
|
||||
| Self::Updater
|
||||
| Self::Ephemeral => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -923,6 +944,27 @@ mod tests {
|
||||
YrUET9sEbz1CATKgK8EyqrfA==").unwrap()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_blocks_without_payload() {
|
||||
// Token, License_Sign, MyTsId_Sign and Updater blocks end with their
|
||||
// header, as Ephemeral blocks do.
|
||||
for typ in [4, 5, 6, 7] {
|
||||
let mut data = vec![1, 0];
|
||||
data.extend_from_slice(&[0x58; 32]);
|
||||
data.push(typ);
|
||||
data.extend_from_slice(&[0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff]);
|
||||
let licenses = Licenses::parse_ignore_expired(data.clone()).unwrap();
|
||||
assert_eq!(licenses.blocks.len(), 1);
|
||||
assert_eq!(licenses.blocks[0].len, BLOCK_MIN_LEN);
|
||||
let block = licenses.blocks[0].get_type(&data[1..]).unwrap();
|
||||
assert_eq!(block.to_u8(), Some(typ));
|
||||
// Anything after the header is the next block.
|
||||
data.push(0);
|
||||
assert!(Licenses::parse_ignore_expired(data).is_err());
|
||||
}
|
||||
assert_eq!(LicenseBlockType::from_u8(6), Some(LicenseBlockType::MytsIdSign));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derive_public_key() {
|
||||
let licenses = Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAAC4R+5mos+UQ/KCbkpQLMI5WRp4wkQu8e5PZY4zU+/FlyAJwaE8CcJJ/A==").unwrap()).unwrap();
|
||||
|
||||
@@ -6,13 +6,17 @@
|
||||
use std::fmt;
|
||||
|
||||
use base64::prelude::*;
|
||||
use curve25519_dalek::edwards::{CompressedEdwardsY, EdwardsPoint};
|
||||
use curve25519_dalek::{constants::ED25519_BASEPOINT_TABLE, scalar::Scalar};
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use sha2::{Digest, Sha256, Sha512};
|
||||
use thiserror::Error;
|
||||
use tsproto_packets::packets::OutCommand;
|
||||
use tsproto_types::crypto::EccKeyPubEd25519;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use crate::license::{self, LicenseBlockType, Licenses};
|
||||
|
||||
/// An account identity; distinct from the account UUID and server identity.
|
||||
#[derive(Clone, Serialize)]
|
||||
pub struct Identity {
|
||||
@@ -94,6 +98,13 @@ impl Identity {
|
||||
|
||||
pub fn id(&self) -> String { BASE64_STANDARD.encode(&self.myts_id) }
|
||||
|
||||
/// The myTS ID's 33 bytes: what myTeamSpeak signs the account's avatar,
|
||||
/// badges and identifier token for.
|
||||
pub fn id_bytes(&self) -> &[u8] { &self.myts_id }
|
||||
|
||||
/// The certificate of the myTS ID's signature (`pubSignCert`): public.
|
||||
pub fn public_signature_certificate(&self) -> &[u8] { &self.public_signature[64..] }
|
||||
|
||||
/// Sign this connection's challenge with the original raw private scalar.
|
||||
/// This is not Ed25519's seed expansion: the account already stores a scalar.
|
||||
pub fn proof(&self, shared_iv: &[u8; 64]) -> Proof {
|
||||
@@ -131,6 +142,91 @@ impl Identity {
|
||||
}
|
||||
}
|
||||
|
||||
/// A myTeamSpeak certificate: a TeamSpeak license chain whose last block's
|
||||
/// key signs what myTeamSpeak hands out for an account (its avatar, badges
|
||||
/// and identifier token). Checked as a TeamSpeak 6 server and the official
|
||||
/// client check it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Certificate {
|
||||
block_type: Option<LicenseBlockType>,
|
||||
/// Unix seconds.
|
||||
not_valid_before: i64,
|
||||
not_valid_after: i64,
|
||||
/// The leaf's key, derived along the chain from the root.
|
||||
key: [u8; 32],
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CertificateError {
|
||||
#[error("myTeamSpeak certificate must start with version 1")]
|
||||
Version,
|
||||
#[error("myTeamSpeak certificate holds no key")]
|
||||
Empty,
|
||||
#[error("myTeamSpeak certificate does not parse: {0}")]
|
||||
License(#[from] license::Error),
|
||||
}
|
||||
|
||||
impl Certificate {
|
||||
/// Parse a certificate whose chain starts at `root` (the TeamSpeak root
|
||||
/// key, [`crate::ROOT_KEY`]). Nested validity windows are checked here,
|
||||
/// the leaf's against a time by [`Self::valid_at`].
|
||||
pub fn parse(data: &[u8], root: &[u8; 32]) -> Result<Self, CertificateError> {
|
||||
if data.first() != Some(&1) {
|
||||
return Err(CertificateError::Version);
|
||||
}
|
||||
let licenses = Licenses::parse_ignore_expired(data.to_vec())?;
|
||||
let leaf = licenses.blocks.last().ok_or(CertificateError::Empty)?;
|
||||
let leaf_data = &data[data.len() - leaf.len..];
|
||||
let key = licenses.derive_public_key(EccKeyPubEd25519::from_bytes(*root))?;
|
||||
Ok(Self {
|
||||
block_type: leaf.get_type(leaf_data).ok(),
|
||||
not_valid_before: leaf.get_not_valid_before(leaf_data)?.unix_timestamp(),
|
||||
not_valid_after: leaf.get_not_valid_after(leaf_data)?.unix_timestamp(),
|
||||
key: key.compress().to_bytes(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the leaf is a key that signs for myTS IDs (`MYTSID_SIGN`):
|
||||
/// a TeamSpeak 6 server takes no other for an avatar or badges.
|
||||
pub fn signs_myts_data(&self) -> bool { self.block_type == Some(LicenseBlockType::MytsIdSign) }
|
||||
|
||||
/// Whether the leaf is valid at `unix` seconds.
|
||||
pub fn valid_at(&self, unix: i64) -> bool {
|
||||
self.not_valid_before <= unix && unix < self.not_valid_after
|
||||
}
|
||||
|
||||
/// Until when the leaf is valid, Unix seconds.
|
||||
pub fn not_valid_after(&self) -> i64 { self.not_valid_after }
|
||||
|
||||
/// Whether the leaf's key signed `message` (Ed25519, as TeamSpeak checks
|
||||
/// it: SHA-512 over R, the key and the message, without the cofactor;
|
||||
/// a signature whose S is not reduced is refused).
|
||||
pub fn verifies(&self, message: &[u8], signature: &[u8]) -> bool {
|
||||
verify_ed25519(&self.key, message, signature)
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_ed25519(key: &[u8; 32], message: &[u8], signature: &[u8]) -> bool {
|
||||
if signature.len() != 64 {
|
||||
return false;
|
||||
}
|
||||
let Some(public) = CompressedEdwardsY(*key).decompress() else {
|
||||
return false;
|
||||
};
|
||||
let mut s = [0; 32];
|
||||
s.copy_from_slice(&signature[32..]);
|
||||
let Some(s) = Option::<Scalar>::from(Scalar::from_canonical_bytes(s)) else {
|
||||
return false;
|
||||
};
|
||||
let mut hash = Sha512::new();
|
||||
hash.update(&signature[..32]);
|
||||
hash.update(key);
|
||||
hash.update(message);
|
||||
let k = Scalar::from_bytes_mod_order_wide(&hash.finalize().into());
|
||||
let r = EdwardsPoint::vartime_double_scalar_mul_basepoint(&k, &-public, &s);
|
||||
r.compress().as_bytes() == &signature[..32]
|
||||
}
|
||||
|
||||
/// Public, connection-bound authentication values. Never contains private keys.
|
||||
#[derive(Clone)]
|
||||
pub struct Proof {
|
||||
@@ -244,4 +340,136 @@ mod tests {
|
||||
]);
|
||||
assert!(!wire.contains("private"));
|
||||
}
|
||||
|
||||
/// A chain from a synthetic root (secret `root`): an intermediate block
|
||||
/// when `outer` is set, then a leaf of `kind` with the key `leaf`·B, valid
|
||||
/// from `from` to `to` (Unix seconds). Also the leaf's derived secret.
|
||||
fn chain(
|
||||
root: Scalar, outer: Option<(i64, i64)>, leaf: Scalar, kind: u8, from: i64, to: i64,
|
||||
) -> (Vec<u8>, Scalar) {
|
||||
fn block(key: &Scalar, kind: u8, from: i64, to: i64, extra: &[u8]) -> (Vec<u8>, Scalar) {
|
||||
let mut block = vec![0];
|
||||
block.extend_from_slice((ED25519_BASEPOINT_TABLE * key).compress().as_bytes());
|
||||
block.push(kind);
|
||||
for time in [from, to] {
|
||||
block.extend_from_slice(&((time - license::TIMESTAMP_OFFSET) as u32).to_be_bytes());
|
||||
}
|
||||
block.extend_from_slice(extra);
|
||||
let mut hash: [u8; 64] = Sha512::digest(&block[1..]).into();
|
||||
hash[0] &= 248;
|
||||
hash[31] &= 63;
|
||||
hash[31] |= 64;
|
||||
let mut low = [0; 32];
|
||||
low.copy_from_slice(&hash[..32]);
|
||||
(block, Scalar::from_bytes_mod_order(low))
|
||||
}
|
||||
let mut data = vec![1];
|
||||
let mut secret = root;
|
||||
if let Some((from, to)) = outer {
|
||||
let key = Scalar::from_bytes_mod_order([3; 32]);
|
||||
let (outer, hash) = block(&key, 0, from, to, b"\0\0\0\0Synthetic\0");
|
||||
data.extend_from_slice(&outer);
|
||||
secret += key * hash;
|
||||
}
|
||||
let (leaf_block, hash) = block(&leaf, kind, from, to, &[]);
|
||||
data.extend_from_slice(&leaf_block);
|
||||
(data, secret + leaf * hash)
|
||||
}
|
||||
|
||||
fn sign(secret: &Scalar, message: &[u8]) -> Vec<u8> {
|
||||
let public = (ED25519_BASEPOINT_TABLE * secret).compress().to_bytes();
|
||||
let nonce = Scalar::from_bytes_mod_order_wide(
|
||||
&Sha512::new().chain_update(secret.as_bytes()).chain_update(message).finalize().into(),
|
||||
);
|
||||
let r = (ED25519_BASEPOINT_TABLE * &nonce).compress().to_bytes();
|
||||
let k = Scalar::from_bytes_mod_order_wide(
|
||||
&Sha512::new().chain_update(r).chain_update(public).chain_update(message).finalize().into(),
|
||||
);
|
||||
let mut signature = r.to_vec();
|
||||
signature.extend_from_slice((k * secret + nonce).as_bytes());
|
||||
signature
|
||||
}
|
||||
|
||||
const NOW: i64 = 1_790_000_000;
|
||||
|
||||
#[test]
|
||||
fn certificate_key_signs_along_the_chain() {
|
||||
let root = Scalar::from_bytes_mod_order([5; 32]);
|
||||
let root_key = (ED25519_BASEPOINT_TABLE * &root).compress().to_bytes();
|
||||
let leaf = Scalar::from_bytes_mod_order([7; 32]);
|
||||
for outer in [None, Some((NOW - 1000, NOW + 1000))] {
|
||||
let (data, secret) = chain(root, outer, leaf, 6, NOW - 10, NOW + 10);
|
||||
let certificate = Certificate::parse(&data, &root_key).unwrap();
|
||||
assert!(certificate.signs_myts_data());
|
||||
assert!(certificate.valid_at(NOW - 10) && certificate.valid_at(NOW + 9));
|
||||
assert!(!certificate.valid_at(NOW - 11) && !certificate.valid_at(NOW + 10));
|
||||
assert_eq!(certificate.not_valid_after(), NOW + 10);
|
||||
let signature = sign(&secret, b"message");
|
||||
assert!(certificate.verifies(b"message", &signature));
|
||||
assert!(!certificate.verifies(b"messagE", &signature));
|
||||
assert!(!certificate.verifies(b"message", &signature[..63]));
|
||||
let mut flipped = signature.clone();
|
||||
flipped[5] ^= 1;
|
||||
assert!(!certificate.verifies(b"message", &flipped));
|
||||
// The same S plus the group order: refused, though it is the same
|
||||
// point (S must be reduced).
|
||||
let mut s = [0u8; 32];
|
||||
s.copy_from_slice(&signature[32..]);
|
||||
let order: [u8; 32] = [
|
||||
0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9,
|
||||
0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10,
|
||||
];
|
||||
let mut carry = 0u16;
|
||||
for (s, l) in s.iter_mut().zip(order) {
|
||||
let sum = u16::from(*s) + u16::from(l) + carry;
|
||||
*s = sum as u8;
|
||||
carry = sum >> 8;
|
||||
}
|
||||
let mut unreduced = signature.clone();
|
||||
unreduced[32..].copy_from_slice(&s);
|
||||
assert!(!certificate.verifies(b"message", &unreduced));
|
||||
// Another root: another key.
|
||||
let other = Certificate::parse(&data, &crate::ROOT_KEY).unwrap();
|
||||
assert!(!other.verifies(b"message", &signature));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ed25519_matches_rfc_8032() {
|
||||
// RFC 8032, 7.1, tests 1 and 2.
|
||||
let key = hex::<32>("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a");
|
||||
let signature = hex::<64>(
|
||||
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b",
|
||||
);
|
||||
assert!(verify_ed25519(&key, b"", &signature));
|
||||
assert!(!verify_ed25519(&key, b"\x72", &signature));
|
||||
let key = hex::<32>("3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c");
|
||||
let signature = hex::<64>(
|
||||
"92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00",
|
||||
);
|
||||
assert!(verify_ed25519(&key, b"\x72", &signature));
|
||||
assert!(!verify_ed25519(&key, b"\x73", &signature));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certificate_kinds_windows_and_format() {
|
||||
let root = Scalar::from_bytes_mod_order([5; 32]);
|
||||
let root_key = (ED25519_BASEPOINT_TABLE * &root).compress().to_bytes();
|
||||
let leaf = Scalar::from_bytes_mod_order([7; 32]);
|
||||
for kind in [4, 5, 7, 32] {
|
||||
let (data, _) = chain(root, None, leaf, kind, NOW - 10, NOW + 10);
|
||||
assert!(!Certificate::parse(&data, &root_key).unwrap().signs_myts_data(), "{}", kind);
|
||||
}
|
||||
// A leaf valid longer than the block above it.
|
||||
let (data, _) = chain(root, Some((NOW - 5, NOW + 5)), leaf, 6, NOW - 10, NOW + 10);
|
||||
assert!(Certificate::parse(&data, &root_key).is_err());
|
||||
let (mut data, _) = chain(root, None, leaf, 6, NOW - 10, NOW + 10);
|
||||
data[0] = 0;
|
||||
assert!(matches!(Certificate::parse(&data, &root_key), Err(CertificateError::Version)));
|
||||
assert!(matches!(Certificate::parse(&[1], &root_key), Err(CertificateError::Empty)));
|
||||
assert!(Certificate::parse(&[], &root_key).is_err());
|
||||
data[0] = 1;
|
||||
data[34] = 9;
|
||||
assert!(Certificate::parse(&data, &root_key).is_err());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user