Skip to main content

clm_rust_core/layer3/
wireguard.rs

1//! WireGuard key exchange and tunnel establishment for Sprint 140.1.
2//!
3//! Provides X25519 keypair generation, hex encoding for mDNS announcement,
4//! and userspace WireGuard tunnel establishment using `boringtun`-style
5//! peer configuration. The keypair uses `x25519-dalek` which is the standard
6//! Rust implementation of Curve25519 Diffie-Hellman key exchange — the same
7//! curve used by WireGuard for session key agreement.
8
9use x25519_dalek::{PublicKey, StaticSecret};
10use rand::rngs::OsRng;
11use serde::{Serialize, Deserialize};
12use std::net::SocketAddr;
13
14/// WireGuard keypair for a PKC node.
15///
16/// The private key is 32 bytes of random data on Curve25519.
17/// The public key is the corresponding X25519 public key.
18/// The public key is announced via mDNS so peers can establish tunnels.
19#[derive(Clone, Serialize, Deserialize)]
20pub struct WgKeypair {
21    private_key: [u8; 32],
22    public_key: [u8; 32],
23}
24
25impl WgKeypair {
26    /// Generate a new WireGuard keypair using the OS CSPRNG.
27    pub fn generate() -> Self {
28        let secret = StaticSecret::random_from_rng(OsRng);
29        let public = PublicKey::from(&secret);
30        Self {
31            private_key: secret.to_bytes(),
32            public_key: public.to_bytes(),
33        }
34    }
35
36    /// Generate a WireGuard keypair from a deterministic 32-byte seed.
37    /// Used for testing — production code should use `generate()`.
38    pub fn from_seed(seed: &[u8; 32]) -> Self {
39        let secret = StaticSecret::from(*seed);
40        let public = PublicKey::from(&secret);
41        Self {
42            private_key: secret.to_bytes(),
43            public_key: public.to_bytes(),
44        }
45    }
46
47    /// Returns the public key as a 64-character hex string for mDNS announcement.
48    pub fn public_key_hex(&self) -> String {
49        hex::encode(self.public_key)
50    }
51
52    /// Returns the private key as a 64-character hex string.
53    /// Used for debugging and testing only — never log or expose in production.
54    pub fn private_key_hex(&self) -> String {
55        hex::encode(self.private_key)
56    }
57
58    /// Returns the raw 32-byte public key.
59    pub fn public_key_bytes(&self) -> &[u8; 32] {
60        &self.public_key
61    }
62
63    /// Returns the raw 32-byte private key.
64    pub fn private_key_bytes(&self) -> &[u8; 32] {
65        &self.private_key
66    }
67
68    /// Perform X25519 Diffie-Hellman with a peer's public key to derive
69    /// a shared secret. This shared secret is the basis for the WireGuard
70    /// session key.
71    pub fn diffie_hellman(&self, peer_public_key: &[u8; 32]) -> [u8; 32] {
72        let secret = StaticSecret::from(self.private_key);
73        let peer_public = PublicKey::from(*peer_public_key);
74        let shared = secret.diffie_hellman(&peer_public);
75        shared.to_bytes()
76    }
77}
78
79impl std::fmt::Debug for WgKeypair {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        f.debug_struct("WgKeypair")
82            .field("public_key", &self.public_key_hex())
83            .field("private_key", &"[REDACTED]")
84            .finish()
85    }
86}
87
88/// Parse a 64-character hex string into a 32-byte public key.
89pub fn parse_public_key_hex(hex_str: &str) -> Result<[u8; 32], String> {
90    let bytes = hex::decode(hex_str).map_err(|e| format!("Invalid hex: {}", e))?;
91    if bytes.len() != 32 {
92        return Err(format!("Public key must be 32 bytes, got {}", bytes.len()));
93    }
94    let mut arr = [0u8; 32];
95    arr.copy_from_slice(&bytes);
96    Ok(arr)
97}
98
99/// A WireGuard tunnel to a peer PKC node.
100///
101/// In the userspace implementation, the tunnel represents an established
102/// WireGuard session with a peer. The `virtual_ip` is the peer's address
103/// within the WireGuard overlay network.
104#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct WgTunnel {
106    pub interface_name: String,
107    pub peer_addr: SocketAddr,
108    pub virtual_ip: String,
109    pub peer_public_key: String,
110}
111
112/// Establish a WireGuard tunnel to a peer.
113///
114/// This performs the X25519 key exchange and creates a `WgTunnel` record
115/// representing the established session. In a full implementation, this
116/// would create a TUN device and start the WireGuard handshake. For now,
117/// it performs the cryptographic key exchange and records the tunnel
118/// metadata for the QUIC transport layer (Sprint 140.2) to use.
119///
120/// # Arguments
121/// * `peer_ip` - The peer's IP address (for the UDP endpoint)
122/// * `peer_port` - The peer's WireGuard UDP port
123/// * `peer_wg_pubkey_hex` - The peer's WireGuard public key as hex
124/// * `local_keypair` - This node's WireGuard keypair
125/// * `local_virtual_ip` - This node's virtual IP in the overlay
126/// * `peer_virtual_ip` - The peer's virtual IP in the overlay
127pub fn establish_wireguard_tunnel(
128    peer_ip: &str,
129    peer_port: u16,
130    peer_wg_pubkey_hex: &str,
131    local_keypair: &WgKeypair,
132    _local_virtual_ip: &str,
133    peer_virtual_ip: &str,
134) -> Result<WgTunnel, String> {
135    let peer_public_key = parse_public_key_hex(peer_wg_pubkey_hex)?;
136
137    // Perform X25519 Diffie-Hellman key exchange
138    let _shared_secret = local_keypair.diffie_hellman(&peer_public_key);
139
140    // Parse peer address
141    let peer_addr: SocketAddr = format!("{}:{}", peer_ip, peer_port)
142        .parse()
143        .map_err(|e| format!("Invalid peer address {}:{}: {}", peer_ip, peer_port, e))?;
144
145    // Generate interface name based on peer public key hash
146    let interface_name = format!("wg{}", &peer_wg_pubkey_hex[..8]);
147
148    Ok(WgTunnel {
149        interface_name,
150        peer_addr,
151        virtual_ip: peer_virtual_ip.to_string(),
152        peer_public_key: peer_wg_pubkey_hex.to_string(),
153    })
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    #[test]
161    fn test_keypair_generation_produces_32_byte_keys() {
162        let kp = WgKeypair::generate();
163        assert_eq!(kp.public_key_bytes().len(), 32);
164        assert_eq!(kp.private_key_bytes().len(), 32);
165    }
166
167    #[test]
168    fn test_public_key_hex_is_64_chars() {
169        let kp = WgKeypair::generate();
170        let hex = kp.public_key_hex();
171        assert_eq!(hex.len(), 64);
172        // Verify it's valid hex
173        assert!(hex.chars().all(|c| c.is_ascii_hexdigit()));
174    }
175
176    #[test]
177    fn test_deterministic_generation_from_seed() {
178        let seed = [42u8; 32];
179        let kp1 = WgKeypair::from_seed(&seed);
180        let kp2 = WgKeypair::from_seed(&seed);
181        assert_eq!(kp1.public_key_hex(), kp2.public_key_hex());
182        assert_eq!(kp1.private_key_hex(), kp2.private_key_hex());
183    }
184
185    #[test]
186    fn test_different_seeds_produce_different_keypairs() {
187        let kp1 = WgKeypair::from_seed(&[1u8; 32]);
188        let kp2 = WgKeypair::from_seed(&[2u8; 32]);
189        assert_ne!(kp1.public_key_hex(), kp2.public_key_hex());
190    }
191
192    #[test]
193    fn test_diffie_hellman_produces_shared_secret() {
194        let alice = WgKeypair::generate();
195        let bob = WgKeypair::generate();
196
197        let alice_shared = alice.diffie_hellman(bob.public_key_bytes());
198        let bob_shared = bob.diffie_hellman(alice.public_key_bytes());
199
200        // Both parties should derive the same shared secret
201        assert_eq!(alice_shared, bob_shared);
202        // Shared secret should be 32 bytes
203        assert_eq!(alice_shared.len(), 32);
204        // Shared secret should not be all zeros
205        assert!(alice_shared.iter().any(|&b| b != 0));
206    }
207
208    #[test]
209    fn test_parse_public_key_hex_valid() {
210        let kp = WgKeypair::generate();
211        let hex = kp.public_key_hex();
212        let parsed = parse_public_key_hex(&hex).unwrap();
213        assert_eq!(parsed, *kp.public_key_bytes());
214    }
215
216    #[test]
217    fn test_parse_public_key_hex_invalid_length() {
218        let result = parse_public_key_hex("abc123");
219        assert!(result.is_err());
220        assert!(result.unwrap_err().contains("32 bytes"));
221    }
222
223    #[test]
224    fn test_parse_public_key_hex_invalid_hex() {
225        let result = parse_public_key_hex(&"zz".repeat(32));
226        assert!(result.is_err());
227    }
228
229    #[test]
230    fn test_establish_wireguard_tunnel() {
231        let alice = WgKeypair::from_seed(&[1u8; 32]);
232        let bob = WgKeypair::from_seed(&[2u8; 32]);
233
234        let tunnel = establish_wireguard_tunnel(
235            "127.0.0.1",
236            51820,
237            &bob.public_key_hex(),
238            &alice,
239            "10.0.0.1",
240            "10.0.0.2",
241        ).unwrap();
242
243        assert_eq!(tunnel.peer_addr, "127.0.0.1:51820".parse().unwrap());
244        assert_eq!(tunnel.virtual_ip, "10.0.0.2");
245        assert_eq!(tunnel.peer_public_key, bob.public_key_hex());
246        assert!(tunnel.interface_name.starts_with("wg"));
247    }
248
249    #[test]
250    fn test_establish_wireguard_tunnel_invalid_pubkey() {
251        let kp = WgKeypair::generate();
252        let result = establish_wireguard_tunnel(
253            "127.0.0.1",
254            51820,
255            "invalid",
256            &kp,
257            "10.0.0.1",
258            "10.0.0.2",
259        );
260        assert!(result.is_err());
261    }
262
263    #[test]
264    fn test_establish_wireguard_tunnel_invalid_addr() {
265        let alice = WgKeypair::from_seed(&[1u8; 32]);
266        let bob = WgKeypair::from_seed(&[2u8; 32]);
267
268        let result = establish_wireguard_tunnel(
269            "999.999.999.999",
270            51820,
271            &bob.public_key_hex(),
272            &alice,
273            "10.0.0.1",
274            "10.0.0.2",
275        );
276        assert!(result.is_err());
277    }
278
279    #[test]
280    fn test_debug_does_not_leak_private_key() {
281        let kp = WgKeypair::generate();
282        let debug_str = format!("{:?}", kp);
283        assert!(debug_str.contains("[REDACTED]"));
284        assert!(!debug_str.contains(&kp.private_key_hex()));
285    }
286}