Crypto
WASM
TESTS
This commit is contained in:
Alex Emmet 2026-06-25 22:08:44 +02:00
commit 687e6f9642
49 changed files with 6272 additions and 366 deletions

View file

@ -14,3 +14,4 @@ tokio = { version = "1", features = ["full"] }
serde_json = { version = "1" }
hex = "0.4"
serde_core = "1.0.228"
base64 = "0.22"

View file

@ -8,14 +8,18 @@ pub fn load_client_db(
path: &str,
) -> Result<(Arc<Mutex<HashMap<u64, PublicKeyBundle>>>, Arc<Mutex<u64>>), Box<dyn std::error::Error>>
{
let clients: Arc<Mutex<HashMap<u64, PublicKeyBundle>>> =
Arc::new(Mutex::new(if let Ok(data) = fs::read_to_string(path) {
serde_json::from_str(&data).unwrap_or_default()
} else {
HashMap::new()
}));
let next_id = Arc::new(Mutex::new(
clients.lock().unwrap().keys().max().unwrap_or(&999) + 1,
));
let clients_map = match fs::read_to_string(path) {
Ok(data) => match serde_json::from_str(&data) {
Ok(clients) => clients,
Err(e) => {
eprintln!("Failed to parse {path}; starting with empty client database: {e}");
HashMap::new()
}
},
Err(_) => HashMap::new(),
};
let clients: Arc<Mutex<HashMap<u64, PublicKeyBundle>>> = Arc::new(Mutex::new(clients_map));
let next_value = clients.lock().unwrap().keys().max().unwrap_or(&999) + 1;
let next_id = Arc::new(Mutex::new(next_value));
Ok((clients, next_id))
}

View file

@ -63,6 +63,7 @@ pub fn process_and_respond(
enc_status = format!("EncryptedPayload decrypted OK ({} entries)", entries.len());
}
} else {
eprintln!(" EncryptedPayload decryption failed");
enc_status = String::from("EncryptedPayload: decryption FAILED");
}
}
@ -75,13 +76,14 @@ pub fn process_and_respond(
if dv.verify_into_container(&verifier).is_some() {
if let Some(entries) = dv.as_container() {
println!(" Verified SignedPayload: {:?}", entries);
sig_status =
format!("SignedPayload verified OK ({} entries)", entries.len());
sig_status = format!("SignedPayload verified OK ({} entries)", entries.len());
}
} else {
eprintln!(" SignedPayload verification failed");
sig_status = String::from("SignedPayload: verification FAILED");
}
} else {
eprintln!(" SignedPayload cannot be verified; no client public key available");
sig_status = String::from("SignedPayload: no client public key available");
}
}
@ -102,9 +104,11 @@ pub fn process_and_respond(
);
}
} else {
eprintln!(" SecurePayload decryption/verification failed");
secure_status = String::from("SecurePayload: decryption/verification FAILED");
}
} else {
eprintln!(" SecurePayload cannot be verified; no client public key available");
secure_status = String::from("SecurePayload: no client public key available");
}
}

View file

