mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-25 19:25:56 +00:00
feat(phase15): release and security hardening, DPAPI key store, probe & protocol hardening, secret redaction, audit and readiness report
This commit is contained in:
1 parent
b69fa6b867
commit
51e0f136d6
207 files changed
+38235
-7770
No files matched your search
@@ -18,7 +18,10 @@ 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('_')
|
||||
(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).
|
||||
@@ -43,17 +46,28 @@ pub fn generate_password() -> String {
|
||||
|
||||
/// 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 = 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() }
|
||||
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 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}")
|
||||
@@ -62,14 +76,28 @@ pub fn alternative_username(base: &str, player: &Uuid, attempt: u32) -> String {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Request {
|
||||
Hello { protocol: u32, client: String },
|
||||
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 },
|
||||
Provision {
|
||||
desired: Option<String>,
|
||||
password: String,
|
||||
have_credentials: bool,
|
||||
},
|
||||
ListCharacters,
|
||||
Claim { token: u32 },
|
||||
ClaimAck { character_id: Uuid },
|
||||
Claim {
|
||||
token: u32,
|
||||
},
|
||||
ClaimAck {
|
||||
character_id: Uuid,
|
||||
},
|
||||
/// Link an account the realm already has (one time).
|
||||
Link { login: String, password: String },
|
||||
Link {
|
||||
login: String,
|
||||
password: String,
|
||||
},
|
||||
Route,
|
||||
/// Phase 12.1: Start or resume a remote portable character transfer.
|
||||
TransferOffer {
|
||||
@@ -105,7 +133,6 @@ pub enum Request {
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AppError {
|
||||
@@ -144,19 +171,45 @@ pub struct CharacterEntry {
|
||||
#[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> },
|
||||
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` the hash of its canonical JSON, `collections` the account's
|
||||
/// appearance and vanity ids the Host holds for the account (kind -> ids).
|
||||
Claimed { character_id: Uuid, sha256: String, payload: String, collections: BTreeMap<String, Vec<u32>> },
|
||||
Linked { username: String },
|
||||
Claimed {
|
||||
character_id: Uuid,
|
||||
sha256: String,
|
||||
payload: String,
|
||||
collections: BTreeMap<String, Vec<u32>>,
|
||||
},
|
||||
Linked {
|
||||
username: String,
|
||||
},
|
||||
Done,
|
||||
RouteInfo { address: Option<String> },
|
||||
RouteInfo {
|
||||
address: Option<String>,
|
||||
},
|
||||
/// The Host is ready to receive transfer chunks (or indicates an offset to resume from).
|
||||
TransferReady { transfer_id: Uuid, received_offset: usize },
|
||||
TransferReady {
|
||||
transfer_id: Uuid,
|
||||
received_offset: usize,
|
||||
},
|
||||
/// Acknowledgement of a transfer chunk.
|
||||
TransferChunkAck { transfer_id: Uuid, received_offset: usize },
|
||||
TransferChunkAck {
|
||||
transfer_id: Uuid,
|
||||
received_offset: usize,
|
||||
},
|
||||
/// Successful commit and session arm.
|
||||
TransferCommitted {
|
||||
transfer_id: Uuid,
|
||||
@@ -174,10 +227,12 @@ pub enum Response {
|
||||
token: String,
|
||||
expires_at: i64,
|
||||
},
|
||||
Error { code: AppError, message: String },
|
||||
Error {
|
||||
code: AppError,
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
pub fn encode_request(r: &Request) -> Vec<u8> {
|
||||
serde_json::to_vec(r).expect("a request serialises")
|
||||
}
|
||||
@@ -186,13 +241,26 @@ pub fn decode_request(bytes: &[u8]) -> Result<Request> {
|
||||
if bytes.len() > MAX_TRANSFER_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()))?;
|
||||
if !matches!(&r, Request::TransferOffer { .. } | Request::TransferChunk { .. }) && bytes.len() > MAX_CONTROL_REQUEST_BYTES {
|
||||
return Err(ControlError::Limit("a standard control request exceeds 4096 bytes".into()));
|
||||
let r: Request = serde_json::from_slice(bytes)
|
||||
.map_err(|_| ControlError::Invalid("a request is not valid".into()))?;
|
||||
if !matches!(
|
||||
&r,
|
||||
Request::TransferOffer { .. } | Request::TransferChunk { .. }
|
||||
) && bytes.len() > MAX_CONTROL_REQUEST_BYTES
|
||||
{
|
||||
return Err(ControlError::Limit(
|
||||
"a standard control request exceeds 4096 bytes".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)) {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -201,20 +269,41 @@ pub fn decode_request(bytes: &[u8]) -> Result<Request> {
|
||||
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"),
|
||||
Request::TransferOffer { content_hash, total_size, collections, .. } => {
|
||||
Request::Hello { client, .. } if client.len() > 64 => {
|
||||
return invalid("the client name is too long")
|
||||
}
|
||||
Request::TransferOffer {
|
||||
content_hash,
|
||||
total_size,
|
||||
collections,
|
||||
..
|
||||
} => {
|
||||
if content_hash.len() != 64 || !content_hash.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return invalid("transfer content hash must be 64 hex characters");
|
||||
}
|
||||
if *total_size > crate::noise::MAX_MESSAGE_BYTES {
|
||||
return Err(ControlError::Limit("transfer total size is too large".into()));
|
||||
return Err(ControlError::Limit(
|
||||
"transfer total size is too large".into(),
|
||||
));
|
||||
}
|
||||
if collections.len() > 1000 {
|
||||
return Err(ControlError::Limit(
|
||||
"collections dictionary exceeds 1,000 keys".into(),
|
||||
));
|
||||
}
|
||||
let total_items: usize = collections.values().map(|v| v.len()).sum();
|
||||
if total_items > 100_000 {
|
||||
return Err(ControlError::Limit("collection mapping exceeds 100,000 entries".into()));
|
||||
return Err(ControlError::Limit(
|
||||
"collection mapping exceeds 100,000 entries".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Request::TransferChunk { data, .. } => {
|
||||
Request::TransferChunk { offset, data, .. } => {
|
||||
if *offset > MAX_TRANSFER_REQUEST_BYTES {
|
||||
return Err(ControlError::Limit(
|
||||
"transfer chunk offset exceeds limit".into(),
|
||||
));
|
||||
}
|
||||
if data.len() > MAX_TRANSFER_REQUEST_BYTES {
|
||||
return Err(ControlError::Limit("transfer chunk is too large".into()));
|
||||
}
|
||||
@@ -226,7 +315,9 @@ pub fn decode_request(bytes: &[u8]) -> Result<Request> {
|
||||
|
||||
/// 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 != '\\')
|
||||
(6..=16).contains(&s.len())
|
||||
&& s.chars()
|
||||
.all(|c| c.is_ascii_graphic() && c != '"' && c != '\'' && c != '\\')
|
||||
}
|
||||
|
||||
pub fn encode_response(r: &Response) -> Vec<u8> {
|
||||
@@ -234,7 +325,11 @@ pub fn encode_response(r: &Response) -> Vec<u8> {
|
||||
}
|
||||
|
||||
pub fn decode_response(bytes: &[u8]) -> Result<Response> {
|
||||
serde_json::from_slice(bytes).map_err(|_| ControlError::Invalid("a response is not valid".into()))
|
||||
if bytes.len() > MAX_TRANSFER_REQUEST_BYTES {
|
||||
return Err(ControlError::Limit("a response is too long".into()));
|
||||
}
|
||||
serde_json::from_slice(bytes)
|
||||
.map_err(|_| ControlError::Invalid("a response is not valid".into()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -246,12 +341,20 @@ mod tests {
|
||||
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}");
|
||||
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();
|
||||
let symbols: std::collections::HashSet<char> = (0..200)
|
||||
.flat_map(|_| generate_password().chars().collect::<Vec<_>>())
|
||||
.collect();
|
||||
assert_eq!(symbols.len(), 36, "every symbol occurs");
|
||||
}
|
||||
|
||||
@@ -260,21 +363,45 @@ mod tests {
|
||||
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("a very long player name indeed"),
|
||||
"AVERYLONGPLAYERN"
|
||||
);
|
||||
assert_eq!(sanitize_username("<script>"), "SCRIPT");
|
||||
assert!(valid_username(&sanitize_username("")) && valid_username(&sanitize_username("日本語")));
|
||||
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!(
|
||||
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");
|
||||
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 });
|
||||
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(),
|
||||
@@ -288,7 +415,11 @@ mod tests {
|
||||
}
|
||||
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"));
|
||||
assert!(
|
||||
valid_password_for_link("pa55-w0rd")
|
||||
&& !valid_password_for_link("has\"quote")
|
||||
&& !valid_password_for_link("short")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -41,13 +41,29 @@ pub mod limits {
|
||||
#[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 },
|
||||
Challenge {
|
||||
protocol: u32,
|
||||
nonce: String,
|
||||
},
|
||||
/// Host -> Coordinator.
|
||||
HostHello { realm_id: RealmId, ts: i64, sig: String },
|
||||
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 },
|
||||
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 },
|
||||
HostReady {
|
||||
max_connections: u32,
|
||||
max_frame: u32,
|
||||
},
|
||||
/// Coordinator -> Host: a Player wants to talk; its frames will carry this number.
|
||||
Open {
|
||||
conn: u32,
|
||||
@@ -55,10 +71,19 @@ pub enum Frame {
|
||||
client_ip: Option<String>,
|
||||
},
|
||||
/// Either side of a connection ends it.
|
||||
Close { conn: u32, reason: Option<String> },
|
||||
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 },
|
||||
PlayerReady {
|
||||
conn: u32,
|
||||
max_frame: u32,
|
||||
},
|
||||
Error {
|
||||
code: ErrorCode,
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -75,6 +100,7 @@ pub enum ErrorCode {
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ProbePayload {
|
||||
pub ports: Vec<u16>,
|
||||
}
|
||||
@@ -94,57 +120,121 @@ pub fn challenge_nonce() -> String {
|
||||
}
|
||||
|
||||
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()
|
||||
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()
|
||||
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()) }
|
||||
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 {
|
||||
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 }
|
||||
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()))?;
|
||||
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())) };
|
||||
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()));
|
||||
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()))?;
|
||||
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())) };
|
||||
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()));
|
||||
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()))?;
|
||||
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()))
|
||||
coa_registry_proto::sign::decode_public_key(text)
|
||||
.map_err(|e| ControlError::Invalid(e.to_string()))
|
||||
}
|
||||
|
||||
pub fn encode_public_key(key: &VerifyingKey) -> String {
|
||||
@@ -161,16 +251,22 @@ pub fn binary(conn: u32, frame: &[u8]) -> Vec<u8> {
|
||||
|
||||
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()));
|
||||
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..]))
|
||||
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()))
|
||||
serde_json::from_str(text)
|
||||
.map_err(|_| ControlError::Invalid("a control message is not valid".into()))
|
||||
}
|
||||
|
||||
pub fn to_text(frame: &Frame) -> String {
|
||||
@@ -190,11 +286,40 @@ mod tests {
|
||||
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");
|
||||
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]
|
||||
@@ -202,11 +327,51 @@ mod tests {
|
||||
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!() };
|
||||
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");
|
||||
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]
|
||||
|
||||
@@ -18,7 +18,6 @@ pub mod relay;
|
||||
|
||||
pub const CONTROL_PROTOCOL_VERSION: u32 = 1;
|
||||
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum ControlError {
|
||||
#[error("{0}")]
|
||||
|
||||
@@ -50,7 +50,10 @@ impl Initiator {
|
||||
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 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);
|
||||
@@ -60,7 +63,9 @@ impl Initiator {
|
||||
/// 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()));
|
||||
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)?;
|
||||
@@ -82,11 +87,16 @@ 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()));
|
||||
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 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)?;
|
||||
@@ -96,7 +106,9 @@ impl Responder {
|
||||
|
||||
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()));
|
||||
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)?;
|
||||
@@ -117,7 +129,11 @@ pub struct Channel {
|
||||
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() })
|
||||
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.
|
||||
@@ -130,14 +146,21 @@ impl Channel {
|
||||
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 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)?;
|
||||
let n = self
|
||||
.transport
|
||||
.write_message(&plain, &mut out)
|
||||
.map_err(channel_err)?;
|
||||
out.truncate(n);
|
||||
frames.push(out);
|
||||
}
|
||||
@@ -147,12 +170,19 @@ impl Channel {
|
||||
/// 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()));
|
||||
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)?;
|
||||
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()))?;
|
||||
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()));
|
||||
@@ -161,7 +191,10 @@ impl Channel {
|
||||
match more {
|
||||
0 => Ok(Some(std::mem::take(&mut self.partial))),
|
||||
1 => Ok(None),
|
||||
_ => Err(ControlError::Channel("a frame has an unknown flag".into())),
|
||||
_ => {
|
||||
self.partial.clear();
|
||||
Err(ControlError::Channel("a frame has an unknown flag".into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -199,30 +232,72 @@ pub struct PlayerProof {
|
||||
}
|
||||
|
||||
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()))?;
|
||||
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()) }
|
||||
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<()> {
|
||||
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()));
|
||||
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()))
|
||||
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()) }
|
||||
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> {
|
||||
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()))?;
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -241,11 +316,27 @@ mod tests {
|
||||
#[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] {
|
||||
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");
|
||||
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();
|
||||
@@ -265,18 +356,32 @@ mod tests {
|
||||
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");
|
||||
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");
|
||||
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)");
|
||||
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");
|
||||
assert!(
|
||||
h3.open_frame(&foreign[0]).is_err(),
|
||||
"a frame of another channel is refused"
|
||||
);
|
||||
let _ = &mut p3;
|
||||
}
|
||||
|
||||
@@ -294,21 +399,60 @@ mod tests {
|
||||
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 (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)");
|
||||
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");
|
||||
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");
|
||||
assert!(
|
||||
verify_player_proof(&pp, &realm, &third_host).is_err(),
|
||||
"another channel"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
|
||||
pub const RELAY_PROTOCOL_VERSION: u32 = 1;
|
||||
|
||||
/// Default local targets that the Host opens for game traffic.
|
||||
@@ -61,7 +60,7 @@ pub struct RelayWelcome {
|
||||
|
||||
/// Messages multiplexed across the Host <-> Relay tunnel.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "cmd", rename_all = "snake_case")]
|
||||
#[serde(tag = "cmd", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum TunnelMsg {
|
||||
/// Host asks Relay to allocate a game session for a player.
|
||||
Allocate {
|
||||
@@ -120,7 +119,11 @@ pub enum TunnelMsg {
|
||||
}
|
||||
|
||||
fn relay_input(realm: &RealmId, nonce: &str) -> Vec<u8> {
|
||||
format!("coa-relay-host-v1\n{}\n{realm}\n{nonce}", RELAY_PROTOCOL_VERSION).into_bytes()
|
||||
format!(
|
||||
"coa-relay-host-v1\n{}\n{realm}\n{nonce}",
|
||||
RELAY_PROTOCOL_VERSION
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
/// Create a signature over (realm_id, nonce) using the realm's signing key.
|
||||
@@ -130,13 +133,22 @@ pub fn sign_relay_challenge(key: &SigningKey, realm_id: &RealmId, nonce: &str) -
|
||||
}
|
||||
|
||||
/// Verify a signature over (realm_id, nonce) using the realm's verifying key.
|
||||
pub fn verify_relay_challenge(key: &VerifyingKey, realm_id: &RealmId, nonce: &str, sig_hex: &str) -> bool {
|
||||
let Ok(sig_bytes) = hex::decode(sig_hex) else { return false };
|
||||
let Ok(sig) = Signature::from_slice(&sig_bytes) else { return false };
|
||||
key.verify_strict(&relay_input(realm_id, nonce), &sig).is_ok()
|
||||
pub fn verify_relay_challenge(
|
||||
key: &VerifyingKey,
|
||||
realm_id: &RealmId,
|
||||
nonce: &str,
|
||||
sig_hex: &str,
|
||||
) -> bool {
|
||||
let Ok(sig_bytes) = hex::decode(sig_hex) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(sig) = Signature::from_slice(&sig_bytes) else {
|
||||
return false;
|
||||
};
|
||||
key.verify_strict(&relay_input(realm_id, nonce), &sig)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
|
||||
/// Rewrites the realm address in a WoW 3.3.5 REALM_LIST response packet (Opcode 0x10).
|
||||
///
|
||||
/// In WoW 3.3.5 client protocol:
|
||||
@@ -159,7 +171,10 @@ pub fn verify_relay_challenge(key: &VerifyingKey, realm_id: &RealmId, nonce: &st
|
||||
///
|
||||
/// Replaces the address of the first realm (or matches) with `new_host_port` and adjusts
|
||||
/// the uint16 length at bytes 1..2 by the byte length delta.
|
||||
pub fn rewrite_realm_list_address(pkt: &[u8], new_host_port: &str) -> Result<Option<Vec<u8>>, String> {
|
||||
pub fn rewrite_realm_list_address(
|
||||
pkt: &[u8],
|
||||
new_host_port: &str,
|
||||
) -> Result<Option<Vec<u8>>, String> {
|
||||
if pkt.is_empty() || pkt[0] != 0x10 {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -181,20 +196,35 @@ pub fn rewrite_realm_list_address(pkt: &[u8], new_host_port: &str) -> Result<Opt
|
||||
}
|
||||
pos += 3; // type, lock, flag
|
||||
|
||||
let name_end = pkt[pos..].iter().position(|&b| b == 0).ok_or("unterminated realm name")? + pos;
|
||||
let name_end = pkt[pos..]
|
||||
.iter()
|
||||
.position(|&b| b == 0)
|
||||
.ok_or("unterminated realm name")?
|
||||
+ pos;
|
||||
pos = name_end + 1;
|
||||
|
||||
let addr_start = pos;
|
||||
let addr_end = pkt[pos..].iter().position(|&b| b == 0).ok_or("unterminated realm address")? + pos;
|
||||
let addr_end = pkt[pos..]
|
||||
.iter()
|
||||
.position(|&b| b == 0)
|
||||
.ok_or("unterminated realm address")?
|
||||
+ pos;
|
||||
let old_addr = &pkt[addr_start..addr_end];
|
||||
|
||||
if new_host_port.len() > 255 {
|
||||
return Err("new host:port exceeds maximum address length".into());
|
||||
}
|
||||
let diff = new_host_port.len() as isize - old_addr.len() as isize;
|
||||
let new_body_len_isize = body_len as isize + diff;
|
||||
if !(0..=u16::MAX as isize).contains(&new_body_len_isize) {
|
||||
return Err("adjusted body length out of bounds".into());
|
||||
}
|
||||
let new_body_len = new_body_len_isize as u16;
|
||||
|
||||
let mut out = Vec::with_capacity(pkt.len() + new_host_port.len() + 1);
|
||||
out.extend_from_slice(&pkt[..addr_start]);
|
||||
out.extend_from_slice(new_host_port.as_bytes());
|
||||
out.extend_from_slice(&pkt[addr_end..]);
|
||||
|
||||
let diff = new_host_port.len() as isize - old_addr.len() as isize;
|
||||
let new_body_len = (body_len as isize + diff) as u16;
|
||||
out[1..3].copy_from_slice(&new_body_len.to_le_bytes());
|
||||
|
||||
Ok(Some(out))
|
||||
@@ -213,12 +243,27 @@ mod tests {
|
||||
let nonce = "test-challenge-nonce-123";
|
||||
|
||||
let sig = sign_relay_challenge(&key, &realm, nonce);
|
||||
assert!(verify_relay_challenge(&key.verifying_key(), &realm, nonce, &sig));
|
||||
assert!(verify_relay_challenge(
|
||||
&key.verifying_key(),
|
||||
&realm,
|
||||
nonce,
|
||||
&sig
|
||||
));
|
||||
|
||||
// Wrong nonce
|
||||
assert!(!verify_relay_challenge(&key.verifying_key(), &realm, "other-nonce", &sig));
|
||||
assert!(!verify_relay_challenge(
|
||||
&key.verifying_key(),
|
||||
&realm,
|
||||
"other-nonce",
|
||||
&sig
|
||||
));
|
||||
// Wrong realm
|
||||
assert!(!verify_relay_challenge(&key.verifying_key(), &RealmId::new(), nonce, &sig));
|
||||
assert!(!verify_relay_challenge(
|
||||
&key.verifying_key(),
|
||||
&RealmId::new(),
|
||||
nonce,
|
||||
&sig
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -250,7 +295,9 @@ mod tests {
|
||||
|
||||
// Rewrite
|
||||
let new_target = "coa-manager.duckdns.org:40005";
|
||||
let res = rewrite_realm_list_address(&pkt, new_target).unwrap().expect("rewritten");
|
||||
let res = rewrite_realm_list_address(&pkt, new_target)
|
||||
.unwrap()
|
||||
.expect("rewritten");
|
||||
|
||||
assert_eq!(res[0], 0x10);
|
||||
let new_len = u16::from_le_bytes([res[1], res[2]]) as usize;
|
||||
|
||||
Reference in new issue
Block a user