clm_rust_core/layer3/
wireguard.rs1use x25519_dalek::{PublicKey, StaticSecret};
10use rand::rngs::OsRng;
11use serde::{Serialize, Deserialize};
12use std::net::SocketAddr;
13
14#[derive(Clone, Serialize, Deserialize)]
20pub struct WgKeypair {
21 private_key: [u8; 32],
22 public_key: [u8; 32],
23}
24
25impl WgKeypair {
26 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 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 pub fn public_key_hex(&self) -> String {
49 hex::encode(self.public_key)
50 }
51
52 pub fn private_key_hex(&self) -> String {
55 hex::encode(self.private_key)
56 }
57
58 pub fn public_key_bytes(&self) -> &[u8; 32] {
60 &self.public_key
61 }
62
63 pub fn private_key_bytes(&self) -> &[u8; 32] {
65 &self.private_key
66 }
67
68 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
88pub 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#[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
112pub 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 let _shared_secret = local_keypair.diffie_hellman(&peer_public_key);
139
140 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 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 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 assert_eq!(alice_shared, bob_shared);
202 assert_eq!(alice_shared.len(), 32);
204 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}