Dedicated server: online mode, and refused logins in the log

online-mode=true now authenticates players as vanilla's
ServerLoginPacketListenerImpl does. The server makes a 1024-bit RSA key
pair at startup ("Generating keypair"), sends it with a random challenge,
checks the challenge and decrypts the shared secret from the client's key
packet, encrypts the connection with AES/CFB8, and asks the session
service's verify endpoint (hasJoined, through the services discovery
document) whether the player joined with the server's hash, from the
"User Authenticator #N" thread. A verified profile keeps its UUID and
properties, so skins show in the player list; an unverified one is
refused with "Failed to verify username!", and an unreachable service
with authservers_down. The offline-mode warnings are only printed in
offline mode.

Refused logins are logged as vanilla logs them: "Disconnecting
<name> (/<address>): <reason>" and "<name> (/<address>) lost
connection: <reason>", with log-ips respected.

horizon-protocol gains RSA key generation (Miller-Rabin primes,
e = 65537), the X.509 encoding of the public key and PKCS#1 v1.5
decryption. test_online_mode_parity.py runs its logins against Horizon's
server too, plus a verified player the whitelist refuses, and compares
the two servers' log lines about the player.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-16 22:59:36 +02:00
parent f535d1b48c
commit e7003e7d49
10 changed files with 713 additions and 64 deletions
+279 -1
View File
@@ -1,7 +1,9 @@
//! RSA for the online-mode login: the server's X.509 public key
//! (Crypt.byteToPublicKey) and PKCS#1 v1.5 encryption of the shared secret
//! and challenge (Crypt.encryptUsingKey, Java's "RSA" cipher =
//! RSA/ECB/PKCS1Padding). Modular exponentiation uses Montgomery
//! RSA/ECB/PKCS1Padding), and on the server's side the key pair it makes at
//! startup (Crypt.generateKeyPair: 1024 bits) and the decryption
//! (Crypt.decryptUsingKey). Modular exponentiation uses Montgomery
//! multiplication on 32-bit limbs; RSA moduli are always odd.
use crate::{Error, Result};
@@ -43,6 +45,46 @@ impl Big {
}
true
}
/// self · other, as many limbs as both together.
fn mul(&self, other: &Self) -> Self {
let mut out = vec![0u32; self.0.len() + other.0.len()];
for (i, &a) in self.0.iter().enumerate() {
let mut carry = 0u64;
for (j, &b) in other.0.iter().enumerate() {
let t = u64::from(out[i + j]) + u64::from(a) * u64::from(b) + carry;
out[i + j] = t as u32;
carry = t >> 32;
}
out[i + other.0.len()] = carry as u32;
}
Self(out)
}
/// self · m + a, one limb longer.
fn mul_small_add(&self, m: u32, a: u32) -> Self {
let mut out = Vec::with_capacity(self.0.len() + 1);
let mut carry = u64::from(a);
for &l in &self.0 {
let t = u64::from(l) * u64::from(m) + carry;
out.push(t as u32);
carry = t >> 32;
}
out.push(carry as u32);
Self(out)
}
/// (self / d, self mod d).
fn div_small(&self, d: u32) -> (Self, u32) {
let mut out = vec![0u32; self.0.len()];
let mut rem = 0u64;
for i in (0..self.0.len()).rev() {
let t = rem << 32 | u64::from(self.0[i]);
out[i] = (t / u64::from(d)) as u32;
rem = t % u64::from(d);
}
(Self(out), rem as u32)
}
fn is_one(&self) -> bool {
self.0.first() == Some(&1) && self.0[1..].iter().all(|&l| l == 0)
}
fn sub_assign(&mut self, other: &Self) {
let mut borrow = 0i64;
for (a, b) in self.0.iter_mut().zip(&other.0) {
@@ -249,6 +291,198 @@ impl RsaPublicKey {
}
}
/// Small odd primes for sieving prime candidates.
const SMALL_PRIMES: [u32; 53] = [
3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193,
197, 199, 211, 223, 227, 229, 233, 239, 241, 251,
];
/// Miller-Rabin rounds: a composite passes all of them with odds below 2⁻⁸⁰.
const ROUNDS: usize = 40;
const E: u32 = 65537;
/// A random odd number of `limbs` limbs with its two top bits set, so two of
/// them multiply to exactly twice the bits.
fn candidate(limbs: usize) -> Result<Big> {
let mut bytes = vec![0u8; limbs * 4];
crate::crypto::random_bytes(&mut bytes)?;
bytes[0] |= 0xC0;
bytes[limbs * 4 - 1] |= 1;
Ok(Big::from_be_bytes(&bytes, limbs))
}
/// Miller-Rabin with random bases.
fn probably_prime(p: &Big) -> Result<bool> {
if SMALL_PRIMES.iter().any(|&q| p.div_small(q).1 == 0) {
return Ok(false);
}
let k = p.0.len();
let mont = Mont::new(p.clone());
let mut p_minus_one = p.clone();
p_minus_one.0[0] -= 1; // p is odd
let s = (0..k * 32).find(|&i| p_minus_one.bit(i)).unwrap_or(0);
// d = (p - 1) >> s
let mut d = Big(vec![0; k]);
for i in 0..k * 32 - s {
if p_minus_one.bit(i + s) {
d.0[i / 32] |= 1 << (i % 32);
}
}
let mut two = Big(vec![0; k]);
two.0[0] = 2;
'rounds: for _ in 0..ROUNDS {
// A random base in [2, p - 2].
let mut a = candidate(k)?;
a.0[k - 1] %= p.0[k - 1];
if !a.ge(&two) || a.ge(&p_minus_one) {
continue;
}
let mut x = mont.pow(&a, &d);
if x.is_one() || x == p_minus_one {
continue;
}
for _ in 1..s {
x = mont.pow(&x, &two);
if x == p_minus_one {
continue 'rounds;
}
if x.is_one() {
return Ok(false);
}
}
return Ok(false);
}
Ok(true)
}
/// A prime of `limbs` limbs whose p - 1 is prime to E.
fn prime(limbs: usize) -> Result<Big> {
loop {
let p = candidate(limbs)?;
if p.div_small(E).1 != 1 && probably_prime(&p)? {
return Ok(p);
}
}
}
/// DER: a tag and its length, then the contents.
fn der_element(tag: u8, contents: &[u8]) -> Vec<u8> {
let mut out = vec![tag];
let len = contents.len();
if len < 0x80 {
out.push(len as u8);
} else {
let bytes: Vec<u8> = len
.to_be_bytes()
.into_iter()
.skip_while(|&b| b == 0)
.collect();
out.push(0x80 | bytes.len() as u8);
out.extend(bytes);
}
out.extend_from_slice(contents);
out
}
/// A DER INTEGER from big-endian magnitude bytes (a leading zero keeps it positive).
fn der_integer(magnitude: &[u8]) -> Vec<u8> {
let mut v = strip(magnitude);
if v.first().is_none_or(|b| b & 0x80 != 0) {
v.insert(0, 0);
}
der_element(0x02, &v)
}
/// The server's key pair (Crypt.generateKeyPair).
pub struct RsaPrivateKey {
pub public: RsaPublicKey,
/// The private exponent, big-endian.
exponent: Vec<u8>,
}
impl std::fmt::Debug for RsaPrivateKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RsaPrivateKey")
.field("public", &self.public)
.finish_non_exhaustive()
}
}
impl RsaPrivateKey {
/// A new key pair with a `bits`-bit modulus (a multiple of 64) and
/// public exponent 65537, as Java's RSA KeyPairGenerator makes.
pub fn generate(bits: usize) -> Result<Self> {
let limbs = bits / 64;
let p = prime(limbs)?;
let q = loop {
let q = prime(limbs)?;
if q != p {
break q;
}
};
let n = p.mul(&q);
// d = (1 + k·φ) / E with k making it whole: k ≡ -φ⁻¹ (mod E).
let (mut p1, mut q1) = (p, q);
p1.0[0] -= 1;
q1.0[0] -= 1;
let phi = p1.mul(&q1);
let r = u64::from(phi.div_small(E).1);
let inverse = (1..u64::from(E))
.find(|k| k * r % u64::from(E) == 1)
.ok_or_else(|| Error::new("RSA key generation failed"))?;
let k = (u64::from(E) - inverse) as u32;
let (d, rem) = phi.mul_small_add(k, 1).div_small(E);
if rem != 0 {
return Err(Error::new("RSA key generation failed"));
}
let size = bits / 8;
Ok(Self {
public: RsaPublicKey {
modulus: strip(&n.to_be_bytes(size)),
exponent: strip(&E.to_be_bytes()),
},
exponent: d.to_be_bytes(size),
})
}
/// PublicKey.getEncoded: X.509 SubjectPublicKeyInfo.
pub fn public_der(&self) -> Vec<u8> {
let key = der_element(
0x30,
&[
der_integer(&self.public.modulus),
der_integer(&self.public.exponent),
]
.concat(),
);
let algorithm = der_element(
0x30,
&[der_element(0x06, RSA_ENCRYPTION), vec![0x05, 0x00]].concat(),
);
let bits = der_element(0x03, &[&[0u8][..], &key].concat());
der_element(0x30, &[algorithm, bits].concat())
}
/// Crypt.decryptUsingKey: RSAES-PKCS1-v1_5 decryption (RFC 8017 7.2.2).
pub fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>> {
let bad = || Error::new("Decryption error");
let k = self.public.size();
// The modulus has no leading zero, so equal lengths compare as numbers.
if ciphertext.len() != k || ciphertext >= self.public.modulus.as_slice() {
return Err(bad());
}
let block = self.public.apply(ciphertext, &self.exponent);
if block[0] != 0 || block[1] != 2 {
return Err(bad());
}
let zero = block[2..].iter().position(|&b| b == 0).ok_or_else(bad)? + 2;
if zero < 10 {
return Err(bad());
}
Ok(block[zero + 1..].to_vec())
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
@@ -316,6 +550,50 @@ pub(crate) mod tests {
assert!(key.encrypt(&[0; 118]).is_err());
}
/// A key made here: Java-style DER that parses back, and what its public
/// half encrypts its private half decrypts.
#[test]
fn generated_keys_round_trip() {
let key = RsaPrivateKey::generate(1024).unwrap();
assert_eq!(key.public.size(), 128);
assert_eq!(key.public.exponent, vec![1, 0, 1]);
let der = key.public_der();
assert_eq!(
&der[..3],
&[0x30, 0x81, 0x9f],
"a 1024-bit SubjectPublicKeyInfo"
);
assert_eq!(RsaPublicKey::from_der(&der).unwrap(), key.public);
for message in [&[0x5au8; 16][..], &[1, 2, 3, 4], &[]] {
let c = key.public.encrypt(message).unwrap();
assert_eq!(key.decrypt(&c).unwrap(), message);
}
assert!(key.decrypt(&[0u8; 128]).is_err());
assert!(key.decrypt(&[1u8; 64]).is_err());
}
#[test]
fn decrypts_with_a_known_key() {
let key = RsaPrivateKey {
public: RsaPublicKey::from_der(&hex(TEST_SPKI)).unwrap(),
exponent: hex(TEST_D),
};
let c = key.public.encrypt(b"secret").unwrap();
assert_eq!(key.decrypt(&c).unwrap(), b"secret");
}
#[test]
fn finds_primes() {
let p = Big(vec![0xFFFF_FFFB]); // 2^32 - 5 is prime
assert!(probably_prime(&p).unwrap());
assert!(!probably_prime(&Big(vec![0xFFFF_FFFD])).unwrap()); // 3 · 1431655765
// 2^61 - 1 (prime) and a Carmichael-free composite 2^61 + 1.
let m61 = (1u64 << 61) - 1;
assert!(probably_prime(&Big(vec![m61 as u32, (m61 >> 32) as u32])).unwrap());
let c = (1u64 << 61) + 1;
assert!(!probably_prime(&Big(vec![c as u32, (c >> 32) as u32])).unwrap());
}
/// An OpenSSL signature checked with the public exponent: the block ends
/// with SHA-256("hello"), so the modular arithmetic agrees with OpenSSL's.
#[test]