tsproto: solve the Init1 puzzle off-thread with Montgomery squaring
TeamSpeak 6 beta13 raises the puzzle level with the server's protection level. The solver now runs on a blocking thread, can be cancelled, is ~25% faster (crypto-bigint Montgomery form), and the level cap is configurable (default 100M instead of a fixed 10M). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
6 files changed
+145
-15
No files matched your search
Generated
+13
-1
@@ -599,6 +599,17 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-bigint"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "96272c2ff28b807e09250b180ad1fb7889a3258f7455759b5c3c58b719467130"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
"rand_core 0.6.4",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
@@ -803,7 +814,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
|
||||
dependencies = [
|
||||
"base16ct",
|
||||
"crypto-bigint",
|
||||
"crypto-bigint 0.5.5",
|
||||
"digest 0.10.7",
|
||||
"ff",
|
||||
"generic-array",
|
||||
@@ -3319,6 +3330,7 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"clap",
|
||||
"criterion",
|
||||
"crypto-bigint 0.6.1",
|
||||
"curve25519-dalek-ng",
|
||||
"eax",
|
||||
"futures",
|
||||
|
||||
@@ -37,3 +37,9 @@ against or offered back to upstream.
|
||||
`tsclientlib/examples/audio_utils/audio_to_ts.rs`, `tsclientlib/Cargo.toml`).
|
||||
`audiopus` is unmaintained (RUSTSEC-2026-0150) and breaks with CMake 4. The
|
||||
`audiopus-unstable` feature (decoder complexity/DRED via a fork) is dropped.
|
||||
3. **Init1 RSA puzzle off-thread** (`tsproto/src/algorithms.rs`, `tsproto/src/client.rs`,
|
||||
`tsproto/benches/modpow.rs`). `solve_rsa_puzzle` does Montgomery squarings with
|
||||
`crypto-bigint` (about 25% faster than `num-bigint` `modpow`) on a
|
||||
`spawn_blocking` thread that stops when the connect future is dropped. The level
|
||||
cap is `max_puzzle_level()` (default 100 million, was a fixed 10 million),
|
||||
adjustable with `set_max_puzzle_level`, because TeamSpeak 6 adapts the level.
|
||||
@@ -37,11 +37,12 @@ sha-1 = "0.10"
|
||||
sha2 = "0.10"
|
||||
thiserror = "2"
|
||||
time = { version = "0.3", features = ["formatting"] }
|
||||
tokio = { version = "1", features = ["macros", "net", "sync", "time"] }
|
||||
tokio = { version = "1", features = ["macros", "net", "rt", "sync", "time"] }
|
||||
tracing = "0.1"
|
||||
tsproto-packets = { path = "../tsproto-packets", version = "0.1" }
|
||||
tsproto-types = { path = "../tsproto-types", version = "0.1" }
|
||||
quicklz = "0.3"
|
||||
crypto-bigint = "0.6"
|
||||
|
||||
[dev-dependencies]
|
||||
anyhow = "1"
|
||||
|
||||
@@ -16,6 +16,16 @@ fn num_modpow(b: &mut Bencher) {
|
||||
b.iter(|| x.modpow(&e, &n));
|
||||
}
|
||||
|
||||
fn montgomery_squaring(b: &mut Bencher) {
|
||||
let n = "9387019355706217197639129234358945126657617361248696932841794255538327365072557602175160199263073329488914880215590036563068284078359088114486271428098753";
|
||||
let x = "2148617454765635492758175407769288127281667975788420713054995716016550287184632946544163990319181591625774561067011999700977775946073267145316355582522577";
|
||||
let level = 10_000;
|
||||
let n = tsproto::algorithms::biguint_to_array(&n.parse().unwrap());
|
||||
let x = tsproto::algorithms::biguint_to_array(&x.parse().unwrap());
|
||||
|
||||
b.iter(|| tsproto::algorithms::solve_rsa_puzzle(&x, &n, level, None).unwrap());
|
||||
}
|
||||
|
||||
#[cfg(feature = "rug")]
|
||||
fn gmp_modpow(b: &mut Bencher) {
|
||||
let n = "9387019355706217197639129234358945126657617361248696932841794255538327365072557602175160199263073329488914880215590036563068284078359088114486271428098753";
|
||||
@@ -31,6 +41,7 @@ fn gmp_modpow(b: &mut Bencher) {
|
||||
|
||||
fn bench_modpow(c: &mut Criterion) {
|
||||
c.bench_function("num bigint", num_modpow);
|
||||
c.bench_function("crypto-bigint montgomery", montgomery_squaring);
|
||||
|
||||
#[cfg(feature = "rug")]
|
||||
{
|
||||
|
||||
@@ -276,8 +276,100 @@ pub fn biguint_to_array(i: &BigUint) -> [u8; 64] {
|
||||
|
||||
pub fn array_to_biguint(i: &[u8; 64]) -> BigUint { BigUint::from_bytes_be(i) }
|
||||
|
||||
/// Default maximum level of the Init1 RSA puzzle we are willing to solve.
|
||||
///
|
||||
/// TeamSpeak 6 adapts the level to the server's protection level, so this is
|
||||
/// higher than the 10 million upstream used. At about 0.14 µs per squaring
|
||||
/// (x86-64, 2026) a level of 100 million takes roughly 15 seconds.
|
||||
pub const DEFAULT_MAX_PUZZLE_LEVEL: u32 = 100_000_000;
|
||||
|
||||
static MAX_PUZZLE_LEVEL: std::sync::atomic::AtomicU32 =
|
||||
std::sync::atomic::AtomicU32::new(DEFAULT_MAX_PUZZLE_LEVEL);
|
||||
|
||||
/// Maximum Init1 puzzle level accepted by new connections.
|
||||
pub fn max_puzzle_level() -> u32 { MAX_PUZZLE_LEVEL.load(std::sync::atomic::Ordering::Relaxed) }
|
||||
|
||||
/// Change the maximum Init1 puzzle level accepted by new connections.
|
||||
pub fn set_max_puzzle_level(level: u32) {
|
||||
MAX_PUZZLE_LEVEL.store(level, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Solve the Init1 RSA puzzle: `y = x ^ (2 ^ level) mod n`.
|
||||
///
|
||||
/// This is `level` modular squarings in Montgomery form. `cancel` is checked
|
||||
/// every few thousand squarings; when it is set, `None` is returned. `None` is
|
||||
/// also returned for an even (invalid) modulus.
|
||||
pub fn solve_rsa_puzzle(
|
||||
x: &[u8; 64], n: &[u8; 64], level: u32, cancel: Option<&std::sync::atomic::AtomicBool>,
|
||||
) -> Option<[u8; 64]> {
|
||||
use crypto_bigint::modular::{MontyForm, MontyParams};
|
||||
use crypto_bigint::{Odd, U512};
|
||||
|
||||
const CHECK_EVERY: u32 = 4096;
|
||||
|
||||
let n = Option::<Odd<U512>>::from(Odd::new(U512::from_be_slice(n)))?;
|
||||
let params = MontyParams::new_vartime(n);
|
||||
let mut y = MontyForm::new(&U512::from_be_slice(x), params);
|
||||
let mut done = 0;
|
||||
while done < level {
|
||||
if cancel.is_some_and(|c| c.load(std::sync::atomic::Ordering::Relaxed)) {
|
||||
return None;
|
||||
}
|
||||
let steps = CHECK_EVERY.min(level - done);
|
||||
for _ in 0..steps {
|
||||
y = y.square();
|
||||
}
|
||||
done += steps;
|
||||
}
|
||||
Some(y.retrieve().to_be_bytes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn rsa_puzzle_matches_modpow() {
|
||||
use num_bigint::BigUint;
|
||||
use num_traits::One;
|
||||
|
||||
// Deterministic pseudo-random 512 bit inputs; n odd, x < n.
|
||||
let mut state = 0x2545_f491_4f6c_dd1du64;
|
||||
let mut next = || {
|
||||
let mut out = [0u8; 64];
|
||||
for b in &mut out {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
*b = state as u8;
|
||||
}
|
||||
out
|
||||
};
|
||||
for level in [0, 1, 2, 1000, 4097, 20_000] {
|
||||
let mut n = next();
|
||||
n[0] |= 0x80;
|
||||
n[63] |= 1;
|
||||
let mut x = next();
|
||||
x[0] &= 0x7f;
|
||||
let expected = super::biguint_to_array(&BigUint::from_bytes_be(&x).modpow(
|
||||
&(BigUint::one() << level as usize),
|
||||
&BigUint::from_bytes_be(&n),
|
||||
));
|
||||
assert_eq!(super::solve_rsa_puzzle(&x, &n, level, None), Some(expected), "level {level}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rsa_puzzle_rejects_even_modulus_and_cancels() {
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
let x = [3; 64];
|
||||
let mut n = [0xff; 64];
|
||||
n[63] = 0xfe;
|
||||
assert_eq!(super::solve_rsa_puzzle(&x, &n, 10, None), None);
|
||||
n[63] = 0xff;
|
||||
let cancel = AtomicBool::new(true);
|
||||
assert_eq!(super::solve_rsa_puzzle(&x, &n, 10, Some(&cancel)), None);
|
||||
}
|
||||
|
||||
use base64::prelude::*;
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -6,10 +6,6 @@ use std::task::{Context, Poll};
|
||||
|
||||
use base64::prelude::*;
|
||||
use futures::prelude::*;
|
||||
#[cfg(not(feature = "rug"))]
|
||||
use num_bigint::BigUint;
|
||||
#[cfg(not(feature = "rug"))]
|
||||
use num_traits::One;
|
||||
use rand::RngExt;
|
||||
#[cfg(feature = "rug")]
|
||||
use rug::Integer;
|
||||
@@ -29,6 +25,14 @@ use crate::resend::{PacketId, ResenderState};
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// Sets the shared flag when dropped, to stop a background computation.
|
||||
#[derive(Default)]
|
||||
struct CancelOnDrop(std::sync::Arc<std::sync::atomic::AtomicBool>);
|
||||
|
||||
impl Drop for CancelOnDrop {
|
||||
fn drop(&mut self) { self.0.store(true, std::sync::atomic::Ordering::Relaxed); }
|
||||
}
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
@@ -284,8 +288,7 @@ impl Client {
|
||||
S2CInitData::Init3 { x, n, level, random2 } => {
|
||||
let level = *level;
|
||||
// Solve RSA puzzle: y = x ^ (2 ^ level) % n
|
||||
// Use Montgomery Reduction
|
||||
if level > 10_000_000 {
|
||||
if level > algs::max_puzzle_level() {
|
||||
// Reject too high exponents
|
||||
return Err(Error::RsaPuzzleTooHighLevel(level));
|
||||
}
|
||||
@@ -315,15 +318,20 @@ impl Client {
|
||||
yi
|
||||
};
|
||||
|
||||
// Montgomery squarings on a blocking thread, so high
|
||||
// (TeamSpeak 6 adaptive) levels do not stall the runtime.
|
||||
// Dropping the connect future cancels the computation.
|
||||
#[cfg(not(feature = "rug"))]
|
||||
let y = {
|
||||
let xi = BigUint::from_bytes_be(&x);
|
||||
let ni = BigUint::from_bytes_be(&n);
|
||||
let e = BigUint::one() << level as usize;
|
||||
let yi = xi.modpow(&e, &ni);
|
||||
info!(parent: &self.con.span, level, x = %xi, n = %ni, y = %yi,
|
||||
"Solve RSA puzzle");
|
||||
algs::biguint_to_array(&yi)
|
||||
info!(parent: &self.con.span, level, "Solving RSA puzzle");
|
||||
let cancel = CancelOnDrop::default();
|
||||
let flag = cancel.0.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
algs::solve_rsa_puzzle(&x, &n, level, Some(&flag))
|
||||
})
|
||||
.await
|
||||
.map_err(|_| Error::RsaPuzzle)?
|
||||
.ok_or(Error::RsaPuzzle)?
|
||||
};
|
||||
|
||||
// Create the command string
|
||||
|
||||
Reference in new issue
Block a user