//! WireGuard and AmneziaWG `.conf` files: their sections, and a profile as a sing-box //! WireGuard endpoint (upstream's `warp_outbound.py`). use serde_json::{Value, json}; /// The AmneziaWG `[Interface]` keys, lowercased, with their spelling. sing-box speaks plain /// WireGuard and has no use for them. pub const AWG_INTERFACE_FIELDS: [(&str, &str); 25] = [ ("jc", "Jc"), ("jmin", "Jmin"), ("jmax", "Jmax"), ("s1", "S1"), ("s2", "S2"), ("s3", "S3"), ("s4", "S4"), ("h1", "H1"), ("h2", "H2"), ("h3", "H3"), ("h4", "H4"), ("i1", "I1"), ("i2", "I2"), ("i3", "I3"), ("i4", "I4"), ("i5", "I5"), ("headerprotectionkey", "HeaderProtectionKey"), ("contentpaddingaddition", "ContentPaddingAddition"), ("rekeyaftertime", "RekeyAfterTime"), ("rekeytimeout", "RekeyTimeout"), ("rejectaftertime", "RejectAfterTime"), ("keepalivetimeout", "KeepaliveTimeout"), ("maxhandshakeattempts", "MaxHandshakeAttempts"), ("randomtrailers", "RandomTrailers"), ("disablecookies", "DisableCookies"), ]; /// wg-quick keys that run commands or rewrite the file: refused in imported configs unless /// `allowConfigHooks`. pub const FORBIDDEN_WG_QUICK_KEYS: [&str; 5] = ["preup", "postup", "predown", "postdown", "saveconfig"]; pub type Section = (String, Vec<(String, String)>); /// Each `[Section]`, lowercased, with its `key = value` lines in order; keys lowercased, /// comments (`#`, `;`) and lines outside a section dropped. pub fn conf_sections(config: &str) -> Vec
{ let mut sections: Vec
= Vec::new(); for line in crate::links::py::splitlines(config) { let stripped = line.split('#').next().unwrap_or("").split(';').next().unwrap_or("").trim(); if stripped.starts_with('[') && stripped.ends_with(']') && stripped.len() >= 2 { sections.push((stripped[1..stripped.len() - 1].trim().to_lowercase(), Vec::new())); } else if let Some((key, value)) = stripped.split_once('=') { if let Some(last) = sections.last_mut() { last.1.push((key.trim().to_lowercase(), value.trim().to_owned())); } } } sections } fn section<'a>(sections: &'a [Section], name: &str) -> Option<&'a [(String, String)]> { sections.iter().find(|(n, _)| n == name).map(|(_, pairs)| pairs.as_slice()) } fn get<'a>(pairs: &'a [(String, String)], key: &str) -> Option<&'a str> { // dict(pairs): the last value of a repeated key wins. pairs.iter().rev().find(|(k, _)| k == key).map(|(_, v)| v.as_str()).filter(|v| !v.is_empty()) } fn split_list(value: &str) -> Vec { value.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect() } /// `host:port`, IPv6 in brackets. pub fn split_endpoint(endpoint: &str) -> Result<(String, u16), String> { let bad = || format!("endpoint '{endpoint}' is not host:port"); let (host, port) = endpoint.rsplit_once(':').ok_or_else(bad)?; if host.is_empty() || port.is_empty() || !port.chars().all(|c| c.is_ascii_digit()) { return Err(bad()); } let port: u16 = port.parse().map_err(|_| bad())?; Ok((host.trim_matches(|c| c == '[' || c == ']').to_owned(), port)) } /// A WireGuard profile as a sing-box `wireguard` endpoint tagged `tag`, the profile's /// endpoint replaced by `endpoint` when given. Also the AmneziaWG keys it had to drop. pub fn sing_box_endpoint(text: &str, tag: &str, endpoint: Option<&str>) -> Result<(Value, Vec<&'static str>), String> { let sections = conf_sections(text); let (Some(interface), Some(peer)) = (section(§ions, "interface"), section(§ions, "peer")) else { return Err("configuration requires [Interface] and [Peer] sections".into()); }; for (pairs, key) in [(interface, "privatekey"), (interface, "address"), (peer, "publickey"), (peer, "endpoint")] { if get(pairs, key).is_none() { return Err(format!("configuration has no {key}")); } } let (host, port) = split_endpoint(endpoint.unwrap_or_else(|| get(peer, "endpoint").unwrap()))?; let allowed = get(peer, "allowedips").map(split_list).filter(|l| !l.is_empty()); let mut sb_peer = json!({ "address": host, "port": port, "public_key": get(peer, "publickey").unwrap(), "allowed_ips": allowed.unwrap_or_else(|| vec!["0.0.0.0/0".into(), "::/0".into()]), }); if let Some(ka) = get(peer, "persistentkeepalive") { // AWG 3 profiles give a range ("25-35"); sing-box takes one value. let first = ka.split('-').next().unwrap_or(""); let interval: u32 = first.trim().parse().map_err(|_| format!("persistentkeepalive '{ka}' is not a number"))?; sb_peer["persistent_keepalive_interval"] = interval.into(); } if let Some(psk) = get(peer, "presharedkey") { sb_peer["pre_shared_key"] = psk.into(); } let mtu: u32 = match get(interface, "mtu") { Some(m) => m.parse().map_err(|_| format!("mtu '{m}' is not a number"))?, None => 1280, }; let endpoint = json!({ "type": "wireguard", "tag": tag, "address": split_list(get(interface, "address").unwrap()), "private_key": get(interface, "privatekey").unwrap(), "mtu": mtu, "peers": [sb_peer], }); let mut dropped: Vec<&'static str> = AWG_INTERFACE_FIELDS .iter() .filter(|(k, _)| interface.iter().any(|(key, _)| key == k)) .map(|(_, name)| *name) .collect(); dropped.sort_unstable(); Ok((endpoint, dropped)) } /// The wg-quick hooks a config would run. pub fn forbidden_keys(text: &str) -> Vec { let mut found: Vec = conf_sections(text) .into_iter() .flat_map(|(_, pairs)| pairs.into_iter().map(|(k, _)| k)) .filter(|k| FORBIDDEN_WG_QUICK_KEYS.contains(&k.as_str())) .collect(); found.sort(); found.dedup(); found } #[cfg(test)] mod tests { use super::*; const WGCF: &str = "[Interface]\nPrivateKey = cHJpdmF0ZQ==\nAddress = 172.16.0.2/32, 2606:4700:110::2/128\nDNS = 1.1.1.1\nMTU = 1280\nJc = 4\n\n[Peer]\nPublicKey = cHVibGlj\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = engage.cloudflareclient.com:2408 # comment\nPersistentKeepalive = 25-35\n"; #[test] fn a_wgcf_profile_becomes_an_endpoint() { let (ep, dropped) = sing_box_endpoint(WGCF, "warp", None).unwrap(); assert_eq!(ep["address"], json!(["172.16.0.2/32", "2606:4700:110::2/128"])); assert_eq!(ep["peers"][0]["address"], "engage.cloudflareclient.com"); assert_eq!(ep["peers"][0]["port"], 2408); assert_eq!(ep["peers"][0]["persistent_keepalive_interval"], 25); assert_eq!(dropped, ["Jc"]); let (ep, _) = sing_box_endpoint(WGCF, "warp", Some("[2606:4700:d0::a29f:c001]:500")).unwrap(); assert_eq!(ep["peers"][0]["address"], "2606:4700:d0::a29f:c001"); assert_eq!(ep["peers"][0]["port"], 500); } #[test] fn missing_pieces_are_named() { assert!(sing_box_endpoint("[Interface]\nPrivateKey = x\n", "w", None).unwrap_err().contains("[Peer]")); let no_ep = WGCF.replace("Endpoint", "#Endpoint"); assert_eq!(sing_box_endpoint(&no_ep, "w", None).unwrap_err(), "configuration has no endpoint"); } #[test] fn hooks_are_found() { assert_eq!(forbidden_keys("[Interface]\nPostUp = calc.exe\nSaveConfig = true\n"), ["postup", "saveconfig"]); } }