M4: tsgw gateway and tsc-gateway-proto
- tsc-gateway-proto: versioned JSON envelope (tsgw.v1+json), client and server messages, identity-challenge auth (ECDSA P-256 over a signed challenge), unique ids for TS3 (SHA-1) and TS6 (SHA-256, verified on 6.0.0-beta13.1), hash-cash level. - tsc-gateway (tsgw): axum WebSocket server; hub with one observer, a relay pool and a lookup query session; login by signature or token; permission mirroring via permoverview (server group/client/channel group/channel-client levels, skip and negate); per-user filtered presence (snapshot + diff deltas); channel/server chat relay with server-known nicknames, rate limit, idle relay teardown, pinned channels; SQLite tokens, history and audit; Dockerfile; admin guide. - tsctl gateway client; smoke test covers gateway presence, chat both ways and refusal of unknown identities on TS3 and TS6. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
1 parent
7b5f1ad2bb
commit
120d3dfc82
24 files changed
+2578
-9
No files matched your search
@@ -0,0 +1,160 @@
|
||||
//! Identity-challenge authentication.
|
||||
|
||||
use base64::prelude::*;
|
||||
use sha1::{Digest, Sha1};
|
||||
use sha2::Sha256;
|
||||
use tsproto_types::crypto::{EccKeyPrivP256, EccKeyPubP256};
|
||||
|
||||
/// Maximum allowed difference between the client's and our clock.
|
||||
pub const MAX_CLOCK_SKEW_SECS: i64 = 60;
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum AuthError {
|
||||
#[error("invalid public key")]
|
||||
BadKey,
|
||||
#[error("invalid signature")]
|
||||
BadSignature,
|
||||
#[error("timestamp too far from the gateway's clock")]
|
||||
ClockSkew,
|
||||
}
|
||||
|
||||
/// The bytes a client signs.
|
||||
pub fn challenge(gateway_id: &str, server_uid: &str, nonce: &str, ts: i64) -> Vec<u8> {
|
||||
format!("tsgw-auth-v1\n{gateway_id}\n{server_uid}\n{nonce}\n{ts}").into_bytes()
|
||||
}
|
||||
|
||||
/// Client side: sign the challenge with the identity key (base64 DER).
|
||||
pub fn sign_challenge(
|
||||
key: &EccKeyPrivP256,
|
||||
gateway_id: &str,
|
||||
server_uid: &str,
|
||||
nonce: &str,
|
||||
ts: i64,
|
||||
) -> String {
|
||||
BASE64_STANDARD.encode(key.clone().sign(&challenge(gateway_id, server_uid, nonce, ts)))
|
||||
}
|
||||
|
||||
/// The unique ids a TeamSpeak identity has on the two server generations.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct UniqueIds {
|
||||
/// TeamSpeak 3: `base64(SHA1(omega))`.
|
||||
pub ts3: String,
|
||||
/// TeamSpeak 6: `base64(SHA256(omega))` (verified on 6.0.0-beta13.1).
|
||||
pub ts6: String,
|
||||
}
|
||||
|
||||
impl UniqueIds {
|
||||
pub fn from_omega(omega: &str) -> Self {
|
||||
Self {
|
||||
ts3: BASE64_STANDARD.encode(Sha1::digest(omega.as_bytes())),
|
||||
ts6: BASE64_STANDARD.encode(Sha256::digest(omega.as_bytes())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The id the given server knows the identity by.
|
||||
pub fn for_server(&self, is_ts6: bool) -> &str {
|
||||
if is_ts6 { &self.ts6 } else { &self.ts3 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Gateway side: check the signature and clock, return the identity's ids.
|
||||
pub fn verify_auth(
|
||||
omega: &str,
|
||||
signature: &str,
|
||||
gateway_id: &str,
|
||||
server_uid: &str,
|
||||
nonce: &str,
|
||||
ts: i64,
|
||||
now: i64,
|
||||
) -> Result<UniqueIds, AuthError> {
|
||||
if (now - ts).abs() > MAX_CLOCK_SKEW_SECS {
|
||||
return Err(AuthError::ClockSkew);
|
||||
}
|
||||
let key = EccKeyPubP256::from_ts(omega).map_err(|_| AuthError::BadKey)?;
|
||||
let signature = BASE64_STANDARD.decode(signature).map_err(|_| AuthError::BadSignature)?;
|
||||
key.verify(&challenge(gateway_id, server_uid, nonce, ts), &signature)
|
||||
.map_err(|_| AuthError::BadSignature)?;
|
||||
Ok(UniqueIds::from_omega(omega))
|
||||
}
|
||||
|
||||
/// Hash-cash security level of an identity, as TeamSpeak computes it:
|
||||
/// leading zero bits of `SHA1(omega + decimal offset)`, bytes from the start,
|
||||
/// bits from least significant.
|
||||
pub fn identity_level(omega: &str, key_offset: u64) -> u8 {
|
||||
let hash = Sha1::digest(format!("{omega}{key_offset}").as_bytes());
|
||||
let mut level = 0;
|
||||
for &byte in hash.as_slice() {
|
||||
if byte == 0 {
|
||||
level += 8;
|
||||
} else {
|
||||
level += byte.trailing_zeros() as u8;
|
||||
break;
|
||||
}
|
||||
}
|
||||
level
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sign_and_verify() {
|
||||
let key = EccKeyPrivP256::create();
|
||||
let omega = key.to_pub().to_ts();
|
||||
let sig = sign_challenge(&key, "gw", "srv", "nonce", 1000);
|
||||
let ids = verify_auth(&omega, &sig, "gw", "srv", "nonce", 1000, 1010).unwrap();
|
||||
assert_eq!(ids.ts3, key.to_pub().get_uid());
|
||||
assert_eq!(ids.ts6.len(), 44);
|
||||
|
||||
// Any change to the challenge breaks the signature.
|
||||
assert_eq!(
|
||||
verify_auth(&omega, &sig, "gw", "srv", "other", 1000, 1000),
|
||||
Err(AuthError::BadSignature)
|
||||
);
|
||||
assert_eq!(
|
||||
verify_auth(&omega, &sig, "gw2", "srv", "nonce", 1000, 1000),
|
||||
Err(AuthError::BadSignature)
|
||||
);
|
||||
// Someone else's key.
|
||||
let other = EccKeyPrivP256::create().to_pub().to_ts();
|
||||
assert_eq!(
|
||||
verify_auth(&other, &sig, "gw", "srv", "nonce", 1000, 1000),
|
||||
Err(AuthError::BadSignature)
|
||||
);
|
||||
// Stale timestamp.
|
||||
assert_eq!(
|
||||
verify_auth(&omega, &sig, "gw", "srv", "nonce", 1000, 2000),
|
||||
Err(AuthError::ClockSkew)
|
||||
);
|
||||
assert_eq!(
|
||||
verify_auth("garbage", &sig, "gw", "srv", "nonce", 1000, 1000),
|
||||
Err(AuthError::BadKey)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ts6_uid_is_sha256_of_omega() {
|
||||
// One identity as seen in clientdblist of TeamSpeak 3.13.8 and 6.0.0-beta13.1.
|
||||
let omega = "MEsDAgcAAgEgAiBCmlKdgFw427AndT7fm2Wx4bgENOi6eQRUzwbT7Dnv9wIgcJETAwMtVjWdsCqZejblVJruSKWe4l845nWNAMYMkpk=";
|
||||
let ids = UniqueIds::from_omega(omega);
|
||||
assert_eq!(ids.ts3, "uXDkxSZbv0IoA0z/toW3guGpUbI=");
|
||||
assert_eq!(ids.ts6, "xEZDkyeGdZ4bOSBCKqzTw8jVz2jsZCrJDRl9F8WWd3M=");
|
||||
assert_eq!(ids.for_server(true), ids.ts6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn level_matches_tsproto() {
|
||||
// Same algorithm as the vendored client (and the TeamSpeak server).
|
||||
let identity = tsproto::Identity::create();
|
||||
let omega = identity.key().to_pub().to_ts();
|
||||
assert!(identity.level() >= 8);
|
||||
assert_eq!(identity_level(&omega, identity.counter()), identity.level());
|
||||
for offset in 0..200 {
|
||||
assert_eq!(
|
||||
identity_level(&omega, offset),
|
||||
tsproto::algorithms::get_hash_cash_level(&omega, offset)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//! Wire protocol of `tsgw`, the companion gateway that gives app users
|
||||
//! invisible presence and channel chat without joining voice.
|
||||
//!
|
||||
//! Transport: WebSocket, subprotocol [`SUBPROTOCOL`], one JSON [`Envelope`]
|
||||
//! per text frame. Within version 1 changes are additive only: new message
|
||||
//! types and optional fields. Unknown fields must be ignored.
|
||||
//!
|
||||
//! Authentication proves ownership of a TeamSpeak identity: the gateway sends
|
||||
//! a nonce in [`ServerMsg::Hello`], the client answers with
|
||||
//! [`ClientMsg::Auth`], an ECDSA P-256 signature over [`challenge`] made with
|
||||
//! the identity's private key. The unique id is derived from the public key,
|
||||
//! exactly as the TeamSpeak server does.
|
||||
|
||||
mod auth;
|
||||
mod messages;
|
||||
|
||||
pub use auth::{
|
||||
AuthError, MAX_CLOCK_SKEW_SECS, UniqueIds, challenge, identity_level, sign_challenge,
|
||||
verify_auth,
|
||||
};
|
||||
pub use messages::*;
|
||||
|
||||
/// WebSocket subprotocol.
|
||||
pub const SUBPROTOCOL: &str = "tsgw.v1+json";
|
||||
/// Protocol version in every envelope.
|
||||
pub const VERSION: u32 = 1;
|
||||
@@ -0,0 +1,185 @@
|
||||
//! Messages in both directions.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tsc_model::{ChatMessage, ChatTarget, PresenceDelta, PresenceSnapshot};
|
||||
|
||||
/// Every frame: `{"v":1,"id":7,"type":"send_chat","data":{...}}`.
|
||||
///
|
||||
/// `id` is chosen by the client for requests; the gateway copies it into the
|
||||
/// answer ([`ServerMsg::Ok`], [`ServerMsg::Error`], [`ServerMsg::History`]).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Envelope<M> {
|
||||
pub v: u32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub id: Option<u64>,
|
||||
#[serde(flatten)]
|
||||
pub msg: M,
|
||||
}
|
||||
|
||||
impl<M> Envelope<M> {
|
||||
pub fn new(msg: M) -> Self {
|
||||
Self { v: crate::VERSION, id: None, msg }
|
||||
}
|
||||
pub fn with_id(id: u64, msg: M) -> Self {
|
||||
Self { v: crate::VERSION, id: Some(id), msg }
|
||||
}
|
||||
}
|
||||
|
||||
/// Client to gateway.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
|
||||
pub enum ClientMsg {
|
||||
/// Answer to [`ServerMsg::Hello`].
|
||||
Auth {
|
||||
/// Public key, TeamSpeak "omega" format (base64 libtomcrypt DER).
|
||||
omega: String,
|
||||
/// Hash-cash counter (`client_key_offset`) that gives the identity its level.
|
||||
key_offset: u64,
|
||||
/// Unix time in seconds, part of the signed challenge.
|
||||
ts: i64,
|
||||
/// Base64 DER ECDSA signature over [`crate::challenge`].
|
||||
signature: String,
|
||||
/// Nickname for relayed messages.
|
||||
nickname: String,
|
||||
},
|
||||
/// Log in again with a token from [`ServerMsg::AuthOk`] instead of a signature.
|
||||
Resume {
|
||||
token: String,
|
||||
nickname: String,
|
||||
},
|
||||
/// Start (or restart) the presence stream: a snapshot, then deltas.
|
||||
SubscribePresence,
|
||||
UnsubscribePresence,
|
||||
/// Start receiving a chat.
|
||||
OpenChat {
|
||||
target: ChatTarget,
|
||||
},
|
||||
CloseChat {
|
||||
target: ChatTarget,
|
||||
},
|
||||
SendChat {
|
||||
target: ChatTarget,
|
||||
text: String,
|
||||
},
|
||||
/// Up to `limit` messages before message id `before` (latest when absent).
|
||||
History {
|
||||
target: ChatTarget,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
before: Option<i64>,
|
||||
limit: u32,
|
||||
},
|
||||
Ping,
|
||||
}
|
||||
|
||||
/// Gateway to client.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
|
||||
pub enum ServerMsg {
|
||||
/// First message after connecting.
|
||||
Hello {
|
||||
gateway_id: String,
|
||||
server_uid: String,
|
||||
server_name: String,
|
||||
nonce: String,
|
||||
/// Optional features, e.g. `history`.
|
||||
#[serde(default)]
|
||||
capabilities: Vec<String>,
|
||||
},
|
||||
AuthOk {
|
||||
uid: String,
|
||||
/// Opaque; send it in [`ClientMsg::Resume`].
|
||||
token: String,
|
||||
/// Unix time in seconds.
|
||||
token_expires: i64,
|
||||
},
|
||||
/// Presence restricted to what this user may see. `seq` restarts at 0 with
|
||||
/// each snapshot and increases by one per delta.
|
||||
PresenceSnapshot {
|
||||
seq: u64,
|
||||
snapshot: PresenceSnapshot,
|
||||
},
|
||||
PresenceDelta {
|
||||
seq: u64,
|
||||
delta: PresenceDelta,
|
||||
},
|
||||
/// A message in an open chat. `id` orders messages and pages history.
|
||||
ChatEvent {
|
||||
id: i64,
|
||||
message: ChatMessage,
|
||||
},
|
||||
History {
|
||||
messages: Vec<HistoryEntry>,
|
||||
},
|
||||
/// Request succeeded.
|
||||
Ok,
|
||||
Error {
|
||||
code: ErrorCode,
|
||||
message: String,
|
||||
},
|
||||
Pong,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct HistoryEntry {
|
||||
pub id: i64,
|
||||
pub message: ChatMessage,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ErrorCode {
|
||||
/// Malformed or unexpected message.
|
||||
BadRequest,
|
||||
/// Signature, timestamp or token invalid.
|
||||
AuthFailed,
|
||||
/// The server's database has no client with this unique id: connect
|
||||
/// with voice once first.
|
||||
UnknownIdentity,
|
||||
/// Identity security level below what the server requires.
|
||||
LevelTooLow,
|
||||
/// The user is banned on the server.
|
||||
Banned,
|
||||
/// Not allowed by the user's server permissions or the gateway config.
|
||||
Forbidden,
|
||||
NotAuthenticated,
|
||||
/// Temporary problem talking to the TeamSpeak server.
|
||||
Unavailable,
|
||||
Internal,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn envelope_json_shape() {
|
||||
let env = Envelope::with_id(
|
||||
7,
|
||||
ClientMsg::SendChat { target: ChatTarget::Channel(5), text: "hi".into() },
|
||||
);
|
||||
let json = serde_json::to_string(&env).unwrap();
|
||||
assert_eq!(
|
||||
json,
|
||||
r#"{"v":1,"id":7,"type":"send_chat","data":{"target":{"kind":"channel","id":5},"text":"hi"}}"#
|
||||
);
|
||||
let back: Envelope<ClientMsg> = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back, env);
|
||||
|
||||
let ping = serde_json::to_string(&Envelope::new(ClientMsg::Ping)).unwrap();
|
||||
assert_eq!(ping, r#"{"v":1,"type":"ping"}"#);
|
||||
assert_eq!(
|
||||
serde_json::to_string(&Envelope::new(ServerMsg::Ok)).unwrap(),
|
||||
r#"{"v":1,"type":"ok"}"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_unknown_fields() {
|
||||
let json = r#"{"v":1,"type":"history","data":{"target":{"kind":"server"},"limit":5,"future":true},"extra":1}"#;
|
||||
let env: Envelope<ClientMsg> = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(
|
||||
env.msg,
|
||||
ClientMsg::History { target: ChatTarget::Server, before: None, limit: 5 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user