Skip to main content

ghast_auth/
chat.rs

1//! Signed chat (Minecraft 1.19.3+ chat sessions): the player's profile key pair and the message
2//! signature chain of a chat session.
3//!
4//! An online-mode client fetches a **profile key pair** from the Minecraft services
5//! (`MicrosoftAuth::profile_keys` with the `microsoft` feature, or bring your own with
6//! [`ProfileKeys::from_der`]), starts a **chat session** (a random session id, announced to the
7//! server with the public key, its expiry and the services' signature over them), and signs
8//! every chat message and every signable command argument with the private key
9//! (SHA256withRSA, PKCS#1 v1.5 — deterministic, so the same input gives the same bytes as the
10//! vanilla client).
11//!
12//! The signed data of one message (`PlayerChatMessage.updateSignature` in 26.1): the version
13//! `1` (i32), the link (sender profile id, session id, index), the body (salt, timestamp in
14//! **seconds**, content length and UTF-8 bytes, the count and the bytes of the last-seen
15//! signatures), all big-endian. [`SignedMessageChain::sign`] builds it straight into the hash.
16//!
17//! This module does no I/O and knows no packets: the client crate puts the results into
18//! `chat_session_update`, `chat_message` and `chat_command_signed`.
19
20use std::fmt;
21use std::time::{Duration, SystemTime, UNIX_EPOCH};
22
23use rsa::pkcs8::{DecodePrivateKey, DecodePublicKey};
24use rsa::traits::PublicKeyParts;
25use rsa::{Pkcs1v15Sign, RsaPrivateKey, RsaPublicKey};
26use sha2::{Digest, Sha256};
27use thiserror::Error;
28use uuid::Uuid;
29
30/// DER `DigestInfo` prefix of SHA-256 (RFC 8017 §9.2, note 1).
31const SHA256_PREFIX: [u8; 19] = [
32    0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
33    0x00, 0x04, 0x20,
34];
35
36/// Errors of [`ProfileKeys`].
37#[derive(Debug, Error)]
38#[non_exhaustive]
39pub enum ChatKeyError {
40    /// The private key is not a PKCS#8 RSA key.
41    #[error("invalid private key: {0}")]
42    InvalidPrivateKey(String),
43    /// The public key is not a DER `SubjectPublicKeyInfo` RSA key.
44    #[error("invalid public key: {0}")]
45    InvalidPublicKey(String),
46    /// The public key does not belong to the private key.
47    #[error("the public key does not match the private key")]
48    KeyMismatch,
49    /// Signing failed.
50    #[error("signing failed: {0}")]
51    Sign(#[source] rsa::Error),
52}
53
54/// A profile key pair: what the Minecraft services issue for signed chat (valid for about two
55/// days; vanilla fetches a new one once [`ProfileKeys::due_refresh`]).
56///
57/// `Debug` does not print the private key.
58#[derive(Clone)]
59pub struct ProfileKeys {
60    private: RsaPrivateKey,
61    public_der: Vec<u8>,
62    key_signature: Vec<u8>,
63    expires_at: SystemTime,
64    refreshed_after: SystemTime,
65}
66
67impl ProfileKeys {
68    /// A key pair from its parts: the PKCS#8 DER private key, the DER `SubjectPublicKeyInfo`
69    /// public key, the services' signature over the public key (`publicKeySignatureV2`), when
70    /// it expires and when it should be refreshed.
71    pub fn from_der(
72        private_pkcs8: &[u8],
73        public_spki: &[u8],
74        key_signature: Vec<u8>,
75        expires_at: SystemTime,
76        refreshed_after: SystemTime,
77    ) -> Result<Self, ChatKeyError> {
78        let private = RsaPrivateKey::from_pkcs8_der(private_pkcs8)
79            .map_err(|e| ChatKeyError::InvalidPrivateKey(e.to_string()))?;
80        let public = RsaPublicKey::from_public_key_der(public_spki)
81            .map_err(|e| ChatKeyError::InvalidPublicKey(e.to_string()))?;
82        if public.n() != private.n() || public.e() != private.e() {
83            return Err(ChatKeyError::KeyMismatch);
84        }
85        Ok(Self {
86            private,
87            public_der: public_spki.to_vec(),
88            key_signature,
89            expires_at,
90            refreshed_after,
91        })
92    }
93
94    /// The public key as DER `SubjectPublicKeyInfo` (sent in `chat_session_update`).
95    #[must_use]
96    pub fn public_key_der(&self) -> &[u8] {
97        &self.public_der
98    }
99
100    /// The services' signature over the profile id, the expiry and the public key.
101    #[must_use]
102    pub fn key_signature(&self) -> &[u8] {
103        &self.key_signature
104    }
105
106    /// When the key expires (servers refuse it afterwards).
107    #[must_use]
108    pub fn expires_at(&self) -> SystemTime {
109        self.expires_at
110    }
111
112    /// The expiry in milliseconds since the Unix epoch (its wire form).
113    #[must_use]
114    pub fn expires_at_millis(&self) -> i64 {
115        millis(self.expires_at)
116    }
117
118    /// When the services want the key replaced.
119    #[must_use]
120    pub fn refreshed_after(&self) -> SystemTime {
121        self.refreshed_after
122    }
123
124    /// `ProfileKeyPair.dueRefresh`: the refresh time has passed.
125    #[must_use]
126    pub fn due_refresh(&self) -> bool {
127        SystemTime::now() > self.refreshed_after
128    }
129
130    /// The key has expired (or does so within `margin`).
131    #[must_use]
132    pub fn expires_within(&self, margin: Duration) -> bool {
133        SystemTime::now()
134            .checked_add(margin)
135            .is_none_or(|t| t >= self.expires_at)
136    }
137
138    /// The signature length in bytes (the modulus size; 256 for the services' 2048-bit keys).
139    #[must_use]
140    pub fn signature_len(&self) -> usize {
141        self.private.size()
142    }
143
144    /// SHA256withRSA over everything `feed` passes to the hasher.
145    fn sign_with(&self, feed: impl FnOnce(&mut Sha256)) -> Result<Vec<u8>, ChatKeyError> {
146        let mut h = Sha256::new();
147        feed(&mut h);
148        let digest = h.finalize();
149        let scheme = Pkcs1v15Sign {
150            hash_len: Some(32),
151            prefix: Box::new(SHA256_PREFIX),
152        };
153        self.private
154            .sign(scheme, &digest[..])
155            .map_err(ChatKeyError::Sign)
156    }
157
158    /// SHA256withRSA over `data` (`Signer.from(privateKey, "SHA256withRSA")`).
159    pub fn sign(&self, data: &[u8]) -> Result<Vec<u8>, ChatKeyError> {
160        self.sign_with(|h| h.update(data))
161    }
162}
163
164impl fmt::Debug for ProfileKeys {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        f.debug_struct("ProfileKeys")
167            .field("bits", &(self.private.size() * 8))
168            .field("expires_at_ms", &self.expires_at_millis())
169            .finish_non_exhaustive()
170    }
171}
172
173fn millis(t: SystemTime) -> i64 {
174    match t.duration_since(UNIX_EPOCH) {
175        Ok(d) => i64::try_from(d.as_millis()).unwrap_or(i64::MAX),
176        Err(e) => -i64::try_from(e.duration().as_millis()).unwrap_or(i64::MAX),
177    }
178}
179
180/// One chat session's signature chain (`SignedMessageChain` with its encoder): every signed
181/// message takes the next index of the link (sender, session id, index).
182#[derive(Debug, Clone)]
183pub struct SignedMessageChain {
184    profile_id: Uuid,
185    session_id: Uuid,
186    /// The next link's index; `None` once the chain is exhausted (`Integer.MAX_VALUE`).
187    next: Option<i32>,
188}
189
190impl SignedMessageChain {
191    /// A new chain at index 0 (`SignedMessageLink.root`).
192    #[must_use]
193    pub fn new(profile_id: Uuid, session_id: Uuid) -> Self {
194        Self {
195            profile_id,
196            session_id,
197            next: Some(0),
198        }
199    }
200
201    /// The session id.
202    #[must_use]
203    pub fn session_id(&self) -> Uuid {
204        self.session_id
205    }
206
207    /// The index the next signed message gets.
208    #[must_use]
209    pub fn next_index(&self) -> Option<i32> {
210        self.next
211    }
212
213    /// Signs one message body and advances the chain (`SignedMessageChain.Encoder.pack`).
214    /// `timestamp_millis` is the packet's timestamp (the signature covers its whole seconds);
215    /// `last_seen` are the acknowledged signatures in the order of the update. `None` once the
216    /// chain is exhausted (vanilla then sends the message unsigned).
217    pub fn sign<'a>(
218        &mut self,
219        keys: &ProfileKeys,
220        content: &str,
221        timestamp_millis: i64,
222        salt: i64,
223        last_seen: impl ExactSizeIterator<Item = &'a [u8]>,
224    ) -> Result<Option<Vec<u8>>, ChatKeyError> {
225        let Some(index) = self.next else {
226            return Ok(None);
227        };
228        self.next = index.checked_add(1);
229        let (profile, session) = (self.profile_id, self.session_id);
230        keys.sign_with(|h| {
231            h.update(1i32.to_be_bytes());
232            h.update(profile.as_bytes());
233            h.update(session.as_bytes());
234            h.update(index.to_be_bytes());
235            h.update(salt.to_be_bytes());
236            // Instant.getEpochSecond: floor division.
237            h.update(timestamp_millis.div_euclid(1000).to_be_bytes());
238            let bytes = content.as_bytes();
239            h.update((bytes.len() as i32).to_be_bytes());
240            h.update(bytes);
241            h.update((last_seen.len() as i32).to_be_bytes());
242            for sig in last_seen {
243                h.update(sig);
244            }
245        })
246        .map(Some)
247    }
248}
249
250/// The payload the services sign for a profile key (`ProfilePublicKey.Data.signedPayload`): the
251/// profile id, the expiry in milliseconds and the DER public key. For checking a key or for a
252/// local test key service.
253#[must_use]
254pub fn profile_key_payload(
255    profile_id: Uuid,
256    expires_at_millis: i64,
257    public_spki: &[u8],
258) -> Vec<u8> {
259    let mut v = Vec::with_capacity(24 + public_spki.len());
260    v.extend_from_slice(profile_id.as_bytes());
261    v.extend_from_slice(&expires_at_millis.to_be_bytes());
262    v.extend_from_slice(public_spki);
263    v
264}
265
266/// Decodes the base64 body of a PEM block (`-----BEGIN …-----`, MIME line breaks), as the
267/// services send the key pair (`Crypt.rsaStringToKey`).
268pub fn pem_body(pem: &str) -> Option<Vec<u8>> {
269    let mut body = String::with_capacity(pem.len());
270    for line in pem.lines() {
271        let line = line.trim();
272        if line.starts_with("-----") || line.is_empty() {
273            continue;
274        }
275        body.push_str(line);
276    }
277    base64_decode(&body)
278}
279
280/// Standard base64 (padding optional, no whitespace).
281pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
282    fn val(c: u8) -> Option<u32> {
283        Some(match c {
284            b'A'..=b'Z' => c - b'A',
285            b'a'..=b'z' => c - b'a' + 26,
286            b'0'..=b'9' => c - b'0' + 52,
287            b'+' => 62,
288            b'/' => 63,
289            _ => return None,
290        } as u32)
291    }
292    let s = s.trim_end_matches('=').as_bytes();
293    let mut out = Vec::with_capacity(s.len() * 3 / 4);
294    for chunk in s.chunks(4) {
295        let mut acc = 0u32;
296        for (i, &c) in chunk.iter().enumerate() {
297            acc |= val(c)? << (18 - 6 * i);
298        }
299        match chunk.len() {
300            4 => out.extend_from_slice(&[(acc >> 16) as u8, (acc >> 8) as u8, acc as u8]),
301            3 => out.extend_from_slice(&[(acc >> 16) as u8, (acc >> 8) as u8]),
302            2 => out.push((acc >> 16) as u8),
303            _ => return None,
304        }
305    }
306    Some(out)
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312
313    #[test]
314    fn base64_round_trips_known_values() {
315        assert_eq!(base64_decode("").unwrap(), b"");
316        assert_eq!(base64_decode("Zg==").unwrap(), b"f");
317        assert_eq!(base64_decode("Zm8").unwrap(), b"fo");
318        assert_eq!(base64_decode("Zm9vYmFy").unwrap(), b"foobar");
319        assert!(base64_decode("Zm9v!").is_none());
320        let pem = "-----BEGIN RSA PUBLIC KEY-----\nZm9v\nYmFy\n-----END RSA PUBLIC KEY-----\n";
321        assert_eq!(pem_body(pem).unwrap(), b"foobar");
322    }
323
324    #[test]
325    fn chain_stops_at_the_last_index() {
326        let mut c = SignedMessageChain::new(Uuid::nil(), Uuid::nil());
327        c.next = Some(i32::MAX);
328        assert_eq!(c.next_index(), Some(i32::MAX));
329        // The index after MAX does not exist: the chain ends after this one.
330        assert_eq!(i32::MAX.checked_add(1), None);
331    }
332}