@ -1,9 +1,11 @@
use std::fs;
use mtp::crypto::{Ed25519Signer, Keyring, MlDsaSigner};
use mtp::crypto::kem::HybridKem;
use mtp::crypto::{Ed25519Signer, Keyring, MlDsaSigner};
pub fn load_or_generate_host_keys(path: &str) -> Result<(u64, Keyring), Box<dyn std::error::Error>> {
pub fn load_or_generate_host_keys(
path: &str,
) -> Result<(u64, Keyring), Box<dyn std::error::Error>> {
if let Ok(data) = fs::read_to_string(path) {
let json: serde_json::Value = serde_json::from_str(&data)?;
let hid = json["host_id"].as_u64().unwrap_or(1);
@ -27,6 +29,14 @@ pub fn load_or_generate_host_keys(path: &str) -> Result<(u64, Keyring), Box<dyn
}
pub fn export_host_public_keys(host_keyring: &Keyring) -> Result<(), Box<dyn std::error::Error>> {
let public_key_bundle_hex = hex::encode(host_keyring.public_key_bundle().as_bytes());
fs::write("host_public_key_bundle.hex", &public_key_bundle_hex)?;
fs::create_dir_all("web-client/public")?;
fs::write(
"web-client/public/host_public_key_bundle.hex",
&public_key_bundle_hex,
)?;
fs::write(
"host_enc_kem_pk.bin",
host_keyring.kem_public_key.as_bytes(),

View file

@ -5,10 +5,34 @@ mod tls;
use mtp::host::{HostConfig, MTPHost};
use mtp::type_map::TypeMap;
use std::path::Path;
fn dev_cert_paths() -> (String, String) {
let cert = std::env::var("MTP_DEV_CERT").unwrap_or_else(|_| {
if Path::new("example-usage/dev-cert/cert.pem").exists() {
"example-usage/dev-cert/cert.pem".to_string()
} else {
"dev-cert/cert.pem".to_string()
}
});
let key = std::env::var("MTP_DEV_KEY").unwrap_or_else(|_| {
if Path::new("example-usage/dev-cert/key.pem").exists() {
"example-usage/dev-cert/key.pem".to_string()
} else {
"dev-cert/key.pem".to_string()
}
});
(cert, key)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let (cert_pem, key_pem) = tls::load_or_generate_tls("server.pem", "server.key")?;
let (cert_path, key_path) = dev_cert_paths();
let (cert_pem, key_pem) = tls::load_or_generate_tls(&cert_path, &key_path)?;
let cert_hash = tls::certificate_sha256_hex(&cert_pem)?;
tls::export_webtransport_cert_hash(&cert_hash)?;
println!("WebTransport certificate sha256: {cert_hash}");
let (host_id, host_keyring) = keys::load_or_generate_host_keys("host_keys.json")?;
keys::export_host_public_keys(&host_keyring)?;
@ -21,7 +45,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let clients_for_get = clients.clone();
let get_existing_user = Box::new(move |id: u64| -> Option<mtp::crypto::PublicKeyBundle> {
clients_for_get.lock().unwrap().get(&id).cloned()
let result = clients_for_get.lock().unwrap().get(&id).cloned();
if result.is_some() {
println!("Auth lookup: client ID {id} found");
} else {
eprintln!("Auth lookup: unknown client ID {id}");
}
result
});
let clients_for_register = clients.clone();
@ -33,7 +63,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let id = *nid;
*nid += 1;
db.insert(id, bundle);
std::fs::write(&clients_path, serde_json::to_string_pretty(&*db).unwrap()).ok();
match serde_json::to_string_pretty(&*db) {
Ok(json) => match std::fs::write(&clients_path, json) {
Ok(()) => {}
Err(e) => eprintln!("Failed to persist client database to {clients_path}: {e}"),
},
Err(e) => eprintln!("Failed to serialize client database after registering {id}: {e}"),
}
println!("Registered new client with ID: {}", id);
id
});

View file

@ -1,4 +1,7 @@
use std::fs;
use std::path::Path;
use base64::Engine;
pub fn load_or_generate_tls(
cert_path: &str,
@ -10,6 +13,12 @@ pub fn load_or_generate_tls(
}
println!("Generating self-signed TLS certificate ...");
if let Some(parent) = Path::new(cert_path).parent() {
fs::create_dir_all(parent)?;
}
if let Some(parent) = Path::new(key_path).parent() {
fs::create_dir_all(parent)?;
}
let key_pair = rcgen::KeyPair::generate()?;
let params = rcgen::CertificateParams::new(vec!["localhost".into(), "127.0.0.1".into()])?;
let cert = params.self_signed(&key_pair)?;
@ -23,3 +32,39 @@ pub fn load_or_generate_tls(
Ok((cert_str.into_bytes(), key_str.into_bytes()))
}
pub fn certificate_sha256_hex(cert: &[u8]) -> Result<String, Box<dyn std::error::Error>> {
let der = if cert.starts_with(b"-----BEGIN CERTIFICATE-----") {
let pem = std::str::from_utf8(cert)?;
let base64 = pem
.lines()
.filter(|line| !line.starts_with("-----"))
.collect::<String>();
base64::engine::general_purpose::STANDARD.decode(base64)?
} else {
cert.to_vec()
};
Ok(hex::encode(mtp::crypto::sha256(&der)))
}
pub fn export_webtransport_cert_hash(hash: &str) -> Result<(), Box<dyn std::error::Error>> {
let public_dir = if Path::new("web-client").exists() {
Path::new("web-client/public")
} else {
Path::new("example-usage/web-client/public")
};
fs::create_dir_all(public_dir)?;
fs::write(public_dir.join("mtp_dev_cert_hash.txt"), hash)?;
let dev_cert_dir = if Path::new("dev-cert").exists() {
Path::new("dev-cert")
} else {
Path::new("example-usage/dev-cert")
};
if dev_cert_dir.exists() {
fs::write(dev_cert_dir.join("sha256.txt"), hash)?;
}
Ok(())
}