mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-22 03:25:56 +00:00
Phase 12: control protocol crate (Noise channel, coordinator frames, app messages) and Coordinator service
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
95ab5dd9ef
commit
6fa3c9ccf4
14 files changed
+3982
-2
No files matched your search
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "coa-control-proto"
|
||||
description = "Player <-> Host control protocol (Phase 12): coordinator framing, the end-to-end Noise channel, identity binding and the application messages. No I/O."
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "AGPL-3.0-only"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
coa-registry-proto = { path = "../coa-registry-proto" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
base64 = "0.22"
|
||||
ed25519-dalek = "2"
|
||||
snow = "0.9"
|
||||
thiserror = "2"
|
||||
uuid = { version = "1", features = ["serde", "v4", "v7"] }
|
||||
@@ -0,0 +1,210 @@
|
||||
//! The application messages inside the end-to-end channel. One request, one response, in order. Nothing here is ever visible to the Coordinator.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{invalid, ControlError, Result};
|
||||
|
||||
pub const MAX_REQUEST_BYTES: usize = 4096;
|
||||
pub const MIN_USERNAME: usize = 3;
|
||||
pub const MAX_USERNAME: usize = 16;
|
||||
pub const MIN_PASSWORD: usize = 8;
|
||||
pub const MAX_PASSWORD: usize = 16;
|
||||
pub const MAX_CHARACTERS: usize = 200;
|
||||
|
||||
/// A game account name: 3 to 16 ASCII letters, digits or `_`, not beginning or ending with `_`.
|
||||
pub fn valid_username(s: &str) -> bool {
|
||||
(MIN_USERNAME..=MAX_USERNAME).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') && !s.starts_with('_') && !s.ends_with('_')
|
||||
}
|
||||
|
||||
/// A game account password: 8 to 16 ASCII letters and digits (the game compares passwords case-insensitively, so letters carry no extra strength; digits and length do).
|
||||
pub fn valid_password(s: &str) -> bool {
|
||||
(MIN_PASSWORD..=MAX_PASSWORD).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric())
|
||||
}
|
||||
|
||||
/// A password for a realm, 16 characters of `A-Z0-9` from the operating system's randomness (about 82 bits), unique per realm.
|
||||
pub fn generate_password() -> String {
|
||||
const ALPHABET: &[u8; 36] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
let mut out = String::with_capacity(16);
|
||||
while out.len() < 16 {
|
||||
for b in Uuid::new_v4().as_bytes() {
|
||||
// rejection sampling: 252 is the largest multiple of 36 below 256, so every symbol is equally likely
|
||||
if *b < 252 && out.len() < 16 {
|
||||
out.push(ALPHABET[(*b % 36) as usize] as char);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The account name wanted, made fit for the game: letters and digits only, upper case, at most 16 characters.
|
||||
pub fn sanitize_username(wanted: &str) -> String {
|
||||
let base: String = wanted.chars().filter(char::is_ascii_alphanumeric).collect::<String>().to_ascii_uppercase();
|
||||
let base: String = base.chars().take(MAX_USERNAME).collect();
|
||||
if base.len() >= MIN_USERNAME { base } else { format!("{base}PLAYER").chars().take(MAX_USERNAME).collect() }
|
||||
}
|
||||
|
||||
/// The stable alternative of an occupied name: `DMITRY` becomes `DMITRY_7K4M`. The suffix is derived from the player's id, so the same player gets the same alternative.
|
||||
pub fn alternative_username(base: &str, player: &Uuid, attempt: u32) -> String {
|
||||
const ALPHABET: &[u8; 32] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
let bytes = player.as_bytes();
|
||||
let mix = u32::from_be_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]).wrapping_add(attempt.wrapping_mul(0x9E37_79B1));
|
||||
let suffix: String = (0..4).map(|i| ALPHABET[((mix >> (i * 5)) & 31) as usize] as char).collect();
|
||||
let keep = MAX_USERNAME - 5;
|
||||
let head: String = base.chars().take(keep).collect();
|
||||
format!("{head}_{suffix}")
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Request {
|
||||
Hello { protocol: u32, client: String },
|
||||
/// Make the player's account on this realm, or reuse it. `password` is the one the player's Manager keeps for this realm; it travels only inside the channel.
|
||||
Provision { desired: Option<String>, password: String, have_credentials: bool },
|
||||
ListCharacters,
|
||||
Claim { token: u32 },
|
||||
ClaimAck { character_id: Uuid },
|
||||
/// Link an account the realm already has (one time).
|
||||
Link { login: String, password: String },
|
||||
Route,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AppError {
|
||||
UnsupportedVersion,
|
||||
Invalid,
|
||||
ProvisioningOff,
|
||||
NoAccount,
|
||||
NotAtCharacterSelect,
|
||||
NotYours,
|
||||
AlreadyClaimed,
|
||||
NotEligible,
|
||||
WrongCredentials,
|
||||
AccountTaken,
|
||||
RateLimited,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CharacterEntry {
|
||||
/// Opaque to the player: the Host's handle for this character, valid for this realm.
|
||||
pub token: u32,
|
||||
pub name: String,
|
||||
pub class: u32,
|
||||
pub race: u32,
|
||||
pub level: u32,
|
||||
pub eligible: bool,
|
||||
pub reasons: Vec<String>,
|
||||
/// Already portable and claimed by this player.
|
||||
pub yours: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "snake_case")]
|
||||
pub enum Response {
|
||||
Welcome { realm_id: coa_registry_proto::RealmId, automatic: bool, existing_only: bool, route: Option<String> },
|
||||
Provisioned { username: String, created: bool, reset: bool },
|
||||
Characters { characters: Vec<CharacterEntry> },
|
||||
/// The character as the Host exported it: `payload` is the base64 of the encoded portable snapshot, `sha256` its hash.
|
||||
Claimed { character_id: Uuid, sha256: String, payload: String },
|
||||
Linked { username: String },
|
||||
Done,
|
||||
RouteInfo { address: Option<String> },
|
||||
Error { code: AppError, message: String },
|
||||
}
|
||||
|
||||
pub fn encode_request(r: &Request) -> Vec<u8> {
|
||||
serde_json::to_vec(r).expect("a request serialises")
|
||||
}
|
||||
|
||||
pub fn decode_request(bytes: &[u8]) -> Result<Request> {
|
||||
if bytes.len() > MAX_REQUEST_BYTES {
|
||||
return Err(ControlError::Limit("a request is too long".into()));
|
||||
}
|
||||
let r: Request = serde_json::from_slice(bytes).map_err(|_| ControlError::Invalid("a request is not valid".into()))?;
|
||||
match &r {
|
||||
Request::Provision { desired, password, .. } => {
|
||||
if !valid_password(password) || desired.as_deref().is_some_and(|d| d.len() > 64 || d.chars().any(char::is_control)) {
|
||||
return invalid("a provisioning request has an unusable password or name");
|
||||
}
|
||||
}
|
||||
Request::Link { login, password } => {
|
||||
if !valid_username(login) || !valid_password_for_link(password) {
|
||||
return invalid("a link request has an unusable login or password");
|
||||
}
|
||||
}
|
||||
Request::Hello { client, .. } if client.len() > 64 => return invalid("the client name is too long"),
|
||||
_ => {}
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// An existing account's password may be anything the game accepts (6 to 16 printable characters without spaces or quotes).
|
||||
pub fn valid_password_for_link(s: &str) -> bool {
|
||||
(6..=16).contains(&s.len()) && s.chars().all(|c| c.is_ascii_graphic() && c != '"' && c != '\'' && c != '\\')
|
||||
}
|
||||
|
||||
pub fn encode_response(r: &Response) -> Vec<u8> {
|
||||
serde_json::to_vec(r).expect("a response serialises")
|
||||
}
|
||||
|
||||
pub fn decode_response(bytes: &[u8]) -> Result<Response> {
|
||||
serde_json::from_slice(bytes).map_err(|_| ControlError::Invalid("a response is not valid".into()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn passwords_are_random_unique_and_fit_the_game() {
|
||||
let a = generate_password();
|
||||
let b = generate_password();
|
||||
assert_ne!(a, b);
|
||||
assert!(valid_password(&a) && a.len() == 16 && a.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit()), "{a}");
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for _ in 0..200 {
|
||||
assert!(seen.insert(generate_password()), "no repeats");
|
||||
}
|
||||
let symbols: std::collections::HashSet<char> = (0..200).flat_map(|_| generate_password().chars().collect::<Vec<_>>()).collect();
|
||||
assert_eq!(symbols.len(), 36, "every symbol occurs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_are_made_fit_and_the_alternative_is_stable() {
|
||||
assert_eq!(sanitize_username("Dmitry"), "DMITRY");
|
||||
assert_eq!(sanitize_username("d m-i_t.r y"), "DMITRY");
|
||||
assert_eq!(sanitize_username("ab"), "ABPLAYER");
|
||||
assert_eq!(sanitize_username("a very long player name indeed"), "AVERYLONGPLAYERN");
|
||||
assert_eq!(sanitize_username("<script>"), "SCRIPT");
|
||||
assert!(valid_username(&sanitize_username("")) && valid_username(&sanitize_username("日本語")));
|
||||
let p = Uuid::now_v7();
|
||||
let alt = alternative_username("DMITRY", &p, 0);
|
||||
assert!(valid_username(&alt) && alt.starts_with("DMITRY_") && alt.len() == 11, "{alt}");
|
||||
assert_eq!(alt, alternative_username("DMITRY", &p, 0), "stable for the same player");
|
||||
assert_ne!(alt, alternative_username("DMITRY", &p, 1), "another attempt, another suffix");
|
||||
assert_ne!(alt, alternative_username("DMITRY", &Uuid::now_v7(), 0));
|
||||
assert_eq!(alternative_username("ABCDEFGHIJKLMNOP", &p, 0).len(), 16, "a long name is shortened to make room");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_are_strict() {
|
||||
let ok = encode_request(&Request::Provision { desired: Some("DMITRY".into()), password: generate_password(), have_credentials: false });
|
||||
assert!(decode_request(&ok).is_ok());
|
||||
for bad in [
|
||||
br#"{"op":"provision","desired":null,"password":"short","have_credentials":false}"#.as_slice(),
|
||||
br#"{"op":"provision","desired":null,"password":"has space 123456","have_credentials":false}"#,
|
||||
br#"{"op":"claim","token":1,"extra":true}"#,
|
||||
br#"{"op":"link","login":"a b","password":"secret1"}"#,
|
||||
br#"{"op":"unknown"}"#,
|
||||
b"not json",
|
||||
] {
|
||||
assert!(decode_request(bad).is_err(), "{}", String::from_utf8_lossy(bad));
|
||||
}
|
||||
assert!(decode_request(&vec![b' '; MAX_REQUEST_BYTES + 1]).is_err());
|
||||
assert!(decode_request(br#"{"op":"list_characters"}"#).is_ok());
|
||||
assert!(valid_password_for_link("pa55-w0rd") && !valid_password_for_link("has\"quote") && !valid_password_for_link("short"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
//! The Coordinator's own protocol. Text frames are JSON control messages; binary frames carry one end-to-end frame for one connection, prefixed with the
|
||||
//! connection number. The Coordinator routes by connection number and never looks inside.
|
||||
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
|
||||
use base64::Engine;
|
||||
use coa_registry_proto::RealmId;
|
||||
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{invalid, ControlError, Result};
|
||||
|
||||
/// The largest end-to-end frame the Coordinator forwards (a Noise message with its tag fits in 64 KiB; chunks are much smaller).
|
||||
pub const MAX_FRAME_BYTES: usize = 20 * 1024;
|
||||
/// Bytes of the connection number in front of a binary frame.
|
||||
pub const CONN_PREFIX: usize = 4;
|
||||
pub const MAX_CONTROL_TEXT_BYTES: usize = 2048;
|
||||
pub const HELLO_TIMEOUT_SECS: u64 = 10;
|
||||
/// A Hello's timestamp must be this close to the Coordinator's clock.
|
||||
pub const MAX_HELLO_SKEW_SECS: i64 = 120;
|
||||
|
||||
/// Hard limits of the Coordinator (the defaults of its configuration).
|
||||
pub mod limits {
|
||||
/// Simultaneous Player connections routed to one Host.
|
||||
pub const PER_HOST_CONNECTIONS: usize = 16;
|
||||
/// Simultaneous connections from one address.
|
||||
pub const PER_IP_CONNECTIONS: usize = 8;
|
||||
/// New Player connections per minute per realm, and per address.
|
||||
pub const PER_REALM_PER_MINUTE: u32 = 60;
|
||||
pub const PER_IP_PER_MINUTE: u32 = 30;
|
||||
/// Bytes through one connection, in total.
|
||||
pub const BYTES_PER_CONNECTION: usize = 16 * 1024 * 1024;
|
||||
/// Seconds a connection may live, and may be silent.
|
||||
pub const CONNECTION_LIFETIME_SECS: u64 = 600;
|
||||
pub const IDLE_SECS: u64 = 60;
|
||||
/// Seconds the Host has to answer a new connection (the first frame back).
|
||||
pub const HOST_ANSWER_SECS: u64 = 10;
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "t", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Frame {
|
||||
/// Coordinator -> anyone who connected: prove who you are with this.
|
||||
Challenge { protocol: u32, nonce: String },
|
||||
/// Host -> Coordinator.
|
||||
HostHello { realm_id: RealmId, ts: i64, sig: String },
|
||||
/// Player -> Coordinator (the realm it wants is in the URL and is signed).
|
||||
PlayerHello { player_id: Uuid, public_key: String, realm_id: RealmId, ts: i64, sig: String },
|
||||
/// Coordinator -> Host: the Host is registered and these are the limits.
|
||||
HostReady { max_connections: u32, max_frame: u32 },
|
||||
/// Coordinator -> Host: a Player wants to talk; its frames will carry this number.
|
||||
Open { conn: u32 },
|
||||
/// Either side of a connection ends it.
|
||||
Close { conn: u32, reason: Option<String> },
|
||||
/// Coordinator -> Player: the Host accepted the connection; binary frames flow now.
|
||||
PlayerReady { conn: u32, max_frame: u32 },
|
||||
Error { code: ErrorCode, message: String },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ErrorCode {
|
||||
BadHello,
|
||||
UnknownRealm,
|
||||
HostOffline,
|
||||
HostBusy,
|
||||
RateLimited,
|
||||
TooLarge,
|
||||
Timeout,
|
||||
Internal,
|
||||
}
|
||||
|
||||
pub fn challenge_nonce() -> String {
|
||||
let mut n = [0u8; 32];
|
||||
n[..16].copy_from_slice(Uuid::new_v4().as_bytes());
|
||||
n[16..].copy_from_slice(Uuid::new_v4().as_bytes());
|
||||
B64.encode(n)
|
||||
}
|
||||
|
||||
fn host_input(realm: &RealmId, nonce: &str, ts: i64) -> Vec<u8> {
|
||||
format!("coa-coord-host-v1\n{}\n{realm}\n{nonce}\n{ts}", crate::CONTROL_PROTOCOL_VERSION).into_bytes()
|
||||
}
|
||||
|
||||
fn player_input(player: &Uuid, public_key: &str, realm: &RealmId, nonce: &str, ts: i64) -> Vec<u8> {
|
||||
format!("coa-coord-player-v1\n{}\n{}\n{public_key}\n{realm}\n{nonce}\n{ts}", crate::CONTROL_PROTOCOL_VERSION, player.hyphenated()).into_bytes()
|
||||
}
|
||||
|
||||
pub fn sign_host_hello(key: &SigningKey, realm: &RealmId, nonce: &str, ts: i64) -> Frame {
|
||||
Frame::HostHello { realm_id: *realm, ts, sig: B64.encode(key.sign(&host_input(realm, nonce, ts)).to_bytes()) }
|
||||
}
|
||||
|
||||
pub fn sign_player_hello(key: &SigningKey, player: &Uuid, realm: &RealmId, nonce: &str, ts: i64) -> Frame {
|
||||
let public_key = B64.encode(key.verifying_key().as_bytes());
|
||||
let sig = B64.encode(key.sign(&player_input(player, &public_key, realm, nonce, ts)).to_bytes());
|
||||
Frame::PlayerHello { player_id: *player, public_key, realm_id: *realm, ts, sig }
|
||||
}
|
||||
|
||||
fn decode_sig(sig: &str) -> Result<Signature> {
|
||||
if sig.len() != 86 {
|
||||
return invalid("the signature has the wrong length");
|
||||
}
|
||||
let bytes: [u8; 64] = B64.decode(sig).map_err(|_| ControlError::Invalid("the signature is not base64url".into()))?.try_into().map_err(|_| ControlError::Invalid("the signature is not 64 bytes".into()))?;
|
||||
Ok(Signature::from_bytes(&bytes))
|
||||
}
|
||||
|
||||
/// A Host's hello checked against the key the Registry holds for the realm.
|
||||
pub fn verify_host_hello(frame: &Frame, realm_key: &VerifyingKey, expect_realm: Option<&RealmId>, nonce: &str, now: i64) -> Result<RealmId> {
|
||||
let Frame::HostHello { realm_id, ts, sig } = frame else { return Err(ControlError::Auth("not a host hello".into())) };
|
||||
if expect_realm.is_some_and(|r| r != realm_id) {
|
||||
return Err(ControlError::Auth("another realm".into()));
|
||||
}
|
||||
if (ts - now).abs() > MAX_HELLO_SKEW_SECS {
|
||||
return Err(ControlError::Auth("the timestamp is outside the allowed skew".into()));
|
||||
}
|
||||
realm_key.verify_strict(&host_input(realm_id, nonce, *ts), &decode_sig(sig)?).map_err(|_| ControlError::Auth("the signature does not match".into()))?;
|
||||
Ok(*realm_id)
|
||||
}
|
||||
|
||||
/// A Player's hello checked against the key it presents (proof of possession; the Host decides whether it is a known player).
|
||||
pub fn verify_player_hello(frame: &Frame, nonce: &str, now: i64) -> Result<(Uuid, RealmId, VerifyingKey)> {
|
||||
let Frame::PlayerHello { player_id, public_key, realm_id, ts, sig } = frame else { return Err(ControlError::Auth("not a player hello".into())) };
|
||||
if (ts - now).abs() > MAX_HELLO_SKEW_SECS {
|
||||
return Err(ControlError::Auth("the timestamp is outside the allowed skew".into()));
|
||||
}
|
||||
let key = decode_public_key(public_key)?;
|
||||
key.verify_strict(&player_input(player_id, public_key, realm_id, nonce, *ts), &decode_sig(sig)?).map_err(|_| ControlError::Auth("the signature does not match".into()))?;
|
||||
Ok((*player_id, *realm_id, key))
|
||||
}
|
||||
|
||||
pub fn decode_public_key(text: &str) -> Result<VerifyingKey> {
|
||||
coa_registry_proto::sign::decode_public_key(text).map_err(|e| ControlError::Invalid(e.to_string()))
|
||||
}
|
||||
|
||||
pub fn encode_public_key(key: &VerifyingKey) -> String {
|
||||
coa_registry_proto::sign::encode_public_key(key)
|
||||
}
|
||||
|
||||
/// `[connection number][end-to-end frame]`
|
||||
pub fn binary(conn: u32, frame: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(CONN_PREFIX + frame.len());
|
||||
out.extend_from_slice(&conn.to_be_bytes());
|
||||
out.extend_from_slice(frame);
|
||||
out
|
||||
}
|
||||
|
||||
pub fn split_binary(data: &[u8]) -> Result<(u32, &[u8])> {
|
||||
if data.len() < CONN_PREFIX || data.len() > CONN_PREFIX + MAX_FRAME_BYTES {
|
||||
return Err(ControlError::Limit("a frame is too short or too long".into()));
|
||||
}
|
||||
Ok((u32::from_be_bytes(data[..CONN_PREFIX].try_into().expect("4 bytes")), &data[CONN_PREFIX..]))
|
||||
}
|
||||
|
||||
pub fn parse_text(text: &str) -> Result<Frame> {
|
||||
if text.len() > MAX_CONTROL_TEXT_BYTES {
|
||||
return Err(ControlError::Limit("a control message is too long".into()));
|
||||
}
|
||||
serde_json::from_str(text).map_err(|_| ControlError::Invalid("a control message is not valid".into()))
|
||||
}
|
||||
|
||||
pub fn to_text(frame: &Frame) -> String {
|
||||
serde_json::to_string(frame).expect("a frame serialises")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn key(n: u8) -> SigningKey {
|
||||
SigningKey::from_bytes(&[n; 32])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_proves_its_realm_key_and_only_that() {
|
||||
let realm = RealmId::new();
|
||||
let nonce = challenge_nonce();
|
||||
let hello = sign_host_hello(&key(1), &realm, &nonce, 1000);
|
||||
assert_eq!(verify_host_hello(&hello, &key(1).verifying_key(), Some(&realm), &nonce, 1010).unwrap(), realm);
|
||||
assert!(verify_host_hello(&hello, &key(2).verifying_key(), Some(&realm), &nonce, 1010).is_err(), "another key");
|
||||
assert!(verify_host_hello(&hello, &key(1).verifying_key(), Some(&RealmId::new()), &nonce, 1010).is_err(), "another realm");
|
||||
assert!(verify_host_hello(&hello, &key(1).verifying_key(), None, &challenge_nonce(), 1010).is_err(), "another challenge: no replay");
|
||||
assert!(verify_host_hello(&hello, &key(1).verifying_key(), None, &nonce, 5000).is_err(), "too old");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_player_proves_possession_of_its_key() {
|
||||
let (player, realm, nonce) = (Uuid::now_v7(), RealmId::new(), challenge_nonce());
|
||||
let hello = sign_player_hello(&key(3), &player, &realm, &nonce, 50);
|
||||
let (p, r, k) = verify_player_hello(&hello, &nonce, 55).unwrap();
|
||||
assert_eq!((p, r, k.to_bytes()), (player, realm, key(3).verifying_key().to_bytes()));
|
||||
let Frame::PlayerHello { player_id, public_key, realm_id, ts, sig } = hello.clone() else { unreachable!() };
|
||||
let other_key = encode_public_key(&key(4).verifying_key());
|
||||
assert!(verify_player_hello(&Frame::PlayerHello { player_id, public_key: other_key, realm_id, ts, sig: sig.clone() }, &nonce, 55).is_err(), "a key that did not sign");
|
||||
assert!(verify_player_hello(&Frame::PlayerHello { player_id: Uuid::now_v7(), public_key, realm_id, ts, sig }, &nonce, 55).is_err(), "another player id");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_are_strict_and_bounded() {
|
||||
assert!(parse_text(r#"{"t":"close","conn":1,"reason":null,"extra":1}"#).is_err());
|
||||
assert!(parse_text(&"x".repeat(5000)).is_err());
|
||||
assert!(parse_text(r#"{"t":"open","conn":7}"#).is_ok());
|
||||
let b = binary(9, b"abc");
|
||||
assert_eq!(split_binary(&b).unwrap(), (9, b"abc".as_slice()));
|
||||
assert!(split_binary(&[0, 0]).is_err());
|
||||
assert!(split_binary(&vec![0u8; CONN_PREFIX + MAX_FRAME_BYTES + 1]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! The Player <-> Host control protocol (Phase 12), control plane only.
|
||||
//!
|
||||
//! ```text
|
||||
//! Player Manager --(WebSocket)--> Coordinator <--(WebSocket, opened by the Host)-- Host Manager
|
||||
//! \________ Noise_XX end-to-end channel, authenticated by Ed25519 signatures over its handshake hash ________/
|
||||
//! ```
|
||||
//!
|
||||
//! * [`coord`]: what the Coordinator sees and decides: who may connect (a Host proves its RealmId key, a Player proves a PlayerId key), how frames are routed, the limits.
|
||||
//! * [`noise`]: the end-to-end channel the Coordinator cannot read: the Noise handshake, the framing of long messages, and the binding of identities to it.
|
||||
//! * [`app`]: the application messages inside the channel (account provisioning, listing and claiming characters, linking an existing account, the route).
|
||||
//!
|
||||
//! The Coordinator never receives plaintext account passwords, character data or database/RA credentials: everything of that kind exists only inside the channel.
|
||||
|
||||
pub mod app;
|
||||
pub mod coord;
|
||||
pub mod noise;
|
||||
|
||||
pub const CONTROL_PROTOCOL_VERSION: u32 = 1;
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum ControlError {
|
||||
#[error("{0}")]
|
||||
Invalid(String),
|
||||
#[error("the channel failed: {0}")]
|
||||
Channel(String),
|
||||
#[error("the peer could not prove who it is: {0}")]
|
||||
Auth(String),
|
||||
#[error("a limit was exceeded: {0}")]
|
||||
Limit(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, ControlError>;
|
||||
|
||||
pub(crate) fn invalid<T>(m: impl Into<String>) -> Result<T> {
|
||||
Err(ControlError::Invalid(m.into()))
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
//! The end-to-end channel between a Player Manager and a Host Manager, over whatever carries frames between them (the Coordinator, later perhaps a direct socket).
|
||||
//!
|
||||
//! **Handshake: `Noise_XX_25519_ChaChaPoly_BLAKE2s`** (the Noise Protocol Framework, implemented by the `snow` crate; no primitive is invented here). Both sides use fresh
|
||||
//! random X25519 static keys for each channel, so the Noise layer gives confidentiality, integrity and forward secrecy but no identity. Identity is added the standard way,
|
||||
//! by **channel binding**: after the handshake each side signs the handshake hash `h` (unique to this channel) with its long-lived Ed25519 key.
|
||||
//!
|
||||
//! ```text
|
||||
//! Player -> Host msg1 (e)
|
||||
//! Host -> Player msg2 (e, ee, s, es)
|
||||
//! Player -> Host msg3 (s, se) channel is open; h = the handshake hash
|
||||
//! Host -> Player HostProof Ed25519_realm_key("coa-ctl-host-v1\0" || h || realm_id) the Player checks it against the key the Registry publishes
|
||||
//! Player -> Host PlayerProof Ed25519_player_key("coa-ctl-player-v1\0" || h || realm_id || player_id) sent only after the Host's proof was good
|
||||
//! ```
|
||||
//!
|
||||
//! A Coordinator that relays the frames can neither read nor alter them (Noise authenticates every message), and cannot impersonate either side: a signature over `h`
|
||||
//! for one channel is useless on another.
|
||||
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
|
||||
use base64::Engine;
|
||||
use coa_registry_proto::RealmId;
|
||||
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use snow::{Builder, HandshakeState, TransportState};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{ControlError, Result};
|
||||
|
||||
pub const NOISE_PARAMS: &str = "Noise_XX_25519_ChaChaPoly_BLAKE2s";
|
||||
/// Plaintext bytes per transport frame (a frame is this plus one flag byte plus the 16-byte tag).
|
||||
pub const CHUNK: usize = 16 * 1024;
|
||||
/// The largest application message (reassembled).
|
||||
pub const MAX_MESSAGE_BYTES: usize = 8 * 1024 * 1024;
|
||||
const MAX_HANDSHAKE_BYTES: usize = 1024;
|
||||
|
||||
fn channel_err(e: snow::Error) -> ControlError {
|
||||
ControlError::Channel(e.to_string())
|
||||
}
|
||||
|
||||
fn builder() -> Result<Builder<'static>> {
|
||||
Ok(Builder::new(NOISE_PARAMS.parse().map_err(channel_err)?))
|
||||
}
|
||||
|
||||
/// The Player's side of the handshake.
|
||||
pub struct Initiator {
|
||||
hs: HandshakeState,
|
||||
}
|
||||
|
||||
impl Initiator {
|
||||
/// The state and the first message to send.
|
||||
pub fn start() -> Result<(Self, Vec<u8>)> {
|
||||
let b = builder()?;
|
||||
let key = b.generate_keypair().map_err(channel_err)?;
|
||||
let mut hs = b.local_private_key(&key.private).build_initiator().map_err(channel_err)?;
|
||||
let mut buf = vec![0u8; MAX_HANDSHAKE_BYTES];
|
||||
let n = hs.write_message(&[], &mut buf).map_err(channel_err)?;
|
||||
buf.truncate(n);
|
||||
Ok((Self { hs }, buf))
|
||||
}
|
||||
|
||||
/// Read the Host's answer; returns the third message to send and the open channel.
|
||||
pub fn finish(mut self, msg2: &[u8]) -> Result<(Vec<u8>, Channel)> {
|
||||
if msg2.len() > MAX_HANDSHAKE_BYTES {
|
||||
return Err(ControlError::Limit("a handshake message is too long".into()));
|
||||
}
|
||||
let mut buf = vec![0u8; MAX_HANDSHAKE_BYTES];
|
||||
self.hs.read_message(msg2, &mut buf).map_err(channel_err)?;
|
||||
let n = self.hs.write_message(&[], &mut buf).map_err(channel_err)?;
|
||||
buf.truncate(n);
|
||||
if !self.hs.is_handshake_finished() {
|
||||
return Err(ControlError::Channel("the handshake did not finish".into()));
|
||||
}
|
||||
Ok((buf, Channel::from(self.hs)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// The Host's side of the handshake.
|
||||
pub struct Responder {
|
||||
hs: HandshakeState,
|
||||
}
|
||||
|
||||
impl Responder {
|
||||
/// Read the first message; returns the state and the second message to send.
|
||||
pub fn start(msg1: &[u8]) -> Result<(Self, Vec<u8>)> {
|
||||
if msg1.len() > MAX_HANDSHAKE_BYTES {
|
||||
return Err(ControlError::Limit("a handshake message is too long".into()));
|
||||
}
|
||||
let b = builder()?;
|
||||
let key = b.generate_keypair().map_err(channel_err)?;
|
||||
let mut hs = b.local_private_key(&key.private).build_responder().map_err(channel_err)?;
|
||||
let mut buf = vec![0u8; MAX_HANDSHAKE_BYTES];
|
||||
hs.read_message(msg1, &mut buf).map_err(channel_err)?;
|
||||
let n = hs.write_message(&[], &mut buf).map_err(channel_err)?;
|
||||
buf.truncate(n);
|
||||
Ok((Self { hs }, buf))
|
||||
}
|
||||
|
||||
pub fn finish(mut self, msg3: &[u8]) -> Result<Channel> {
|
||||
if msg3.len() > MAX_HANDSHAKE_BYTES {
|
||||
return Err(ControlError::Limit("a handshake message is too long".into()));
|
||||
}
|
||||
let mut buf = vec![0u8; MAX_HANDSHAKE_BYTES];
|
||||
self.hs.read_message(msg3, &mut buf).map_err(channel_err)?;
|
||||
if !self.hs.is_handshake_finished() {
|
||||
return Err(ControlError::Channel("the handshake did not finish".into()));
|
||||
}
|
||||
Channel::from(self.hs)
|
||||
}
|
||||
}
|
||||
|
||||
/// An open channel: messages go out as one or more encrypted frames and come back reassembled.
|
||||
pub struct Channel {
|
||||
transport: TransportState,
|
||||
hash: Vec<u8>,
|
||||
partial: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Channel {
|
||||
fn from(hs: HandshakeState) -> Result<Self> {
|
||||
let hash = hs.get_handshake_hash().to_vec();
|
||||
Ok(Self { transport: hs.into_transport_mode().map_err(channel_err)?, hash, partial: Vec::new() })
|
||||
}
|
||||
|
||||
/// The handshake hash: unique to this channel, the same on both ends.
|
||||
pub fn handshake_hash(&self) -> &[u8] {
|
||||
&self.hash
|
||||
}
|
||||
|
||||
/// Encrypt one application message into frames (in order).
|
||||
pub fn seal(&mut self, message: &[u8]) -> Result<Vec<Vec<u8>>> {
|
||||
if message.len() > MAX_MESSAGE_BYTES {
|
||||
return Err(ControlError::Limit("a message is too long".into()));
|
||||
}
|
||||
let chunks: Vec<&[u8]> = if message.is_empty() { vec![&[][..]] } else { message.chunks(CHUNK).collect() };
|
||||
let mut frames = Vec::with_capacity(chunks.len());
|
||||
for (i, chunk) in chunks.iter().enumerate() {
|
||||
let mut plain = Vec::with_capacity(chunk.len() + 1);
|
||||
plain.push(u8::from(i + 1 < chunks.len()));
|
||||
plain.extend_from_slice(chunk);
|
||||
let mut out = vec![0u8; plain.len() + 16];
|
||||
let n = self.transport.write_message(&plain, &mut out).map_err(channel_err)?;
|
||||
out.truncate(n);
|
||||
frames.push(out);
|
||||
}
|
||||
Ok(frames)
|
||||
}
|
||||
|
||||
/// Decrypt one frame. `Some(message)` when it completed a message; `None` when more frames follow. A frame that does not authenticate ends the channel.
|
||||
pub fn open_frame(&mut self, frame: &[u8]) -> Result<Option<Vec<u8>>> {
|
||||
if frame.len() < 17 || frame.len() > CHUNK + 17 {
|
||||
return Err(ControlError::Limit("a frame is too short or too long".into()));
|
||||
}
|
||||
let mut plain = vec![0u8; frame.len()];
|
||||
let n = self.transport.read_message(frame, &mut plain).map_err(channel_err)?;
|
||||
plain.truncate(n);
|
||||
let (&more, chunk) = plain.split_first().ok_or_else(|| ControlError::Channel("an empty frame".into()))?;
|
||||
if self.partial.len() + chunk.len() > MAX_MESSAGE_BYTES {
|
||||
self.partial.clear();
|
||||
return Err(ControlError::Limit("a message is too long".into()));
|
||||
}
|
||||
self.partial.extend_from_slice(chunk);
|
||||
match more {
|
||||
0 => Ok(Some(std::mem::take(&mut self.partial))),
|
||||
1 => Ok(None),
|
||||
_ => Err(ControlError::Channel("a frame has an unknown flag".into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- identity bound to the channel --------------------------------------------------------------------------------------------
|
||||
|
||||
fn host_input(h: &[u8], realm: &RealmId) -> Vec<u8> {
|
||||
let mut v = b"coa-ctl-host-v1\0".to_vec();
|
||||
v.extend_from_slice(h);
|
||||
v.extend_from_slice(realm.to_string().as_bytes());
|
||||
v
|
||||
}
|
||||
|
||||
fn player_input(h: &[u8], realm: &RealmId, player: &Uuid) -> Vec<u8> {
|
||||
let mut v = b"coa-ctl-player-v1\0".to_vec();
|
||||
v.extend_from_slice(h);
|
||||
v.extend_from_slice(realm.to_string().as_bytes());
|
||||
v.extend_from_slice(player.hyphenated().to_string().as_bytes());
|
||||
v
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct HostProof {
|
||||
pub realm_id: RealmId,
|
||||
pub sig: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PlayerProof {
|
||||
pub player_id: Uuid,
|
||||
pub public_key: String,
|
||||
pub sig: String,
|
||||
}
|
||||
|
||||
fn decode_sig(sig: &str) -> Result<Signature> {
|
||||
let bytes: [u8; 64] = B64.decode(sig).ok().and_then(|b| b.try_into().ok()).ok_or_else(|| ControlError::Auth("a signature is not 64 bytes of base64url".into()))?;
|
||||
Ok(Signature::from_bytes(&bytes))
|
||||
}
|
||||
|
||||
pub fn host_proof(key: &SigningKey, realm: &RealmId, channel: &Channel) -> HostProof {
|
||||
HostProof { realm_id: *realm, sig: B64.encode(key.sign(&host_input(channel.handshake_hash(), realm)).to_bytes()) }
|
||||
}
|
||||
|
||||
/// The Player checks that the peer holds the key the Registry publishes for the realm it asked for, on this very channel.
|
||||
pub fn verify_host_proof(proof: &HostProof, realm_key: &VerifyingKey, expected_realm: &RealmId, channel: &Channel) -> Result<()> {
|
||||
if proof.realm_id != *expected_realm {
|
||||
return Err(ControlError::Auth("the peer answers for another realm".into()));
|
||||
}
|
||||
realm_key.verify_strict(&host_input(channel.handshake_hash(), expected_realm), &decode_sig(&proof.sig)?).map_err(|_| ControlError::Auth("the peer is not the realm's Host".into()))
|
||||
}
|
||||
|
||||
pub fn player_proof(key: &SigningKey, realm: &RealmId, player: &Uuid, channel: &Channel) -> PlayerProof {
|
||||
PlayerProof { player_id: *player, public_key: crate::coord::encode_public_key(&key.verifying_key()), sig: B64.encode(key.sign(&player_input(channel.handshake_hash(), realm, player)).to_bytes()) }
|
||||
}
|
||||
|
||||
/// The Host learns which player key signed this channel; whether that key is the one it knows for the player id is the Host's decision.
|
||||
pub fn verify_player_proof(proof: &PlayerProof, realm: &RealmId, channel: &Channel) -> Result<VerifyingKey> {
|
||||
let key = crate::coord::decode_public_key(&proof.public_key)?;
|
||||
key.verify_strict(&player_input(channel.handshake_hash(), realm, &proof.player_id), &decode_sig(&proof.sig)?).map_err(|_| ControlError::Auth("the player's proof does not match this channel".into()))?;
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pair() -> (Channel, Channel) {
|
||||
let (init, m1) = Initiator::start().unwrap();
|
||||
let (resp, m2) = Responder::start(&m1).unwrap();
|
||||
let (m3, player) = init.finish(&m2).unwrap();
|
||||
let host = resp.finish(&m3).unwrap();
|
||||
(player, host)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_channel_carries_messages_of_any_size_in_both_directions() {
|
||||
let (mut player, mut host) = pair();
|
||||
assert_eq!(player.handshake_hash(), host.handshake_hash(), "both ends hold the same channel binding");
|
||||
for len in [0usize, 1, 100, CHUNK - 1, CHUNK, CHUNK + 1, 5 * CHUNK + 7, 600_000] {
|
||||
let msg: Vec<u8> = (0..len).map(|i| (i * 31 % 251) as u8).collect();
|
||||
let frames = player.seal(&msg).unwrap();
|
||||
assert!(frames.iter().all(|f| f.len() <= CHUNK + 17), "every frame fits the coordinator's limit");
|
||||
let mut got = None;
|
||||
for f in &frames {
|
||||
got = host.open_frame(f).unwrap();
|
||||
}
|
||||
assert_eq!(got.as_deref(), Some(msg.as_slice()), "{len}");
|
||||
let back = host.seal(&msg).unwrap();
|
||||
let mut got = None;
|
||||
for f in &back {
|
||||
got = player.open_frame(f).unwrap();
|
||||
}
|
||||
assert_eq!(got.as_deref(), Some(msg.as_slice()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_a_relay_sees_is_not_the_message_and_what_it_changes_is_refused() {
|
||||
let (mut player, mut host) = pair();
|
||||
let secret = b"the password of this account is HUNTER2HUNTER2";
|
||||
let frames = player.seal(secret).unwrap();
|
||||
assert!(!frames[0].windows(7).any(|w| w == b"HUNTER2" || w == b"account"), "ciphertext carries no plaintext");
|
||||
let mut tampered = frames[0].clone();
|
||||
tampered[20] ^= 1;
|
||||
assert!(host.open_frame(&tampered).is_err(), "a changed frame does not authenticate");
|
||||
let (mut p2, mut h2) = pair();
|
||||
let f = p2.seal(b"x").unwrap();
|
||||
assert!(h2.open_frame(&f[0]).is_ok());
|
||||
assert!(h2.open_frame(&f[0]).is_err(), "a replayed frame is refused (the nonce moved on)");
|
||||
let (mut p3, mut h3) = pair();
|
||||
let (mut p4, _h4) = pair();
|
||||
let foreign = p4.seal(b"x").unwrap();
|
||||
assert!(h3.open_frame(&foreign[0]).is_err(), "a frame of another channel is refused");
|
||||
let _ = &mut p3;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_message_that_is_too_long_or_a_frame_that_is_malformed_is_a_limit_error() {
|
||||
let (mut player, mut host) = pair();
|
||||
assert!(player.seal(&vec![0u8; MAX_MESSAGE_BYTES + 1]).is_err());
|
||||
assert!(host.open_frame(&[0u8; 5]).is_err());
|
||||
assert!(host.open_frame(&vec![0u8; CHUNK + 40]).is_err());
|
||||
assert!(Responder::start(&vec![0u8; 5000]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identities_are_bound_to_one_channel() {
|
||||
let (player_ch, host_ch) = pair();
|
||||
let (other_player_ch, _other_host_ch) = pair();
|
||||
let realm = RealmId::new();
|
||||
let (realm_key, player_key) = (SigningKey::from_bytes(&[5; 32]), SigningKey::from_bytes(&[6; 32]));
|
||||
let player_id = Uuid::now_v7();
|
||||
|
||||
let proof = host_proof(&realm_key, &realm, &host_ch);
|
||||
verify_host_proof(&proof, &realm_key.verifying_key(), &realm, &player_ch).unwrap();
|
||||
assert!(verify_host_proof(&proof, &SigningKey::from_bytes(&[9; 32]).verifying_key(), &realm, &player_ch).is_err(), "an impostor with another key");
|
||||
assert!(verify_host_proof(&proof, &realm_key.verifying_key(), &RealmId::new(), &player_ch).is_err(), "another realm");
|
||||
assert!(verify_host_proof(&proof, &realm_key.verifying_key(), &realm, &other_player_ch).is_err(), "a proof captured on another channel is useless (no relay can replay it)");
|
||||
|
||||
let pp = player_proof(&player_key, &realm, &player_id, &player_ch);
|
||||
let key = verify_player_proof(&pp, &realm, &host_ch).unwrap();
|
||||
assert_eq!(key.to_bytes(), player_key.verifying_key().to_bytes());
|
||||
assert!(verify_player_proof(&pp, &RealmId::new(), &host_ch).is_err());
|
||||
assert!(verify_player_proof(&PlayerProof { player_id: Uuid::now_v7(), ..pp.clone() }, &realm, &host_ch).is_err(), "another player id under the same signature");
|
||||
let (_, third_host) = pair();
|
||||
assert!(verify_player_proof(&pp, &realm, &third_host).is_err(), "another channel");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user