// SPF Smart Gateway - Cryptographic Identity // Copyright 2026 Joseph Stone - All Rights Reserved // // Ed25519 key pair management for SPF mesh authentication. // Each SPF instance generates a unique identity on first run. // Public keys are shared between peers via group files. // // Key storage: // LIVE/CONFIG/identity.key — Ed25519 private key (hex, 64 chars) // LIVE/CONFIG/identity.pub — Ed25519 public key (hex, 64 chars) // LIVE/CONFIG/identity.seal — Filesystem-bound clone detection seal // LIVE/CONFIG/groups/*.keys — Trusted peer public keys (one per line) // LIVE/CONFIG/groups/*.json — Peer info with addresses (key, addr, name, role) // // BLOCK SEC-3: boot_integrity_check() — verifies .mcp.json routing + scans for rogue agent configs use ed25519_dalek::{Signer, SigningKey, Verifier, VerifyingKey}; use sha2::{Sha256, Digest}; use std::collections::{HashMap, HashSet}; use std::path::Path; /// Ensure an Ed25519 identity exists with clone detection. /// - First boot: generate keypair + seal + derived API key /// - Normal boot: load keypair, verify seal, continue /// - Clone detected: archive old, generate new, update API key, preserve settings /// Returns (signing_key, verifying_key) — signature UNCHANGED. pub fn ensure_identity(config_dir: &Path) -> (SigningKey, VerifyingKey) { let key_path = config_dir.join("identity.key"); let seal_path = config_dir.join("identity.seal"); if key_path.exists() { // Load existing key pair let key_hex = std::fs::read_to_string(&key_path) .expect("Failed to read identity.key"); let key_bytes: [u8; 32] = hex::decode(key_hex.trim()) .expect("Invalid hex in identity.key") .try_into() .expect("identity.key must be exactly 32 bytes"); let signing_key = SigningKey::from_bytes(&key_bytes); let verifying_key = signing_key.verifying_key(); // CL-1: Self-test — verify key pair is mathematically valid // Catches file corruption that passes hex decode but garbles the key let test_msg = b"spf-identity-self-test-v1"; let test_sig = signing_key.sign(test_msg); if verifying_key.verify(test_msg, &test_sig).is_err() { eprintln!("[SPF] ⚠ IDENTITY CORRUPTED — key self-test failed"); eprintln!("[SPF] Archiving corrupted key, generating fresh credentials"); archive_old_identity(config_dir); return generate_fresh_identity(config_dir); } // Check seal if seal_path.exists() { if verify_seal(&signing_key, &key_path, config_dir) { // ORIGINAL — seal valid, normal boot return (signing_key, verifying_key); } // CLONE DETECTED — seal exists but doesn't match eprintln!("[SPF] ⚠ CLONE DETECTED — identity seal mismatch"); eprintln!("[SPF] Archiving cloned identity, generating fresh credentials"); archive_old_identity(config_dir); return generate_fresh_identity(config_dir); } else { // UPGRADE PATH — existing key, no seal (pre-seal version) eprintln!("[SPF] Identity seal created for existing key"); write_seal(&signing_key, &key_path, config_dir); // Also derive API key if http.json has empty api_key let http_json = config_dir.join("http.json"); if let Ok(content) = std::fs::read_to_string(&http_json) { if let Ok(config) = serde_json::from_str::(&content) { if config["api_key"].as_str().unwrap_or("").is_empty() { let api_key = derive_api_key(&signing_key); update_api_key_in_config(config_dir, &api_key); eprintln!("[SPF] API key derived from identity"); } } } return (signing_key, verifying_key); } } // FIRST BOOT — no identity exists generate_fresh_identity(config_dir) } /// Generate a complete fresh identity: keypair + seal + API key. fn generate_fresh_identity(config_dir: &Path) -> (SigningKey, VerifyingKey) { let key_path = config_dir.join("identity.key"); let pub_path = config_dir.join("identity.pub"); let signing_key = SigningKey::generate(&mut rand::rng()); let verifying_key = signing_key.verifying_key(); std::fs::create_dir_all(config_dir).ok(); std::fs::write(&key_path, hex::encode(signing_key.to_bytes())) .expect("Failed to write identity.key"); std::fs::write(&pub_path, hex::encode(verifying_key.to_bytes())) .expect("Failed to write identity.pub"); // Write seal bound to this instance write_seal(&signing_key, &key_path, config_dir); // Derive and write API key let api_key = derive_api_key(&signing_key); update_api_key_in_config(config_dir, &api_key); eprintln!("[SPF] Generated Ed25519 identity: {}", hex::encode(verifying_key.to_bytes())); eprintln!("[SPF] API key derived from identity"); (signing_key, verifying_key) } // ============================================================================ // IDENTITY SEAL — Clone detection via filesystem binding // ============================================================================ /// Get filesystem inode for a path (Unix/Android). /// Returns 0 on non-Unix platforms (falls back to path-only seal). #[cfg(unix)] fn get_inode(path: &Path) -> u64 { use std::os::unix::fs::MetadataExt; std::fs::metadata(path).map(|m| m.ino()).unwrap_or(0) } #[cfg(not(unix))] fn get_inode(_path: &Path) -> u64 { 0 } /// Build the canonical message that gets signed for the seal. /// Includes inode (changes on copy) + canonical path (changes on move/copy). fn seal_message(key_path: &Path, config_dir: &Path) -> Vec { let inode = get_inode(key_path); let canon = config_dir.canonicalize() .unwrap_or_else(|_| config_dir.to_path_buf()); format!("{}\n{}", inode, canon.to_string_lossy()).into_bytes() } /// Write identity.seal — Ed25519 signature over (inode + path). fn write_seal(signing_key: &SigningKey, key_path: &Path, config_dir: &Path) { let message = seal_message(key_path, config_dir); let signature = signing_key.sign(&message); let seal = serde_json::json!({ "inode": get_inode(key_path), "path": config_dir.canonicalize() .unwrap_or_else(|_| config_dir.to_path_buf()) .to_string_lossy(), "signature": hex::encode(signature.to_bytes()), }); let seal_path = config_dir.join("identity.seal"); std::fs::write(&seal_path, serde_json::to_string_pretty(&seal).unwrap_or_default()).ok(); } /// Verify identity.seal — returns true if seal matches current filesystem state. fn verify_seal(signing_key: &SigningKey, key_path: &Path, config_dir: &Path) -> bool { let seal_path = config_dir.join("identity.seal"); let content = match std::fs::read_to_string(&seal_path) { Ok(c) => c, Err(_) => return false, }; let seal: serde_json::Value = match serde_json::from_str(&content) { Ok(v) => v, Err(_) => return false, }; let sig_hex = match seal["signature"].as_str() { Some(s) => s, None => return false, }; let sig_bytes: [u8; 64] = match hex::decode(sig_hex) { Ok(b) if b.len() == 64 => match b.try_into() { Ok(arr) => arr, Err(_) => return false, }, _ => return false, }; let signature = ed25519_dalek::Signature::from_bytes(&sig_bytes); let verifying_key = signing_key.verifying_key(); let message = seal_message(key_path, config_dir); verifying_key.verify(&message, &signature).is_ok() } // ============================================================================ // API KEY DERIVATION — cryptographically bound to identity // ============================================================================ /// Derive an API key from the signing key. /// Deterministic, one-way (SHA256), domain-separated. /// One identity = one API key. Always. pub fn derive_api_key(signing_key: &SigningKey) -> String { let mut hasher = Sha256::new(); hasher.update(signing_key.to_bytes()); hasher.update(b"spf-api-key-v1"); hex::encode(hasher.finalize())[..48].to_string() } /// Derive a peer-specific API key using pseudo-ECDH key agreement. /// Both sides can compute this independently: /// Peer A: derive_peer_api_key(my_signing_key, peer_b_pub_hex) /// Peer B: derive_peer_api_key(my_signing_key, peer_a_pub_hex) /// This bridges mesh auth → HTTP auth: a mesh-trusted peer /// can derive a valid API key for HTTP endpoints. pub fn derive_peer_api_key(my_signing_key: &SigningKey, their_pub_hex: &str) -> Option { let their_bytes: [u8; 32] = match hex::decode(their_pub_hex) { Ok(b) if b.len() == 32 => match b.try_into() { Ok(arr) => arr, Err(_) => return None, }, _ => return None, }; // Ed25519 signing key → deterministic secret (domain-separated hash) let my_x25519 = { let mut hasher = Sha256::new(); hasher.update(my_signing_key.to_bytes()); hasher.update(b"spf-x25519-derive-v1"); let hash: [u8; 32] = hasher.finalize().into(); hash }; // Combine: SHA256(my_secret + their_pub + domain separator) let mut hasher = Sha256::new(); hasher.update(my_x25519); hasher.update(their_bytes); hasher.update(b"spf-peer-api-v1"); Some(hex::encode(hasher.finalize())[..48].to_string()) } /// Update only the api_key field in http.json, preserving all other settings. /// Uses serde_json::Value to avoid struct coupling and preserve unknown fields. fn update_api_key_in_config(config_dir: &Path, new_api_key: &str) { let http_json = config_dir.join("http.json"); if let Ok(content) = std::fs::read_to_string(&http_json) { if let Ok(mut config) = serde_json::from_str::(&content) { config["api_key"] = serde_json::Value::String(new_api_key.to_string()); if let Ok(updated) = serde_json::to_string_pretty(&config) { std::fs::write(&http_json, updated).ok(); } } } // If http.json doesn't exist yet, it will be created by HttpConfig::load() default path } // ============================================================================ // ARCHIVE — preserve old identity for audit trail // ============================================================================ fn archive_old_identity(config_dir: &Path) { let ts = chrono::Utc::now().format("%Y%m%dT%H%M%S").to_string(); let key_path = config_dir.join("identity.key"); let pub_path = config_dir.join("identity.pub"); let seal_path = config_dir.join("identity.seal"); if key_path.exists() { std::fs::rename(&key_path, config_dir.join(format!("identity.key.prior.{}", ts))).ok(); } if pub_path.exists() { std::fs::rename(&pub_path, config_dir.join(format!("identity.pub.prior.{}", ts))).ok(); } if seal_path.exists() { std::fs::rename(&seal_path, config_dir.join(format!("identity.seal.prior.{}", ts))).ok(); } // I-3 FIX: Remove TLS certs so they regenerate with new identity let tls_cert = config_dir.join("tls/cert.pem"); let tls_key = config_dir.join("tls/key.pem"); if tls_cert.exists() { std::fs::remove_file(&tls_cert).ok(); eprintln!("[SPF] TLS cert removed — will regenerate with new identity"); } if tls_key.exists() { std::fs::remove_file(&tls_key).ok(); } } /// Load all trusted public keys from group files in the groups directory. /// Each .keys file contains one hex-encoded public key per line. /// Lines starting with # are comments. Empty lines are ignored. pub fn load_trusted_keys(groups_dir: &Path) -> HashSet { let mut trusted = HashSet::new(); if let Ok(entries) = std::fs::read_dir(groups_dir) { for entry in entries.flatten() { let path = entry.path(); if path.extension().map(|e| e == "keys").unwrap_or(false) { if let Ok(content) = std::fs::read_to_string(&path) { for line in content.lines() { let key = line.split('#').next().unwrap_or("").trim(); if !key.is_empty() { trusted.insert(key.to_string()); } } } } } } if !trusted.is_empty() { eprintln!("[SPF] Loaded {} trusted keys from {:?}", trusted.len(), groups_dir); } trusted } // ============================================================================ // PEER INFO — structured peer data with addresses for mesh connectivity // ============================================================================ /// Peer information loaded from groups/*.json files. /// Carries addresses so iroh can connect directly without relay/mDNS/DHT. #[derive(Debug, Clone)] pub struct PeerInfo { pub key: String, pub addr: Vec, pub name: String, pub role: crate::config::AgentRole, } /// Load all peer info from JSON files in the groups directory. /// Each .json file contains: { "key": "hex...", "addr": ["ip:port", ...], "name": "...", "role": "..." } /// Returns HashMap keyed by public key hex string. pub fn load_peers(groups_dir: &Path) -> HashMap { let mut peers = HashMap::new(); if let Ok(entries) = std::fs::read_dir(groups_dir) { for entry in entries.flatten() { let path = entry.path(); if path.extension().map(|e| e == "json").unwrap_or(false) { if let Ok(content) = std::fs::read_to_string(&path) { if let Ok(val) = serde_json::from_str::(&content) { let key = val["key"].as_str().unwrap_or("").to_string(); if key.is_empty() { continue; } let addr = val["addr"].as_array() .map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect()) .unwrap_or_default(); let name = val["name"].as_str().unwrap_or("unknown").to_string(); let role = serde_json::from_value::( val.get("role").cloned().unwrap_or_else(|| serde_json::json!("orchestrator")) ).unwrap_or_default(); peers.insert(key.clone(), PeerInfo { key, addr, name, role }); } } } } } if !peers.is_empty() { eprintln!("[SPF] Loaded {} peer configs from {:?}", peers.len(), groups_dir); } peers } // ============================================================================ // BLOCK SEC-3 — Boot Integrity Check // Verifies .mcp.json routing and scans for rogue agent config directories. // Called from mcp::run() and mcp::run_worker() after identity initialization. // WARNING-ONLY — logs issues but does NOT block startup. // ============================================================================ /// Boot-time integrity check for MCP routing and agent configs. /// /// Checks: /// 1. .mcp.json binary path matches current executable (detects hijack) /// 2. Scans working directories for rogue agent config dirs (.qwen/, .xlaude/) /// /// This is informational only — warnings are logged to stderr. /// The gate's blocked_paths (SEC-2) provide the enforcement layer. pub fn boot_integrity_check() { let root = crate::paths::spf_root(); let home = crate::paths::actual_home(); // ── CHECK 1: .mcp.json binary path verification ────────────────────── // The .mcp.json file tells Claude Code which binary to use as the MCP server. // If an agent with native Write access modifies this file, it can redirect // ALL MCP tool calls to a different gate instance (confirmed exploit). let current_exe = std::env::current_exe() .ok() .and_then(|p| p.canonicalize().ok()) .map(|p| p.to_string_lossy().to_string()); // Check all known .mcp.json locations let mcp_json_paths = [ home.join(".mcp.json"), // Home-level (global) root.join("LIVE/LMDB5/.mcp.json"), // Primary work directory ]; for mcp_path in &mcp_json_paths { if mcp_path.exists() { if let Ok(content) = std::fs::read_to_string(mcp_path) { if let Ok(val) = serde_json::from_str::(&content) { // Extract the command field from mcpServers.spf-smart-gate let configured_binary = val .get("mcpServers") .and_then(|s| s.get("spf-smart-gate")) .and_then(|s| s.get("command")) .and_then(|v| v.as_str()) .unwrap_or(""); if !configured_binary.is_empty() { // Canonicalize the configured path for comparison let configured_canonical = std::path::Path::new(configured_binary) .canonicalize() .ok() .map(|p| p.to_string_lossy().to_string()); if let (Some(ref current), Some(ref configured)) = (¤t_exe, &configured_canonical) { if current != configured { eprintln!("[SPF] ⚠ SEC-3 WARNING: .mcp.json ROUTING MISMATCH"); eprintln!("[SPF] File: {:?}", mcp_path); eprintln!("[SPF] Configured: {}", configured); eprintln!("[SPF] Running: {}", current); eprintln!("[SPF] This may indicate a config hijack attempt."); } } } } } } } // ── CHECK 2: Rogue agent config directories ────────────────────────── // External AI agents (Qwen, xlaude) may create config directories // containing .mcp.json files that redirect tool calls. // These directories should not exist in work areas. let rogue_dirs = [ // Home-level agent configs (home.join(".qwen"), "Home-level .qwen/ directory"), (home.join(".xlaude"), "Home-level .xlaude/ directory"), // Work directory agent configs (inside SPFsmartGATE) (root.join("LIVE/LMDB5/.qwen"), "LMDB5 .qwen/ directory"), (root.join("LIVE/LMDB5/.xlaude"), "LMDB5 .xlaude/ directory"), ]; for (dir_path, description) in &rogue_dirs { if dir_path.exists() { eprintln!("[SPF] ⚠ SEC-3 WARNING: Rogue agent config detected"); eprintln!("[SPF] Found: {} at {:?}", description, dir_path); // Check if it contains an .mcp.json (escalates severity) let mcp_inside = dir_path.join(".mcp.json"); if mcp_inside.exists() { eprintln!("[SPF] ⚠ Contains .mcp.json — potential routing hijack file"); } } } eprintln!("[SPF] SEC-3: Boot integrity check complete"); }