| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| use ed25519_dalek::{Signer, SigningKey, Verifier, VerifyingKey}; |
|
|
| use sha2::{Sha256, Digest}; |
| use std::collections::{HashMap, HashSet}; |
| use std::path::Path; |
|
|
| |
| |
| |
| |
| |
| 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() { |
| |
| 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(); |
|
|
| |
| |
| 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); |
| } |
|
|
| |
| if seal_path.exists() { |
| if verify_seal(&signing_key, &key_path, config_dir) { |
| |
| return (signing_key, verifying_key); |
| } |
| |
| 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 { |
| |
| eprintln!("[SPF] Identity seal created for existing key"); |
| write_seal(&signing_key, &key_path, config_dir); |
| |
| 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::<serde_json::Value>(&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); |
| } |
| } |
|
|
| |
| generate_fresh_identity(config_dir) |
| } |
|
|
| |
| 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(&signing_key, &key_path, config_dir); |
|
|
| |
| 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) |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| #[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 } |
|
|
| |
| |
| fn seal_message(key_path: &Path, config_dir: &Path) -> Vec<u8> { |
| 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() |
| } |
|
|
| |
| 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(); |
| } |
|
|
| |
| 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() |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| |
| 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() |
| } |
|
|
| |
| |
| |
| |
| |
| |
| pub fn derive_peer_api_key(my_signing_key: &SigningKey, their_pub_hex: &str) -> Option<String> { |
| 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, |
| }; |
| |
| 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 |
| }; |
| |
| 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()) |
| } |
|
|
| |
| |
| 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::<serde_json::Value>(&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(); |
| } |
| } |
| } |
| |
| } |
|
|
| |
| |
| |
|
|
| 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(); |
| } |
| |
| 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(); |
| } |
| } |
|
|
| |
| |
| |
| pub fn load_trusted_keys(groups_dir: &Path) -> HashSet<String> { |
| 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 |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| #[derive(Debug, Clone)] |
| pub struct PeerInfo { |
| pub key: String, |
| pub addr: Vec<String>, |
| pub name: String, |
| pub role: crate::config::AgentRole, |
| } |
|
|
| |
| |
| |
| pub fn load_peers(groups_dir: &Path) -> HashMap<String, PeerInfo> { |
| 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::<serde_json::Value>(&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::<crate::config::AgentRole>( |
| 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 |
| } |
|
|
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| pub fn boot_integrity_check() { |
| let root = crate::paths::spf_root(); |
| let home = crate::paths::actual_home(); |
|
|
| |
| |
| |
| |
| let current_exe = std::env::current_exe() |
| .ok() |
| .and_then(|p| p.canonicalize().ok()) |
| .map(|p| p.to_string_lossy().to_string()); |
|
|
| |
| let mcp_json_paths = [ |
| home.join(".mcp.json"), |
| root.join("LIVE/LMDB5/.mcp.json"), |
| ]; |
|
|
| 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::<serde_json::Value>(&content) { |
| |
| 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() { |
| |
| 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."); |
| } |
| } |
| } |
| } |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| let rogue_dirs = [ |
| |
| (home.join(".qwen"), "Home-level .qwen/ directory"), |
| (home.join(".xlaude"), "Home-level .xlaude/ directory"), |
| |
| (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); |
| |
| 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"); |
| } |
|
|