Files
Legatus/crates/protocol/src/code.rs
T

220 lines
7.1 KiB
Rust

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! The enrollment code: `lgt1-` and base32 of version, root SHA-256, secret, server URL, checksum.
use std::fmt;
use data_encoding::{Encoding, Specification};
use crate::hex;
/// What every code starts with.
pub const CODE_PREFIX: &str = "lgt1-";
const VERSION: u8 = 1;
const MAX_URL: usize = 200;
const MIN_LEN: usize = 1 + 32 + 16 + 1 + 1 + 4;
/// Why a code cannot be read or made.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum CodeError {
/// It does not start with `lgt1-`.
#[error("an enrollment code starts with lgt1-")]
Prefix,
/// Not base32.
#[error("the enrollment code has characters that do not belong in it")]
Encoding,
/// Too short or its parts do not add up.
#[error("the enrollment code is incomplete")]
Length,
/// A version this Legatus does not know.
#[error("the enrollment code is from a newer Fabrica; update Legatus")]
Version,
/// The checksum does not match: a typo or a cut copy.
#[error("the enrollment code has a typo; copy it again from Fabrica")]
Checksum,
/// The server URL is not a plain `https://host[:port]`.
#[error("the server address cannot be used: {0}")]
BadServer(String),
}
/// An enrollment code: where the Fabrica server is, which Domi root it chains to, and the
/// one-time secret. `Debug` never shows the secret.
#[derive(Clone, PartialEq, Eq)]
pub struct EnrollmentCode {
server: String,
root_sha256: [u8; 32],
secret: [u8; 16],
}
impl fmt::Debug for EnrollmentCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("EnrollmentCode")
.field("server", &self.server)
.field("root_sha256", &hex(&self.root_sha256))
.field("secret", &"…")
.finish()
}
}
fn base32() -> Result<Encoding, CodeError> {
let mut spec = Specification::new();
spec.symbols.push_str("abcdefghijklmnopqrstuvwxyz234567");
spec.encoding().map_err(|_| CodeError::Encoding)
}
fn digest(b: &[u8]) -> [u8; 32] {
let d = ring::digest::digest(&ring::digest::SHA256, b);
let mut out = [0u8; 32];
out.copy_from_slice(d.as_ref());
out
}
/// Is `url` exactly `https://host` or `https://host:port`?
pub(crate) fn check_server(url: &str) -> Result<(), CodeError> {
let bad = |why: &str| Err(CodeError::BadServer(why.to_owned()));
if url.len() > MAX_URL {
return bad("longer than 200 characters");
}
let Some(auth) = url.strip_prefix("https://") else {
return bad("it must start with https://");
};
if auth.is_empty() {
return bad("no host");
}
if auth
.bytes()
.any(|b| matches!(b, b'/' | b'?' | b'#' | b'@' | b'\\') || !b.is_ascii_graphic())
{
return bad("only a host and a port, nothing else");
}
let (host, port) = if let Some(rest) = auth.strip_prefix('[') {
let Some((h, after)) = rest.split_once(']') else {
return bad("an unclosed [");
};
if h.is_empty()
|| !h
.bytes()
.all(|b| b.is_ascii_hexdigit() || b == b':' || b == b'.')
{
return bad("not an IPv6 address");
}
match after {
"" => (h, None),
p => match p.strip_prefix(':') {
Some(p) => (h, Some(p)),
None => return bad("garbage after the address"),
},
}
} else {
match auth.split_once(':') {
Some((h, p)) => (h, Some(p)),
None => (auth, None),
}
};
if host.is_empty()
|| host.starts_with('.')
|| host.starts_with('-')
|| !host
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b':'))
{
return bad("not a host name");
}
if let Some(p) = port {
let ok = !p.is_empty()
&& p.len() <= 5
&& p.bytes().all(|b| b.is_ascii_digit())
&& p.parse::<u32>().is_ok_and(|n| (1..=65_535).contains(&n));
if !ok {
return bad("the port must be 1 to 65535");
}
}
Ok(())
}
impl EnrollmentCode {
/// A code for `server` (`https://host[:port]`), the root with SHA-256 `root_sha256`, and a
/// secret from a good random source.
pub fn new(
server: &str,
root_sha256: [u8; 32],
secret: [u8; 16],
) -> Result<EnrollmentCode, CodeError> {
check_server(server)?;
Ok(EnrollmentCode {
server: server.to_owned(),
root_sha256,
secret,
})
}
/// The server URL, `https://host[:port]`.
pub fn server(&self) -> &str {
&self.server
}
/// SHA-256 of the Domi root certificate's DER.
pub fn root_sha256(&self) -> &[u8; 32] {
&self.root_sha256
}
/// The secret as 32 lowercase hex characters (what `enroll` sends).
pub fn secret_hex(&self) -> String {
hex(&self.secret)
}
/// The text the person copies.
pub fn encode(&self) -> String {
let mut b = Vec::with_capacity(MIN_LEN + self.server.len());
b.push(VERSION);
b.extend_from_slice(&self.root_sha256);
b.extend_from_slice(&self.secret);
// `new` keeps the URL at 200 bytes or fewer.
b.push(u8::try_from(self.server.len()).unwrap_or(u8::MAX));
b.extend_from_slice(self.server.as_bytes());
let check = digest(&b);
b.extend_from_slice(&check[..4]);
let body = base32().map(|e| e.encode(&b)).unwrap_or_default();
format!("{CODE_PREFIX}{body}")
}
/// Read a code someone pasted (surrounding whitespace and upper case are fine).
pub fn parse(text: &str) -> Result<EnrollmentCode, CodeError> {
let t = text.trim();
let body = t
.strip_prefix(CODE_PREFIX)
.ok_or(CodeError::Prefix)?
.to_ascii_lowercase();
if body.len() > 1000 {
return Err(CodeError::Length);
}
let b = base32()?
.decode(body.as_bytes())
.map_err(|_| CodeError::Encoding)?;
if b.len() < MIN_LEN {
return Err(CodeError::Length);
}
let (data, check) = b.split_at(b.len() - 4);
if digest(data)[..4] != *check {
return Err(CodeError::Checksum);
}
if data.first() != Some(&VERSION) {
return Err(CodeError::Version);
}
let mut root_sha256 = [0u8; 32];
root_sha256.copy_from_slice(data.get(1..33).ok_or(CodeError::Length)?);
let mut secret = [0u8; 16];
secret.copy_from_slice(data.get(33..49).ok_or(CodeError::Length)?);
let n = usize::from(*data.get(49).ok_or(CodeError::Length)?);
let url = data.get(50..).ok_or(CodeError::Length)?;
if url.len() != n {
return Err(CodeError::Length);
}
let server =
std::str::from_utf8(url).map_err(|_| CodeError::BadServer("not text".into()))?;
EnrollmentCode::new(server, root_sha256, secret)
}
}