use x25519_dalek::{PublicKey, StaticSecret};
use rand::rngs::OsRng;
use serde::{Serialize, Deserialize};
use std::net::SocketAddr;
#[derive(Clone, Serialize, Deserialize)]
pub struct WgKeypair {
private_key: [u8; 32],
public_key: [u8; 32],
}
impl WgKeypair {
pub fn generate() -> Self {
let secret = StaticSecret::random_from_rng(OsRng);
let public = PublicKey::from(&secret);
Self {
private_key: secret.to_bytes(),
public_key: public.to_bytes(),
}
}
pub fn from_seed(seed: &[u8; 32]) -> Self {
let secret = StaticSecret::from(*seed);
let public = PublicKey::from(&secret);
Self {
private_key: secret.to_bytes(),
public_key: public.to_bytes(),
}
}
pub fn public_key_hex(&self) -> String {
hex::encode(self.public_key)
}
pub fn private_key_hex(&self) -> String {
hex::encode(self.private_key)
}
pub fn public_key_bytes(&self) -> &[u8; 32] {
&self.public_key
}
pub fn private_key_bytes(&self) -> &[u8; 32] {
&self.private_key
}
pub fn diffie_hellman(&self, peer_public_key: &[u8; 32]) -> [u8; 32] {
let secret = StaticSecret::from(self.private_key);
let peer_public = PublicKey::from(*peer_public_key);
let shared = secret.diffie_hellman(&peer_public);
shared.to_bytes()
}
}
impl std::fmt::Debug for WgKeypair {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WgKeypair")
.field("public_key", &self.public_key_hex())
.field("private_key", &"[REDACTED]")
.finish()
}
}
pub fn parse_public_key_hex(hex_str: &str) -> Result<[u8; 32], String> {
let bytes = hex::decode(hex_str).map_err(|e| format!("Invalid hex: {}", e))?;
if bytes.len() != 32 {
return Err(format!("Public key must be 32 bytes, got {}", bytes.len()));
}
let mut arr = [0u8; 32];
arr.copy_from_slice(&bytes);
Ok(arr)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WgTunnel {
pub interface_name: String,
pub peer_addr: SocketAddr,
pub virtual_ip: String,
pub peer_public_key: String,
}
pub fn establish_wireguard_tunnel(
peer_ip: &str,
peer_port: u16,
peer_wg_pubkey_hex: &str,
local_keypair: &WgKeypair,
_local_virtual_ip: &str,
peer_virtual_ip: &str,
) -> Result<WgTunnel, String> {
let peer_public_key = parse_public_key_hex(peer_wg_pubkey_hex)?;
let _shared_secret = local_keypair.diffie_hellman(&peer_public_key);
let peer_addr: SocketAddr = format!("{}:{}", peer_ip, peer_port)
.parse()
.map_err(|e| format!("Invalid peer address {}:{}: {}", peer_ip, peer_port, e))?;
let interface_name = format!("wg{}", &peer_wg_pubkey_hex[..8]);
Ok(WgTunnel {
interface_name,
peer_addr,
virtual_ip: peer_virtual_ip.to_string(),
peer_public_key: peer_wg_pubkey_hex.to_string(),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_keypair_generation_produces_32_byte_keys() {
let kp = WgKeypair::generate();
assert_eq!(kp.public_key_bytes().len(), 32);
assert_eq!(kp.private_key_bytes().len(), 32);
}
#[test]
fn test_public_key_hex_is_64_chars() {
let kp = WgKeypair::generate();
let hex = kp.public_key_hex();
assert_eq!(hex.len(), 64);
assert!(hex.chars().all(|c| c.is_ascii_hexdigit()));
}
#[test]
fn test_deterministic_generation_from_seed() {
let seed = [42u8; 32];
let kp1 = WgKeypair::from_seed(&seed);
let kp2 = WgKeypair::from_seed(&seed);
assert_eq!(kp1.public_key_hex(), kp2.public_key_hex());
assert_eq!(kp1.private_key_hex(), kp2.private_key_hex());
}
#[test]
fn test_different_seeds_produce_different_keypairs() {
let kp1 = WgKeypair::from_seed(&[1u8; 32]);
let kp2 = WgKeypair::from_seed(&[2u8; 32]);
assert_ne!(kp1.public_key_hex(), kp2.public_key_hex());
}
#[test]
fn test_diffie_hellman_produces_shared_secret() {
let alice = WgKeypair::generate();
let bob = WgKeypair::generate();
let alice_shared = alice.diffie_hellman(bob.public_key_bytes());
let bob_shared = bob.diffie_hellman(alice.public_key_bytes());
assert_eq!(alice_shared, bob_shared);
assert_eq!(alice_shared.len(), 32);
assert!(alice_shared.iter().any(|&b| b != 0));
}
#[test]
fn test_parse_public_key_hex_valid() {
let kp = WgKeypair::generate();
let hex = kp.public_key_hex();
let parsed = parse_public_key_hex(&hex).unwrap();
assert_eq!(parsed, *kp.public_key_bytes());
}
#[test]
fn test_parse_public_key_hex_invalid_length() {
let result = parse_public_key_hex("abc123");
assert!(result.is_err());
assert!(result.unwrap_err().contains("32 bytes"));
}
#[test]
fn test_parse_public_key_hex_invalid_hex() {
let result = parse_public_key_hex(&"zz".repeat(32));
assert!(result.is_err());
}
#[test]
fn test_establish_wireguard_tunnel() {
let alice = WgKeypair::from_seed(&[1u8; 32]);
let bob = WgKeypair::from_seed(&[2u8; 32]);
let tunnel = establish_wireguard_tunnel(
"127.0.0.1",
51820,
&bob.public_key_hex(),
&alice,
"10.0.0.1",
"10.0.0.2",
).unwrap();
assert_eq!(tunnel.peer_addr, "127.0.0.1:51820".parse().unwrap());
assert_eq!(tunnel.virtual_ip, "10.0.0.2");
assert_eq!(tunnel.peer_public_key, bob.public_key_hex());
assert!(tunnel.interface_name.starts_with("wg"));
}
#[test]
fn test_establish_wireguard_tunnel_invalid_pubkey() {
let kp = WgKeypair::generate();
let result = establish_wireguard_tunnel(
"127.0.0.1",
51820,
"invalid",
&kp,
"10.0.0.1",
"10.0.0.2",
);
assert!(result.is_err());
}
#[test]
fn test_establish_wireguard_tunnel_invalid_addr() {
let alice = WgKeypair::from_seed(&[1u8; 32]);
let bob = WgKeypair::from_seed(&[2u8; 32]);
let result = establish_wireguard_tunnel(
"999.999.999.999",
51820,
&bob.public_key_hex(),
&alice,
"10.0.0.1",
"10.0.0.2",
);
assert!(result.is_err());
}
#[test]
fn test_debug_does_not_leak_private_key() {
let kp = WgKeypair::generate();
let debug_str = format!("{:?}", kp);
assert!(debug_str.contains("[REDACTED]"));
assert!(!debug_str.contains(&kp.private_key_hex()));
}
}