WASM
This commit is contained in:
parent
ade0c3cde4
commit
298253d6fa
31 changed files with 2899 additions and 276 deletions
21
example-usage/server/src/clients.rs
Normal file
21
example-usage/server/src/clients.rs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use mtp::crypto::PublicKeyBundle;
|
||||
|
||||
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,
|
||||
));
|
||||
Ok((clients, next_id))
|
||||
}
|
||||
139
example-usage/server/src/handlers.rs
Normal file
139
example-usage/server/src/handlers.rs
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
use mtp::codec::{CommunicationType, CommunicationValue, DataType, DataTypeId, DataValue, TypeMap};
|
||||
use mtp::crypto::{ChaCha20Poly1305, CryptoError, SignatureScheme, SignaturePublicKey, verify_ed25519};
|
||||
|
||||
struct Ed25519Verifier(SignaturePublicKey);
|
||||
|
||||
impl SignatureScheme for Ed25519Verifier {
|
||||
fn sign(&self, _msg: &[u8]) -> Result<Vec<u8>, CryptoError> {
|
||||
Err(CryptoError::SigningFailed)
|
||||
}
|
||||
fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<(), CryptoError> {
|
||||
verify_ed25519(&self.0, msg, signature)
|
||||
}
|
||||
}
|
||||
|
||||
fn derive_demo_key() -> [u8; 32] {
|
||||
mtp::crypto::derive_encryption_key(
|
||||
b"MTP-demo-shared-secret",
|
||||
b"MTP-demo-salt",
|
||||
b"encrypted-container-demo",
|
||||
)
|
||||
.expect("key derivation must succeed")
|
||||
}
|
||||
|
||||
pub fn process_and_respond(
|
||||
msg: &CommunicationValue,
|
||||
tm: &TypeMap,
|
||||
client_pk: Option<&mtp::crypto::PublicKeyBundle>,
|
||||
) -> CommunicationValue {
|
||||
let desc_id = DataTypeId(tm.data_id_enum(DataType::Description).unwrap());
|
||||
let ts_id = DataTypeId(tm.data_id_enum(DataType::Timestamp).unwrap());
|
||||
let data_id = DataTypeId(tm.data_id_enum(DataType::Data).unwrap());
|
||||
let flags_id = DataTypeId(tm.data_id_enum(DataType::Flags).unwrap());
|
||||
let value_id = DataTypeId(tm.data_id_enum(DataType::Value).unwrap());
|
||||
let bin_id = DataTypeId(tm.data_id_enum(DataType::BinaryData).unwrap());
|
||||
let items_id = DataTypeId(tm.data_id_enum(DataType::Items).unwrap());
|
||||
let enc_id = DataTypeId(tm.data_id_enum(DataType::EncryptedPayload).unwrap());
|
||||
let sig_id = DataTypeId(tm.data_id_enum(DataType::SignedPayload).unwrap());
|
||||
let secure_id = DataTypeId(tm.data_id_enum(DataType::SecurePayload).unwrap());
|
||||
|
||||
let description = msg.get_data(desc_id);
|
||||
let timestamp = msg.get_data(ts_id);
|
||||
let data = msg.get_data(data_id);
|
||||
let flags = msg.get_data(flags_id);
|
||||
let value = msg.get_data(value_id);
|
||||
let binary = msg.get_data(bin_id);
|
||||
let items = msg.get_data(items_id);
|
||||
|
||||
println!(
|
||||
" Description: {}",
|
||||
description.as_str().unwrap_or("(missing)")
|
||||
);
|
||||
println!(" Timestamp: {:?}", timestamp.as_unsigned_number());
|
||||
println!(" Data: {}", data.as_str().unwrap_or("(missing)"));
|
||||
println!(" Flags: {:?}", flags.as_bool());
|
||||
println!(" Value: {:?}", value.as_float());
|
||||
println!(" Binary: {:?}", binary.as_bytes());
|
||||
println!(" Items: {:?}", items.as_array());
|
||||
|
||||
let cipher = ChaCha20Poly1305::new(derive_demo_key());
|
||||
|
||||
let mut enc_status = String::from("EncryptedPayload: not present");
|
||||
let mut sig_status = String::from("SignedPayload: not present");
|
||||
let mut secure_status = String::from("SecurePayload: not present");
|
||||
|
||||
let enc = msg.get_data(enc_id);
|
||||
if matches!(enc, DataValue::EncryptedContainer(_)) {
|
||||
let mut dv = enc.clone();
|
||||
if dv.decrypt_into_container(&cipher, b"demo-aad").is_some() {
|
||||
if let Some(entries) = dv.as_container() {
|
||||
println!(" Decrypted EncryptedPayload: {:?}", entries);
|
||||
enc_status = format!("EncryptedPayload decrypted OK ({} entries)", entries.len());
|
||||
}
|
||||
} else {
|
||||
enc_status = String::from("EncryptedPayload: decryption FAILED");
|
||||
}
|
||||
}
|
||||
|
||||
let sig = msg.get_data(sig_id);
|
||||
if matches!(sig, DataValue::SignedContainer(_)) {
|
||||
if let Some(pk_bundle) = client_pk {
|
||||
let verifier = Ed25519Verifier(pk_bundle.sig_cl_public_key.clone());
|
||||
let mut dv = sig.clone();
|
||||
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());
|
||||
}
|
||||
} else {
|
||||
sig_status = String::from("SignedPayload: verification FAILED");
|
||||
}
|
||||
} else {
|
||||
sig_status = String::from("SignedPayload: no client public key available");
|
||||
}
|
||||
}
|
||||
|
||||
let secure = msg.get_data(secure_id);
|
||||
if matches!(secure, DataValue::SignedEncryptedContainer(_)) {
|
||||
if let Some(pk_bundle) = client_pk {
|
||||
let verifier = Ed25519Verifier(pk_bundle.sig_cl_public_key.clone());
|
||||
let mut dv = secure.clone();
|
||||
if dv.decrypt_signed_encrypted_container(&cipher, b"demo-aad").is_some()
|
||||
&& dv.verify_into_container(&verifier).is_some()
|
||||
{
|
||||
if let Some(entries) = dv.as_container() {
|
||||
println!(" Verified SecurePayload: {:?}", entries);
|
||||
secure_status = format!(
|
||||
"SecurePayload decrypted+verified OK ({} entries)",
|
||||
entries.len()
|
||||
);
|
||||
}
|
||||
} else {
|
||||
secure_status = String::from("SecurePayload: decryption/verification FAILED");
|
||||
}
|
||||
} else {
|
||||
secure_status = String::from("SecurePayload: no client public key available");
|
||||
}
|
||||
}
|
||||
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
|
||||
CommunicationValue::from_comm(CommunicationType::Pong, tm)
|
||||
.add_data(desc_id, description.clone())
|
||||
.add_data(ts_id, DataValue::UnsignedNumber(now as u128))
|
||||
.add_data(
|
||||
data_id,
|
||||
DataValue::Str(format!(
|
||||
"{}. {}. {}.",
|
||||
enc_status, sig_status, secure_status
|
||||
)),
|
||||
)
|
||||
.add_data(flags_id, flags.clone())
|
||||
.add_data(value_id, value.clone())
|
||||
.add_data(bin_id, binary.clone())
|
||||
.add_data(items_id, items.clone())
|
||||
}
|
||||
40
example-usage/server/src/keys.rs
Normal file
40
example-usage/server/src/keys.rs
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
use std::fs;
|
||||
|
||||
use mtp::crypto::{Ed25519Signer, Keyring, MlDsaSigner};
|
||||
use mtp::crypto::kem::HybridKem;
|
||||
|
||||
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);
|
||||
let keyring = Keyring::from_bytes(&hex::decode(json["keyring"].as_str().unwrap())?)?;
|
||||
println!("Loaded host keys (ID: {})", hid);
|
||||
return Ok((hid, keyring));
|
||||
}
|
||||
|
||||
let (_ed_signer, sig_sk, sig_pk) = Ed25519Signer::generate();
|
||||
let (_pq_signer, sig_pq_sk, sig_pq_pk) = MlDsaSigner::generate();
|
||||
let (kem_sk, kem_pk) = HybridKem::generate_keypair();
|
||||
let keyring = Keyring::new(kem_pk, kem_sk, sig_pq_pk, sig_pq_sk, sig_pk, sig_sk);
|
||||
|
||||
let json = serde_json::json!({
|
||||
"host_id": 1,
|
||||
"keyring": hex::encode(keyring.to_bytes()),
|
||||
});
|
||||
fs::write(path, serde_json::to_string_pretty(&json)?)?;
|
||||
println!("Generated host keys -> {path}");
|
||||
Ok((1u64, keyring))
|
||||
}
|
||||
|
||||
pub fn export_host_public_keys(host_keyring: &Keyring) -> Result<(), Box<dyn std::error::Error>> {
|
||||
fs::write(
|
||||
"host_enc_kem_pk.bin",
|
||||
host_keyring.kem_public_key.as_bytes(),
|
||||
)?;
|
||||
fs::write("host_sig_pk.bin", host_keyring.sig_cl_public_key.as_bytes())?;
|
||||
fs::write(
|
||||
"host_sig_pq_pk.bin",
|
||||
host_keyring.sig_pq_public_key.as_bytes(),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -1,149 +1,34 @@
|
|||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::sync::{Arc, Mutex};
|
||||
mod clients;
|
||||
mod handlers;
|
||||
mod keys;
|
||||
mod tls;
|
||||
|
||||
use mtp::codec::{CommunicationType, CommunicationValue, DataType, DataTypeId, DataValue, TypeMap};
|
||||
use mtp::crypto::{Ed25519Signer, Keyring, MlDsaSigner, PublicKeyBundle, kem::HybridKem};
|
||||
use mtp::host::{HostConfig, MTPHost};
|
||||
|
||||
/*
|
||||
* Load an existing TLS certificate and key pair from disk. If neither
|
||||
* file exists, generate a self-signed certificate so the server is
|
||||
* immediately usable without external tooling.
|
||||
*/
|
||||
fn load_or_generate_tls(
|
||||
cert_path: &str,
|
||||
key_path: &str,
|
||||
) -> Result<(Vec<u8>, Vec<u8>), Box<dyn std::error::Error>> {
|
||||
if let (Ok(c), Ok(k)) = (fs::read(cert_path), fs::read(key_path)) {
|
||||
println!("Using existing TLS cert from {cert_path}");
|
||||
return Ok((c, k));
|
||||
}
|
||||
|
||||
println!("Generating self-signed TLS certificate ...");
|
||||
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)?;
|
||||
|
||||
let cert_str = cert.pem();
|
||||
let key_str = key_pair.serialize_pem();
|
||||
|
||||
fs::write(cert_path, cert_str.as_bytes())?;
|
||||
fs::write(key_path, key_str.as_bytes())?;
|
||||
println!("Wrote {cert_path} and {key_path}");
|
||||
|
||||
Ok((cert_str.into_bytes(), key_str.into_bytes()))
|
||||
}
|
||||
|
||||
/*
|
||||
* Load the host's Ed25519 identity from a JSON file, or generate a
|
||||
* fresh one and persist it. Clients need the corresponding public key
|
||||
* (exported separately as host_sig_pk.bin) to authenticate the host
|
||||
* during the handshake.
|
||||
*/
|
||||
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);
|
||||
let keyring = Keyring::from_bytes(&hex::decode(json["keyring"].as_str().unwrap())?)?;
|
||||
println!("Loaded host keys (ID: {})", hid);
|
||||
return Ok((hid, keyring));
|
||||
}
|
||||
|
||||
let (_ed_signer, sig_sk, sig_pk) = Ed25519Signer::generate();
|
||||
let (_pq_signer, sig_pq_sk, sig_pq_pk) = MlDsaSigner::generate();
|
||||
let (kem_sk, kem_pk) = HybridKem::generate_keypair();
|
||||
let keyring = Keyring::new(kem_pk, kem_sk, sig_pq_pk, sig_pq_sk, sig_pk, sig_sk);
|
||||
|
||||
let json = serde_json::json!({
|
||||
"host_id": 1,
|
||||
"keyring": hex::encode(keyring.to_bytes()),
|
||||
});
|
||||
fs::write(path, serde_json::to_string_pretty(&json)?)?;
|
||||
println!("Generated host keys -> {path}");
|
||||
Ok((1u64, keyring))
|
||||
}
|
||||
|
||||
/*
|
||||
* Load the client database from disk. Each entry maps a numeric
|
||||
* client ID to its PublicKeyBundle. next_id starts one past the
|
||||
* highest known ID (or 1000 if the DB is empty).
|
||||
*/
|
||||
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,
|
||||
));
|
||||
Ok((clients, next_id))
|
||||
}
|
||||
|
||||
/*
|
||||
* Build a Pong response carrying a description, a Unix timestamp, and
|
||||
* a custom payload according to the negotiated type map.
|
||||
*/
|
||||
fn build_pong_response(tm: &TypeMap) -> CommunicationValue {
|
||||
let timestamp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
|
||||
CommunicationValue::from_comm(CommunicationType::Pong, tm)
|
||||
.add_data(
|
||||
DataTypeId(tm.data_id_enum(DataType::Description).unwrap()),
|
||||
DataValue::Str("Hello from server!".into()),
|
||||
)
|
||||
.add_data(
|
||||
DataTypeId(tm.data_id_enum(DataType::Timestamp).unwrap()),
|
||||
DataValue::UnsignedNumber(timestamp as u128),
|
||||
)
|
||||
.add_data(
|
||||
DataTypeId(tm.data_id_enum(DataType::Data).unwrap()),
|
||||
DataValue::Str("custom payload".into()),
|
||||
)
|
||||
}
|
||||
use mtp::type_map::TypeMap;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let (cert_pem, key_pem) = load_or_generate_tls("server.pem", "server.key")?;
|
||||
let (host_id, host_keyring) = load_or_generate_host_keys("host_keys.json")?;
|
||||
let (cert_pem, key_pem) = tls::load_or_generate_tls("server.pem", "server.key")?;
|
||||
let (host_id, host_keyring) = keys::load_or_generate_host_keys("host_keys.json")?;
|
||||
keys::export_host_public_keys(&host_keyring)?;
|
||||
|
||||
// Export the host's public keys so clients can verify it
|
||||
fs::write(
|
||||
"host_enc_kem_pk.bin",
|
||||
host_keyring.kem_public_key.as_bytes(),
|
||||
)?;
|
||||
fs::write("host_sig_pk.bin", host_keyring.sig_cl_public_key.as_bytes())?;
|
||||
fs::write(
|
||||
"host_sig_pq_pk.bin",
|
||||
host_keyring.sig_pq_public_key.as_bytes(),
|
||||
)?;
|
||||
let (clients, next_id) = clients::load_client_db("clients.json")?;
|
||||
|
||||
let (clients, next_id) = load_client_db("clients.json")?;
|
||||
|
||||
// Clone the Arc so each closure owns its own reference
|
||||
let clients_for_get = clients.clone();
|
||||
let get_existing_user = Box::new(move |id: u64| -> Option<PublicKeyBundle> {
|
||||
let get_existing_user = Box::new(move |id: u64| -> Option<mtp::crypto::PublicKeyBundle> {
|
||||
clients_for_get.lock().unwrap().get(&id).cloned()
|
||||
});
|
||||
|
||||
let clients_for_register = clients.clone();
|
||||
let next_id_for_register = next_id.clone();
|
||||
let clients_path = "clients.json".to_string();
|
||||
let complete_register = Box::new(move |bundle: PublicKeyBundle| -> u64 {
|
||||
let complete_register = Box::new(move |bundle: mtp::crypto::PublicKeyBundle| -> u64 {
|
||||
let mut db = clients_for_register.lock().unwrap();
|
||||
let mut nid = next_id_for_register.lock().unwrap();
|
||||
let id = *nid;
|
||||
*nid += 1;
|
||||
db.insert(id, bundle);
|
||||
fs::write(&clients_path, serde_json::to_string_pretty(&*db).unwrap()).ok();
|
||||
std::fs::write(&clients_path, serde_json::to_string_pretty(&*db).unwrap()).ok();
|
||||
println!("Registered new client with ID: {}", id);
|
||||
id
|
||||
});
|
||||
|
|
@ -177,7 +62,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
match conn.receiver.receive().await {
|
||||
Ok(msg) => {
|
||||
println!("Received: {msg}");
|
||||
let response = build_pong_response(tm);
|
||||
let response =
|
||||
handlers::process_and_respond(&msg, tm, conn.client_public_key.as_ref());
|
||||
println!("Sending: {response}");
|
||||
conn.sender.send(&response).await?;
|
||||
}
|
||||
|
|
|
|||
25
example-usage/server/src/tls.rs
Normal file
25
example-usage/server/src/tls.rs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
use std::fs;
|
||||
|
||||
pub fn load_or_generate_tls(
|
||||
cert_path: &str,
|
||||
key_path: &str,
|
||||
) -> Result<(Vec<u8>, Vec<u8>), Box<dyn std::error::Error>> {
|
||||
if let (Ok(c), Ok(k)) = (fs::read(cert_path), fs::read(key_path)) {
|
||||
println!("Using existing TLS cert from {cert_path}");
|
||||
return Ok((c, k));
|
||||
}
|
||||
|
||||
println!("Generating self-signed TLS certificate ...");
|
||||
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)?;
|
||||
|
||||
let cert_str = cert26.pem();
|
||||
let key_str = key_pair.serialize_pem();
|
||||
|
||||
fs::write(cert_path, cert_str.as_bytes())?;
|
||||
fs::write(key_path, key_str.as_bytes())?;
|
||||
println!("Wrote {cert_path} and {key_path}");
|
||||
|
||||
Ok((cert_str.into_bytes(), key_str.into_bytes()))
|
||||
}
|
||||
Loading…
Reference in a new issue