Skip to main content

eq_network_game/
p99.rs

1use anyhow::{ensure, Context, Result};
2use num_bigint::BigUint;
3use rand::RngCore;
4use zeroize::{Zeroize, ZeroizeOnDrop};
5
6/// The legacy application header participates in the V62 digest. Its length
7/// includes the four-byte opcode/length header, unlike the UDP payload length.
8///
9/// # Errors
10///
11/// Returns an error when the complete application length exceeds `u16`.
12pub fn packet_digest(opcode: u16, body: &[u8]) -> Result<[u8; 16]> {
13    let length = u16::try_from(body.len() + 4).context("application digest length overflow")?;
14    let mut digest = md5::Context::new();
15    digest.consume(opcode.to_le_bytes());
16    digest.consume(length.to_le_bytes());
17    digest.consume(body);
18    Ok(digest.compute().0)
19}
20
21/// Stateful Titanium/P99-V62 codec for world approval and file validation.
22#[derive(Zeroize, ZeroizeOnDrop)]
23pub struct WorldCodec {
24    key: [u8; 16],
25    incoming: Option<[u8; 16]>,
26    outgoing: Option<[u8; 16]>,
27}
28
29impl WorldCodec {
30    /// Derive the initial world codec key from the exact login-info packet.
31    ///
32    /// # Errors
33    ///
34    /// Returns an error unless `login_info` has the 464-byte Titanium layout.
35    pub fn new(login_info: &[u8]) -> Result<Self> {
36        ensure!(login_info.len() == 464, "invalid Titanium world login size");
37        Ok(Self {
38            key: md5::compute(login_info).0,
39            incoming: None,
40            outgoing: None,
41        })
42    }
43
44    /// Answer the world's approval challenge and initialize rolling state.
45    ///
46    /// # Errors
47    ///
48    /// Returns an error when the challenge is malformed or contains unsupported
49    /// public-key values.
50    pub fn approve(&mut self, challenge: &[u8]) -> Result<Vec<u8>> {
51        ensure!(
52            challenge.len() == 544,
53            "unexpected world approval challenge size"
54        );
55        let bigint = |bytes: &[u8]| -> Result<BigUint> {
56            let count = bytes.get(268..272).context("truncated approval integer")?;
57            let words = usize::try_from(u32::from_le_bytes(count.try_into()?))?;
58            ensure!((1..=64).contains(&words), "invalid world approval integer");
59            let integer = bytes
60                .get(8..8 + words * 4)
61                .context("truncated approval integer words")?;
62            Ok(BigUint::from_bytes_le(integer))
63        };
64        let modulus = bigint(challenge.get(..272).context("missing approval modulus")?)?;
65        let exponent = bigint(challenge.get(272..).context("missing approval exponent")?)?;
66        ensure!(
67            modulus.bits() >= 64 && exponent.bits() > 0,
68            "invalid world approval public key"
69        );
70        // A zero nonce encodes to zero words, which the Titanium vlong header
71        // cannot represent. Setting the low bit guarantees a nonzero value.
72        let random = BigUint::from(rand::thread_rng().next_u64() | 1);
73        let encrypted = random.modpow(&exponent, &modulus).to_bytes_le();
74        ensure!(encrypted.len() <= 256, "approval integer too large");
75        let mut body = vec![0; 272];
76        body[8..8 + encrypted.len()].copy_from_slice(&encrypted);
77        let words = u32::try_from(encrypted.len().div_ceil(4))?;
78        // Titanium's vlong multiplication allocates 2*n-1 words.
79        body[264..268].copy_from_slice(&(words * 2 - 1).to_le_bytes());
80        body[268..272].copy_from_slice(&words.to_le_bytes());
81        self.encode_approval(&mut body)?;
82        Ok(body)
83    }
84
85    /// Encode an approval body and seed the incoming manifest decoder.
86    ///
87    /// # Errors
88    ///
89    /// Returns an error unless `body` has the 272-byte approval layout.
90    pub fn encode_approval(&mut self, body: &mut [u8]) -> Result<()> {
91        ensure!(body.len() == 272, "invalid approval response size");
92        body[..9].fill(0);
93        let seed = packet_digest(0x3c25, body)?;
94        body[..8].fill(0xff);
95        body[8] = 1;
96        self.incoming = Some(packet_digest(0x52a4, body)?);
97        encode(&mut body[..9], &self.key, &seed);
98        Ok(())
99    }
100
101    /// Decode the world manifest and seed its checksum response encoder.
102    ///
103    /// # Errors
104    ///
105    /// Returns an error when approval has not initialized the incoming state.
106    pub fn manifest(&mut self, body: &mut [u8]) -> Result<()> {
107        let seed = self.incoming.context("manifest arrived before approval")?;
108        decode(body, &self.key, &seed);
109        self.outgoing = Some(packet_digest(0x1251, body)?);
110        Ok(())
111    }
112
113    /// Encode a world or zone file-checksum response with rolling state.
114    ///
115    /// # Errors
116    ///
117    /// Returns an error when no manifest has initialized the outgoing state.
118    pub fn file_response(&self, body: &mut [u8]) -> Result<()> {
119        let seed = self.outgoing.context("file response before manifest")?;
120        encode(body, &self.key, &seed);
121        Ok(())
122    }
123
124    /// Decode the file manifest embedded in a world-to-zone handoff.
125    ///
126    /// # Errors
127    ///
128    /// Returns an error when the handoff is too short or its digest input is too large.
129    pub fn zone_manifest(&self, handoff: &[u8]) -> Result<Vec<u8>> {
130        ensure!(handoff.len() > 130, "zone handoff has no file manifest");
131        let mut header = handoff.to_vec();
132        header[130..].fill(0);
133        let seed = packet_digest(0x61b6, &header)?;
134        let mut manifest = handoff[130..].to_vec();
135        decode(&mut manifest, &self.key, &seed);
136        Ok(manifest)
137    }
138
139    /// Rekey the codec for a new zone from the zone-entry packet.
140    ///
141    /// # Errors
142    ///
143    /// Returns an error unless `entry` has the 68-byte Titanium layout.
144    pub fn zone_entry(&mut self, entry: &[u8]) -> Result<()> {
145        ensure!(entry.len() == 68, "invalid Titanium zone entry size");
146        self.key = md5::compute(entry).0;
147        self.outgoing = None;
148        Ok(())
149    }
150
151    /// Seed the zone checksum encoder from the decoded player spawn.
152    ///
153    /// # Errors
154    ///
155    /// Returns an error unless `body` has the 385-byte Titanium layout.
156    pub fn zone_spawn(&mut self, body: &[u8]) -> Result<()> {
157        ensure!(body.len() == 385, "unexpected Titanium player spawn size");
158        self.outgoing = Some(packet_digest(0x7213, body)?);
159        Ok(())
160    }
161}
162
163/// XOR permutation used by the V62 application codec. Zero and the key byte
164/// are fixed points, so neither C string terminators nor nonzero bytes vanish.
165const fn xor_nonzero(value: u8, key: u8) -> u8 {
166    if value == 0 || value == key {
167        value
168    } else {
169        value ^ key
170    }
171}
172
173/// Encode an application body with its session key and outgoing rolling state.
174///
175/// The first byte is unchanged. Each lane remembers the next nonzero plaintext
176/// byte, starting at the end of the body with the supplied 16-byte state.
177pub fn encode(body: &mut [u8], key: &[u8; 16], seed: &[u8; 16]) {
178    let mut rolling = *seed;
179    for i in (1..body.len()).rev() {
180        let plain = body[i];
181        if plain != 0 {
182            body[i] = xor_nonzero(xor_nonzero(plain, key[i % 16]), rolling[i % 16]);
183            rolling[i % 16] = plain;
184        }
185    }
186}
187
188/// Reverse the application codec, retaining the exact original bytes.
189pub fn decode(body: &mut [u8], key: &[u8; 16], seed: &[u8; 16]) {
190    let mut rolling = *seed;
191    for i in (1..body.len()).rev() {
192        if body[i] != 0 {
193            body[i] = xor_nonzero(xor_nonzero(body[i], rolling[i % 16]), key[i % 16]);
194            rolling[i % 16] = body[i];
195        }
196    }
197}
198
199/// CRC1 uses the login server's ten-byte session key, independently of the
200/// world approval digests. The same permutation encodes and decodes it.
201///
202/// # Errors
203///
204/// Returns an error when the session key is empty.
205pub fn session_xor(body: &mut [u8], session_key: &[u8]) -> Result<()> {
206    ensure!(!session_key.is_empty(), "missing login session key");
207    for (index, byte) in body.iter_mut().enumerate() {
208        *byte = xor_nonzero(*byte, session_key[index % session_key.len()]);
209    }
210    Ok(())
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn zero_key_oracle_vector_skips_empty_lane_entries() {
219        // Measured from the isolated current V62 encoder using zero keys and
220        // synthetic bytes 0..357. The zero at offset 256 is skipped in its lane.
221        let mut body: Vec<u8> = (0..=u8::MAX).cycle().take(358).collect();
222        encode(&mut body, &[0; 16], &[0; 16]);
223        assert_eq!(
224            &body[..16],
225            &[0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16]
226        );
227        assert_eq!(body[240], 224);
228        assert_eq!(body[256], 0);
229        assert_eq!(&body[342..], &(86..102).collect::<Vec<u8>>());
230    }
231
232    #[test]
233    fn inverse_preserves_all_byte_values_and_terminators() {
234        let key = std::array::from_fn(|i| u8::try_from(i * 17).unwrap());
235        let seed = std::array::from_fn(|i| u8::try_from(i * 13 + 19).unwrap());
236        for length in [0, 1, 15, 16, 17, 358, 996, 2056] {
237            let plain: Vec<u8> = (0..=u8::MAX).cycle().take(length).collect();
238            let mut body = plain.clone();
239            encode(&mut body, &key, &seed);
240            assert!(body.iter().zip(&plain).all(|(a, b)| (*a == 0) == (*b == 0)));
241            decode(&mut body, &key, &seed);
242            assert_eq!(body, plain);
243        }
244    }
245}