- ps_core::awg: upstream's scripts/amneziawg_config.py, ported: a profile from a .conf, an AmneziaVPN vpn:// link (qCompress'd JSON or the compact .conf form, containers and DNS placeholders as upstream reads them) or declarative settings (with obfuscationFile's secrets); AWG 3's MTU default, the endpoint override, upstream's checks (no wg-quick hooks unless allowed, no control characters, one [Interface]); and the wireproxy configuration. Checked against links made by upstream's own encoder, output byte for byte. - wireproxy-awg for Windows, built from upstream's tag (pinned to its commit) with upstream's patches, by tools/build-wireproxy-awg.sh; in the release as a bundled component. Go joins the dev shell. - The service runs one per "userspace" AmneziaWG outbound and WARP device, on its loopback port with the hop login, its configuration below the protected state root; "singBox" profiles reach the renderer. wireproxy goes direct under the TUN. - End to end on Linux (an_amneziawg_tunnel): sing-box as the WireGuard server, the service's wireproxy as the client; a page through its listener and through the proxy's outbound, named inside the tunnel. - What is still to come and said: AmneziaWG as a system-wide VPN. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
636 lines
30 KiB
Rust
636 lines
30 KiB
Rust
//! AmneziaWG profiles as upstream's scripts/amneziawg_config.py prepares them: from a `.conf`,
|
|
//! a `vpn://` link (AmneziaVPN's export) or declarative settings, to the `.conf` a tunnel runs
|
|
//! (`prepare`); and that `.conf` for wireproxy-awg, a SOCKS listener in front of the tunnel
|
|
//! (`as_wireproxy`).
|
|
|
|
use std::collections::BTreeSet;
|
|
use std::io::Read;
|
|
|
|
use base64::Engine;
|
|
use serde_json::{Map, Value};
|
|
|
|
use crate::config::{AwgObfuscation, AwgProfile, AwgSettings};
|
|
use crate::wg::conf_sections;
|
|
|
|
const MAX_INPUT_BYTES: usize = 8 * 1024 * 1024;
|
|
const AWG3_SAFE_DEFAULT_MTU: &str = "1280";
|
|
const FORBIDDEN_WG_QUICK_KEYS: [&str; 5] = ["preup", "postup", "predown", "postdown", "saveconfig"];
|
|
const AWG_PROTOCOL_KEYS: [&str; 4] = ["awg", "amnezia-awg", "amnezia-awg2", "amnezia-awg3"];
|
|
const AWG3_INTERFACE_KEYS: [&str; 9] = [
|
|
"headerprotectionkey",
|
|
"contentpaddingaddition",
|
|
"rekeyaftertime",
|
|
"rekeytimeout",
|
|
"rejectaftertime",
|
|
"keepalivetimeout",
|
|
"maxhandshakeattempts",
|
|
"randomtrailers",
|
|
"disablecookies",
|
|
];
|
|
/// The obfuscation's keys, normalized (lowercase, letters and digits) and as written.
|
|
const VPN_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"),
|
|
];
|
|
|
|
type Res<T> = Result<T, String>;
|
|
|
|
fn normalize(key: &str) -> String {
|
|
key.to_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect()
|
|
}
|
|
|
|
/// A `vpn://` link's data: URL-safe base64 of Qt's qCompress (a 4-byte length, then zlib) of
|
|
/// JSON, or of the `.conf` itself (AmneziaVPN's compact form, shaped like the JSON here).
|
|
pub fn decode_vpn_link(link: &str) -> Res<Value> {
|
|
let encoded = link.trim().strip_prefix("vpn://").ok_or("expected a self-contained vpn:// link")?;
|
|
let body = encoded.trim_end_matches('=');
|
|
if body.is_empty() || !body.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') || encoded.len() - body.len() > 2 {
|
|
return Err("unsupported vpn:// link; API-backed text keys are not supported".into());
|
|
}
|
|
let raw = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
|
.decode(body)
|
|
.map_err(|_| "unsupported vpn:// link; expected embedded base64 data, not an API-backed text key")?;
|
|
if raw.len() > MAX_INPUT_BYTES {
|
|
return Err("vpn:// payload is too large".into());
|
|
}
|
|
let mut decoded = raw.clone();
|
|
if raw.len() >= 5 {
|
|
let expected = u32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]]) as usize;
|
|
let mut out = Vec::new();
|
|
let mut z = flate2::read::ZlibDecoder::new(&raw[4..]).take(MAX_INPUT_BYTES as u64 + 1);
|
|
if z.read_to_end(&mut out).is_ok() {
|
|
if out.len() > MAX_INPUT_BYTES {
|
|
return Err("decompressed vpn:// payload is too large".into());
|
|
}
|
|
if out.len() != expected {
|
|
return Err("vpn:// qCompress length header does not match payload".into());
|
|
}
|
|
decoded = out;
|
|
}
|
|
}
|
|
let text = String::from_utf8(decoded).map_err(|_| "unsupported vpn:// link; expected embedded qCompress/base64 JSON, not an API-backed key")?;
|
|
if text.trim_start().starts_with("[Interface]") && text.contains("[Peer]") {
|
|
return Ok(serde_json::json!({
|
|
"defaultContainer": "amnezia-awg",
|
|
"containers": [{ "container": "amnezia-awg", "config": text }],
|
|
}));
|
|
}
|
|
match serde_json::from_str::<Value>(&text) {
|
|
Ok(v) if v.is_object() => Ok(v),
|
|
Ok(_) => Err("invalid vpn:// configuration: expected a JSON object".into()),
|
|
Err(_) => Err("unsupported vpn:// link; expected embedded qCompress/base64 JSON, not an API-backed key".into()),
|
|
}
|
|
}
|
|
|
|
fn json_object(value: &Value, label: &str) -> Res<Map<String, Value>> {
|
|
let v = match value {
|
|
Value::String(s) => serde_json::from_str::<Value>(s).map_err(|e| format!("invalid {label} JSON: {e}"))?,
|
|
other => other.clone(),
|
|
};
|
|
match v {
|
|
Value::Object(m) => Ok(m),
|
|
_ => Err(format!("invalid {label}: expected an object")),
|
|
}
|
|
}
|
|
|
|
/// A container's payload: its last configuration and the `.conf` in it.
|
|
fn candidate_payload(value: &Value, key: &str) -> Res<(Map<String, Value>, String)> {
|
|
let payload = json_object(value, &format!("{key} protocol"))?;
|
|
let last = json_object(payload.get("last_config").unwrap_or(&Value::Object(payload.clone())), &format!("{key}.last_config"))?;
|
|
match last.get("config").and_then(Value::as_str) {
|
|
Some(c) if c.contains("[Interface]") && c.contains("[Peer]") => Ok((last.clone(), c.to_owned())),
|
|
_ => Err(format!("{key} candidate does not contain an AmneziaWG config")),
|
|
}
|
|
}
|
|
|
|
/// The AmneziaWG `.conf` of a `vpn://` export: its default container's (or `container`'s),
|
|
/// DNS placeholders filled, the obfuscation and MTU its last configuration records applied.
|
|
pub fn extract_vpn_config(data: &Value, container: Option<&str>) -> Res<String> {
|
|
let containers = data["containers"].as_array().ok_or("vpn:// configuration has no containers list")?;
|
|
struct Candidate {
|
|
id: String,
|
|
key: String,
|
|
last: Map<String, Value>,
|
|
config: String,
|
|
}
|
|
let mut candidates = Vec::new();
|
|
for item in containers {
|
|
let Some(obj) = item.as_object() else { continue };
|
|
let id = obj.get("container").and_then(Value::as_str).unwrap_or("").to_owned();
|
|
let mut protocols: Vec<(String, Value)> = obj.iter().filter(|(k, _)| AWG_PROTOCOL_KEYS.contains(&k.to_lowercase().as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
|
|
if AWG_PROTOCOL_KEYS.contains(&id.to_lowercase().as_str()) && protocols.is_empty() && (obj.contains_key("last_config") || obj.contains_key("config")) {
|
|
protocols = vec![(id.clone(), item.clone())];
|
|
}
|
|
for (key, value) in protocols {
|
|
if let Ok((last, config)) = candidate_payload(&value, &key) {
|
|
candidates.push(Candidate { id: if id.is_empty() { key.clone() } else { id.clone() }, key, last, config });
|
|
}
|
|
}
|
|
}
|
|
if candidates.is_empty() {
|
|
return Err("vpn:// configuration contains no AmneziaWG client config".into());
|
|
}
|
|
let named = |c: &Candidate, name: &str| [c.id.to_lowercase(), c.key.to_lowercase()].contains(&name.to_lowercase());
|
|
let chosen: Vec<&Candidate> = match container {
|
|
Some(want) => {
|
|
let found: Vec<&Candidate> = candidates.iter().filter(|c| named(c, want)).collect();
|
|
if found.len() != 1 {
|
|
return Err(format!("vpnContainer '{want}' matched {} AmneziaWG configs", found.len()));
|
|
}
|
|
found
|
|
}
|
|
None => {
|
|
let default: Vec<&Candidate> = data["defaultContainer"].as_str().map(|d| candidates.iter().filter(|c| named(c, d)).collect()).unwrap_or_default();
|
|
if default.len() == 1 {
|
|
default
|
|
} else if candidates.len() == 1 {
|
|
vec![&candidates[0]]
|
|
} else {
|
|
let ids: Vec<&str> = candidates.iter().map(|c| c.id.as_str()).collect();
|
|
return Err(format!("vpn:// configuration contains multiple AmneziaWG configs ({}); set vpnContainer", ids.join(", ")));
|
|
}
|
|
}
|
|
};
|
|
let c = chosen[0];
|
|
let mut config = c.config.clone();
|
|
if let Some(d) = data["dns1"].as_str().filter(|d| !d.is_empty()) {
|
|
config = config.replace("$PRIMARY_DNS", d);
|
|
}
|
|
if let Some(d) = data["dns2"].as_str().filter(|d| !d.is_empty()) {
|
|
config = config.replace("$SECONDARY_DNS", d);
|
|
}
|
|
if config.contains("$PRIMARY_DNS") || config.contains("$SECONDARY_DNS") {
|
|
return Err("vpn:// configuration contains unresolved DNS placeholders".into());
|
|
}
|
|
let last: Vec<(String, &Value)> = c.last.iter().map(|(k, v)| (normalize(k), v)).collect();
|
|
for (norm, key) in VPN_INTERFACE_FIELDS {
|
|
let Some((_, value)) = last.iter().find(|(k, _)| k == norm) else { continue };
|
|
let text = match value {
|
|
Value::Null => continue,
|
|
Value::String(s) if s.is_empty() => continue,
|
|
Value::Bool(b) if matches!(norm, "randomtrailers" | "disablecookies") => if *b { "on".into() } else { "off".into() },
|
|
Value::String(s) => s.clone(),
|
|
other => other.to_string(),
|
|
};
|
|
config = set_interface_value(&config, key, &text)?;
|
|
}
|
|
for (field, key) in [("mtu", "MTU"), ("port", "ListenPort")] {
|
|
let text = match c.last.get(field) {
|
|
None | Some(Value::Null) => continue,
|
|
Some(Value::String(s)) if s.is_empty() => continue,
|
|
Some(Value::String(s)) => s.clone(),
|
|
Some(other) => other.to_string(),
|
|
};
|
|
config = set_interface_value(&config, key, &text)?;
|
|
}
|
|
apply_awg3_mtu_default(&config)
|
|
}
|
|
|
|
/// Python's `str.splitlines()` and `"\n".join(...) + "\n"`, which upstream's rewrites use.
|
|
fn lines(config: &str) -> Vec<String> {
|
|
crate::links::py::splitlines(config).into_iter().map(str::to_owned).collect()
|
|
}
|
|
|
|
fn joined(lines: &[String]) -> String {
|
|
let mut s = lines.join("\n");
|
|
s.push('\n');
|
|
s
|
|
}
|
|
|
|
fn key_line(line: &str, key: &str) -> bool {
|
|
let t = line.trim_start();
|
|
t.len() >= key.len() && t[..key.len()].eq_ignore_ascii_case(key) && t[key.len()..].trim_start().starts_with('=')
|
|
}
|
|
|
|
/// `key = value` in `[Interface]`: the first such line replaced, or one added at its end.
|
|
fn set_interface_value(config: &str, key: &str, value: &str) -> Res<String> {
|
|
let mut ls = lines(config);
|
|
let start = ls.iter().position(|l| l.trim().eq_ignore_ascii_case("[interface]")).ok_or("configuration has no [Interface] section")?;
|
|
let end = (start + 1..ls.len()).find(|i| ls[*i].trim().starts_with('[')).unwrap_or(ls.len());
|
|
match (start + 1..end).find(|i| key_line(&ls[*i], key)) {
|
|
Some(i) => ls[i] = format!("{key} = {value}"),
|
|
None => ls.insert(end, format!("{key} = {value}")),
|
|
}
|
|
Ok(joined(&ls))
|
|
}
|
|
|
|
fn interface_keys(config: &str) -> BTreeSet<String> {
|
|
conf_sections(config).into_iter().filter(|(n, _)| n == "interface").flat_map(|(_, pairs)| pairs.into_iter().map(|(k, _)| normalize(&k))).collect()
|
|
}
|
|
|
|
/// AWG 3's per-packet padding with awg-quick's 1420 black-holes larger packets: without an
|
|
/// MTU of its own, such a profile gets the official clients' 1280.
|
|
fn apply_awg3_mtu_default(config: &str) -> Res<String> {
|
|
let keys = interface_keys(config);
|
|
if keys.contains("mtu") || !AWG3_INTERFACE_KEYS.iter().any(|k| keys.contains(*k)) {
|
|
return Ok(config.to_owned());
|
|
}
|
|
set_interface_value(config, "MTU", AWG3_SAFE_DEFAULT_MTU)
|
|
}
|
|
|
|
/// Section headers as awg-quick reads them ("[Peer] # home" opens a Peer section).
|
|
fn normalize_headers(config: &str) -> String {
|
|
config
|
|
.split('\n')
|
|
.map(|line| match line.split('#').next().unwrap_or("").trim().to_lowercase().as_str() {
|
|
"[interface]" => "[Interface]".to_owned(),
|
|
"[peer]" => "[Peer]".to_owned(),
|
|
_ => line.to_owned(),
|
|
})
|
|
.collect::<Vec<_>>()
|
|
.join("\n")
|
|
}
|
|
|
|
/// A secret given inline or in a file: exactly one, one line.
|
|
fn secret(inline: Option<&str>, file: Option<&str>, label: &str, read: &dyn Fn(&str) -> Res<String>) -> Res<String> {
|
|
let value = match (inline, file) {
|
|
(Some(v), None) => v.to_owned(),
|
|
(None, Some(f)) => read(f)?.trim().to_owned(),
|
|
_ => return Err(format!("set exactly one of {label} or {label}File")),
|
|
};
|
|
if value.is_empty() || value.contains(['\n', '\r']) {
|
|
return Err(format!("{label} must be one non-empty line"));
|
|
}
|
|
Ok(value)
|
|
}
|
|
|
|
fn range_text(v: &Value) -> String {
|
|
match v {
|
|
Value::String(s) => s.clone(),
|
|
other => other.to_string(),
|
|
}
|
|
}
|
|
|
|
/// The obfuscation given inline, with `obfuscationFile`'s secret fields merged in (a field
|
|
/// given both ways is refused, as upstream refuses it).
|
|
fn obfuscation_values(o: &AwgObfuscation, file: Option<&str>, read: &dyn Fn(&str) -> Res<String>) -> Res<Vec<(String, String)>> {
|
|
let mut values: Vec<(String, String)> = Vec::new();
|
|
let mut put = |name: &str, v: Option<String>| {
|
|
if let Some(v) = v {
|
|
values.push((name.to_owned(), v));
|
|
}
|
|
};
|
|
put("jc", o.jc.map(|v| v.to_string()));
|
|
put("jmin", o.jmin.map(|v| v.to_string()));
|
|
put("jmax", o.jmax.map(|v| v.to_string()));
|
|
put("s1", o.s1.map(|v| v.to_string()));
|
|
put("s2", o.s2.map(|v| v.to_string()));
|
|
put("s3", o.s3.map(|v| v.to_string()));
|
|
put("s4", o.s4.map(|v| v.to_string()));
|
|
put("h1", o.h1.as_ref().map(range_text));
|
|
put("h2", o.h2.as_ref().map(range_text));
|
|
put("h3", o.h3.as_ref().map(range_text));
|
|
put("h4", o.h4.as_ref().map(range_text));
|
|
put("i1", o.i1.clone());
|
|
put("i2", o.i2.clone());
|
|
put("i3", o.i3.clone());
|
|
put("i4", o.i4.clone());
|
|
put("i5", o.i5.clone());
|
|
put("contentpaddingaddition", o.content_padding_addition.as_ref().map(range_text));
|
|
put("rekeyaftertime", o.rekey_after_time.as_ref().map(range_text));
|
|
put("rekeytimeout", o.rekey_timeout.as_ref().map(range_text));
|
|
put("rejectaftertime", o.reject_after_time.as_ref().map(range_text));
|
|
put("keepalivetimeout", o.keepalive_timeout.as_ref().map(range_text));
|
|
put("maxhandshakeattempts", o.max_handshake_attempts.as_ref().map(range_text));
|
|
put("randomtrailers", o.random_trailers.map(|b| if b { "on".into() } else { "off".into() }));
|
|
put("disablecookies", o.disable_cookies.map(|b| if b { "on".into() } else { "off".into() }));
|
|
if let Some(f) = file {
|
|
let text = read(f)?;
|
|
let secret: Map<String, Value> = match serde_json::from_str::<Value>(&text) {
|
|
Ok(Value::Object(m)) => m,
|
|
Ok(_) => return Err("obfuscationFile must contain a JSON object".into()),
|
|
Err(_) => return Err("cannot read or decode obfuscationFile".into()),
|
|
};
|
|
for (key, value) in secret {
|
|
let norm = normalize(&key);
|
|
if !VPN_INTERFACE_FIELDS.iter().any(|(n, _)| *n == norm) {
|
|
return Err("obfuscationFile contains an unsupported field".into());
|
|
}
|
|
if value.is_null() {
|
|
continue;
|
|
}
|
|
if values.iter().any(|(n, _)| *n == norm) || (norm == "headerprotectionkey" && (o.header_protection_key.is_some() || o.header_protection_key_file.is_some())) {
|
|
return Err(format!("obfuscationFile field '{key}' has multiple sources"));
|
|
}
|
|
let unsigned = value.as_u64().is_some();
|
|
let text = match norm.as_str() {
|
|
"jc" | "jmin" | "jmax" | "s1" | "s2" | "s3" | "s4" if unsigned => value.to_string(),
|
|
"randomtrailers" | "disablecookies" => match value.as_bool() {
|
|
Some(b) => (if b { "on" } else { "off" }).to_owned(),
|
|
None => return Err(format!("obfuscationFile field '{key}' has an invalid value")),
|
|
},
|
|
"i1" | "i2" | "i3" | "i4" | "i5" | "headerprotectionkey" => match value.as_str() {
|
|
Some(s) if !s.trim().is_empty() && !s.contains(['\n', '\r', '\0']) => s.to_owned(),
|
|
_ => return Err(format!("obfuscationFile field '{key}' has an invalid value")),
|
|
},
|
|
"h1" | "h2" | "h3" | "h4" | "contentpaddingaddition" | "rekeyaftertime" | "rekeytimeout" | "rejectaftertime" | "keepalivetimeout" | "maxhandshakeattempts" => {
|
|
match &value {
|
|
Value::Number(_) if unsigned => value.to_string(),
|
|
Value::String(s) if s.split_once('-').map_or(s.chars().all(|c| c.is_ascii_digit()) && !s.is_empty(), |(a, b)| !a.is_empty() && !b.is_empty() && (a.to_owned() + b).chars().all(|c| c.is_ascii_digit())) || s == "(off)" => s.clone(),
|
|
_ => return Err(format!("obfuscationFile field '{key}' has an invalid value")),
|
|
}
|
|
}
|
|
_ => return Err(format!("obfuscationFile field '{key}' has an invalid value")),
|
|
};
|
|
values.push((norm, text));
|
|
}
|
|
}
|
|
Ok(values)
|
|
}
|
|
|
|
/// A `.conf` from declarative settings.
|
|
pub fn render_settings(s: &AwgSettings, read: &dyn Fn(&str) -> Res<String>) -> Res<String> {
|
|
if s.addresses.is_empty() {
|
|
return Err("declarative settings require at least one address".into());
|
|
}
|
|
if s.peers.is_empty() {
|
|
return Err("declarative settings require at least one peer".into());
|
|
}
|
|
let mut out = vec!["[Interface]".to_owned()];
|
|
out.push(format!("PrivateKey = {}", secret(s.private_key.as_deref(), s.private_key_file.as_deref(), "privateKey", read)?));
|
|
for a in &s.addresses {
|
|
out.push(format!("Address = {a}"));
|
|
}
|
|
if !s.dns.is_empty() {
|
|
out.push(format!("DNS = {}", s.dns.join(",")));
|
|
}
|
|
if let Some(p) = s.listen_port {
|
|
out.push(format!("ListenPort = {p}"));
|
|
}
|
|
if let Some(m) = s.mtu {
|
|
out.push(format!("MTU = {m}"));
|
|
}
|
|
let values = obfuscation_values(&s.obfuscation, s.obfuscation_file.as_deref(), read)?;
|
|
for (norm, key) in VPN_INTERFACE_FIELDS {
|
|
if norm == "headerprotectionkey" {
|
|
continue;
|
|
}
|
|
if let Some((_, v)) = values.iter().find(|(n, _)| n == norm) {
|
|
out.push(format!("{key} = {v}"));
|
|
}
|
|
}
|
|
let from_file = values.iter().find(|(n, _)| n == "headerprotectionkey").map(|(_, v)| v.clone());
|
|
let o = &s.obfuscation;
|
|
if o.header_protection_key.is_some() || o.header_protection_key_file.is_some() {
|
|
out.push(format!("HeaderProtectionKey = {}", secret(o.header_protection_key.as_deref(), o.header_protection_key_file.as_deref(), "headerProtectionKey", read)?));
|
|
} else if let Some(v) = from_file {
|
|
out.push(format!("HeaderProtectionKey = {v}"));
|
|
}
|
|
for peer in &s.peers {
|
|
if peer.public_key.is_empty() || peer.allowed_ips.is_empty() {
|
|
return Err("each peer requires publicKey and allowedIPs".into());
|
|
}
|
|
out.extend([String::new(), "[Peer]".into(), format!("PublicKey = {}", peer.public_key)]);
|
|
if peer.preshared_key.is_some() || peer.preshared_key_file.is_some() {
|
|
out.push(format!("PresharedKey = {}", secret(peer.preshared_key.as_deref(), peer.preshared_key_file.as_deref(), "presharedKey", read)?));
|
|
}
|
|
out.push(format!("AllowedIPs = {}", peer.allowed_ips.join(",")));
|
|
if let Some(e) = &peer.endpoint {
|
|
out.push(format!("Endpoint = {e}"));
|
|
}
|
|
if let Some(k) = &peer.persistent_keepalive {
|
|
out.push(format!("PersistentKeepalive = {}", range_text(k)));
|
|
}
|
|
if let Some(a) = peer.advanced_security {
|
|
out.push(format!("AdvancedSecurity = {}", if a { "on" } else { "off" }));
|
|
}
|
|
}
|
|
Ok(joined(&out))
|
|
}
|
|
|
|
/// The first peer's `Endpoint` replaced by `endpoint` (host:port, IPv6 in brackets).
|
|
pub fn override_endpoint(config: &str, endpoint: &str) -> Res<String> {
|
|
let mut done = false;
|
|
let out: Vec<String> = config
|
|
.split('\n')
|
|
.map(|line| {
|
|
if !done && key_line(line, "Endpoint") {
|
|
let value = line.split_once('=').map(|(_, v)| v.trim()).unwrap_or("");
|
|
if value.rsplit_once(':').is_some_and(|(h, p)| !h.is_empty() && !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()) && !value.contains(char::is_whitespace)) {
|
|
done = true;
|
|
let prefix = &line[..line.find('=').unwrap() + 1];
|
|
return format!("{prefix} {endpoint}");
|
|
}
|
|
}
|
|
line.to_owned()
|
|
})
|
|
.collect();
|
|
if !done {
|
|
return Err("configuration has no Endpoint to override".into());
|
|
}
|
|
Ok(out.join("\n"))
|
|
}
|
|
|
|
/// Upstream's checks: no control characters a reader could take for a line end, sections
|
|
/// [Interface] (exactly one) and [Peer] only, alone on their lines, and no wg-quick hooks
|
|
/// unless allowed.
|
|
pub fn validate(config: &str, allow_hooks: bool) -> Res<()> {
|
|
let bytes: Vec<char> = config.chars().collect();
|
|
for (i, c) in bytes.iter().enumerate() {
|
|
let lone_cr = *c == '\r' && bytes.get(i + 1) != Some(&'\n');
|
|
let bad = matches!(*c as u32, 0x00..=0x08 | 0x0b | 0x0c | 0x0e..=0x1f | 0x7f | 0x85 | 0x2028 | 0x2029);
|
|
if bad || lone_cr {
|
|
return Err("configuration contains control characters".into());
|
|
}
|
|
}
|
|
let lowered = config.to_lowercase();
|
|
if !lowered.contains("[interface]") || !lowered.contains("[peer]") {
|
|
return Err("configuration requires [Interface] and [Peer] sections".into());
|
|
}
|
|
let mut interfaces = 0;
|
|
for line in config.split('\n') {
|
|
let stripped = line.trim();
|
|
if !stripped.split('#').next().unwrap_or("").trim().starts_with('[') {
|
|
continue;
|
|
}
|
|
let lower = stripped.to_lowercase();
|
|
if lower != "[interface]" && lower != "[peer]" {
|
|
return Err(format!("unexpected section header {:?}: only [Interface] and [Peer], alone on their line", stripped.chars().take(40).collect::<String>()));
|
|
}
|
|
interfaces += usize::from(lower == "[interface]");
|
|
}
|
|
if interfaces != 1 {
|
|
return Err("configuration needs exactly one [Interface] section".into());
|
|
}
|
|
if !allow_hooks {
|
|
for line in config.split('\n') {
|
|
let key = line.split('#').next().unwrap_or("").split('=').next().unwrap_or("").trim().to_lowercase();
|
|
if !key.is_ascii() {
|
|
return Err("configuration has a key with non-ASCII characters".into());
|
|
}
|
|
if FORBIDDEN_WG_QUICK_KEYS.contains(&key.as_str()) {
|
|
return Err(format!("configuration contains privileged wg-quick directive '{key}'; set allowConfigHooks = true only for trusted input"));
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// A profile's `.conf`, from whichever source it has, as upstream's `prepare` makes it.
|
|
pub fn prepare(p: &AwgProfile, read: &dyn Fn(&str) -> Res<String>) -> Res<String> {
|
|
let config = match (&p.config, &p.config_file, &p.vpn, &p.vpn_file, &p.settings) {
|
|
(Some(text), None, None, None, None) => text.clone(),
|
|
(None, Some(f), None, None, None) => read(f)?,
|
|
(None, None, Some(link), None, None) => extract_vpn_config(&decode_vpn_link(link)?, p.vpn_container.as_deref())?,
|
|
(None, None, None, Some(f), None) => extract_vpn_config(&decode_vpn_link(&read(f)?)?, p.vpn_container.as_deref())?,
|
|
(None, None, None, None, Some(s)) => render_settings(s, read)?,
|
|
_ => return Err("a profile needs exactly one of config, configFile, vpn, vpnFile and settings".into()),
|
|
};
|
|
if config.len() > MAX_INPUT_BYTES {
|
|
return Err("the configuration is too large".into());
|
|
}
|
|
let mut config = apply_awg3_mtu_default(&normalize_headers(&config))?;
|
|
if let Some(e) = &p.endpoint {
|
|
config = override_endpoint(&config, e)?;
|
|
}
|
|
validate(&config, p.allow_config_hooks)?;
|
|
Ok(config)
|
|
}
|
|
|
|
/// A wireproxy-awg configuration: the profile served as a SOCKS5 listener on `socks_address`,
|
|
/// with `login`. Only [Interface] and [Peer] are kept, wg-quick's keys dropped.
|
|
pub fn as_wireproxy(config: &str, socks_address: &str, login: Option<(&str, &str)>) -> Res<String> {
|
|
const LISTS: [&str; 3] = ["address", "dns", "allowedips"];
|
|
const DROPPED: [&str; 7] = ["preup", "postup", "predown", "postdown", "saveconfig", "table", "fwmark"];
|
|
let mut out: Vec<String> = Vec::new();
|
|
for (name, pairs) in conf_sections(config) {
|
|
if name != "interface" && name != "peer" {
|
|
continue;
|
|
}
|
|
if !out.is_empty() {
|
|
out.push(String::new());
|
|
}
|
|
out.push(if name == "interface" { "[Interface]".into() } else { "[Peer]".into() });
|
|
let mut lists: Vec<(String, Vec<String>)> = Vec::new();
|
|
let mut section: Vec<String> = Vec::new();
|
|
for (key, value) in pairs {
|
|
if DROPPED.contains(&key.as_str()) {
|
|
continue;
|
|
}
|
|
if LISTS.contains(&key.as_str()) {
|
|
let items = value.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);
|
|
match lists.iter_mut().find(|(k, _)| *k == key) {
|
|
Some((_, l)) => l.extend(items),
|
|
None => {
|
|
lists.push((key.clone(), items.collect()));
|
|
section.push(key);
|
|
}
|
|
}
|
|
} else {
|
|
section.push(format!("{key} = {value}"));
|
|
}
|
|
}
|
|
for line in section {
|
|
match lists.iter().find(|(k, _)| *k == line) {
|
|
Some((k, l)) => out.push(format!("{k} = {}", l.join(","))),
|
|
None => out.push(line),
|
|
}
|
|
}
|
|
}
|
|
out.extend([String::new(), "[Socks5]".into(), format!("BindAddress = {socks_address}")]);
|
|
if let Some((user, password)) = login {
|
|
let ok = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
|
|
if !ok(user) || !ok(password) {
|
|
return Err("the SOCKS login must be letters, digits, dot, dash and underscore".into());
|
|
}
|
|
out.extend([format!("Username = {user}"), format!("Password = {password}")]);
|
|
}
|
|
Ok(joined(&out))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
// Made by upstream's encode_vpn_link (scripts/amneziawg_config.py), and a JSON export with
|
|
// DNS placeholders and a last configuration, as AmneziaVPN shares one.
|
|
const LINK: &str = "vpn://AAAEX3jalVNdb-IwEPwryM9cwPmQqkh9qNpTA72iSJwQB0HIJOZqNTiRbSgp4r93dxO43sPpVCVKZmbXa3vsPbG80k4oLY1l8fL0h7KYiZ2W70p8E2-_WZ_hNz6xcQ6REPh4pzRAPiQsjoAjxFMOiIDfgQQVjgAVH0EAIEAQdtVKYd0aJt8qmIWdMtbijMUZW460k2YrcrnKMp0adRBOPsmmd9sTjzO7ebxx__s_P9zdwti7ojDSWhjIh96Nxz1_EPigP0ymqHn0AB_nQEMEsEnKJiyOgCPEUw6IgN-BBBUcm6CCRZMAQIAg7KrBu0ylNLSN_aZUebuL3J81xW7W_JhPylwvylzx98V87C_mI_d37BftoiyrN1mMUtzI0KNnMOz34niAK_mui7pS2uEyhgEEOQ-8KI74jY_hFI5aWSe1e5KyFqU6SMyMcH2sn7GXyrqJ2Emy_lBrTx7Fri4lBevKOAhQLaB5qaDOWtWUfPGUMrtQDae1fpUNJXzptLCIleYgzbreb641vuQVLdm-XgeTIFr7YNUWxGXGrhZSmFxkKxx5dQoKyHpNXlEdcAtTxzmxsCVwVTobOi6OxKOWTzmxjvifSNJGeEvaSGtiEhAJWhJeZjtDw-BJYMvhSQB1RmiLGjheuQoi-6IGXdmfL8oUqTCuue_ay5m9PJ9XfVbIrdiX7v6fPV9ImxtVO1Vhqz83vVk6AflyRUD7dEEwX1vq9baR2PkDyhJUgw";
|
|
const LINK2: &str = "vpn://AAACXnichVLvb4IwEP1XSLOPDinIpiR-MGoUnY5oYvyBMRXq0gSKgapTwv--O2BZ9mVLafreu-v1Lo-cBIlUTEieZsTRdvkPB0pYLPlDsGd2-yANoHA4Wk4ilqkDJJ4EcpL7pCI-MJ_sXKl4emIB3_u-9FJxZYpP-V3ramy0yo6jtvrvnA16XbjbC8OUZxlcpIbe1qluNi0T9MF8CdqTt3BnvcXmALShPS2H_ff5oOaQNAkgp4UgFrIsUWL2CdhGvKSASmDWYIwKRYAKvjS2AFgIWnU1-HYe52k52-UYiaAaLTBX9zBe3d_W8yiQ2ygQ9LFdT8zt2lW_Y5tytChKbjx0PZzO0MvVNBqa4zSxk6EMz4mQCtswLAhSaum2Y9O2iWEP7BKZ4lJNOT-zSFw5ZtrYHxjlk1hdKjOo9fpSSZOgUmyfFGjmOUkVulfWJEWxBy3kJ3aJVP-PfyCUGUW5o5erlkyUaKsDfZrfmxRfDVi3BA";
|
|
|
|
const EXTRACTED: &str = "[Interface]\nPrivateKey = aGVsbG8taGVsbG8taGVsbG8taGVsbG8taGVsbG8tMDA=\nAddress = 10.8.1.2/32\nDNS = 1.1.1.1\nJc = 4\nJmin = 10\nJmax = 50\nS1 = 0\nS2 = 0\nH1 = 1\nH2 = 2\nH3 = 3\nH4 = 4\n\nListenPort = 51820\n[Peer]\nPublicKey = c2VydmVyLXNlcnZlci1zZXJ2ZXItc2VydmVyLXNlcnY=\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = 203.0.113.5:51820\nPersistentKeepalive = 25\n";
|
|
|
|
#[test]
|
|
fn vpn_links_extract_as_upstreams_do() {
|
|
assert_eq!(extract_vpn_config(&decode_vpn_link(LINK).unwrap(), None).unwrap(), EXTRACTED);
|
|
let two = extract_vpn_config(&decode_vpn_link(LINK2).unwrap(), None).unwrap();
|
|
assert!(two.contains("DNS = 9.9.9.9, 149.112.112.112\n"), "{two}");
|
|
assert!(two.contains("Jc = 5\n") && two.contains("MTU = 1376\n"), "{two}");
|
|
assert!(decode_vpn_link("vpn://short.key").is_err());
|
|
assert!(decode_vpn_link("https://x").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn wireproxy_as_upstreams() {
|
|
let w = as_wireproxy(EXTRACTED, "127.0.0.1:18700", Some(("hop", "pw-123"))).unwrap();
|
|
assert_eq!(
|
|
w,
|
|
"[Interface]\nprivatekey = aGVsbG8taGVsbG8taGVsbG8taGVsbG8taGVsbG8tMDA=\naddress = 10.8.1.2/32\ndns = 1.1.1.1\njc = 4\njmin = 10\njmax = 50\n\
|
|
s1 = 0\ns2 = 0\nh1 = 1\nh2 = 2\nh3 = 3\nh4 = 4\nlistenport = 51820\n\n[Peer]\npublickey = c2VydmVyLXNlcnZlci1zZXJ2ZXItc2VydmVyLXNlcnY=\n\
|
|
allowedips = 0.0.0.0/0,::/0\nendpoint = 203.0.113.5:51820\npersistentkeepalive = 25\n\n[Socks5]\nBindAddress = 127.0.0.1:18700\nUsername = hop\nPassword = pw-123\n"
|
|
);
|
|
assert!(as_wireproxy(EXTRACTED, "127.0.0.1:1", Some(("hop", "a b"))).is_err());
|
|
}
|
|
|
|
fn read(_: &str) -> Res<String> {
|
|
Err("no files here".into())
|
|
}
|
|
|
|
#[test]
|
|
fn prepare_checks_and_overrides() {
|
|
let mut p = AwgProfile { config: Some(EXTRACTED.into()), endpoint: Some("198.51.100.9:443".into()), ..Default::default() };
|
|
let c = prepare(&p, &read).unwrap();
|
|
assert!(c.contains("Endpoint = 198.51.100.9:443"), "{c}");
|
|
p.config = Some(format!("{EXTRACTED}PostUp = calc.exe\n"));
|
|
p.endpoint = None;
|
|
assert!(prepare(&p, &read).unwrap_err().contains("wg-quick directive"));
|
|
p.config = Some(EXTRACTED.replace("[Peer]", "[Peer]\r[Interface]"));
|
|
assert!(prepare(&p, &read).unwrap_err().contains("control"));
|
|
p.config = None;
|
|
p.vpn = Some(LINK.into());
|
|
assert_eq!(prepare(&p, &read).unwrap(), EXTRACTED);
|
|
// AWG 3 keys without an MTU: 1280.
|
|
p.vpn = None;
|
|
p.config = Some(EXTRACTED.replace("H4 = 4", "H4 = 4\nRandomTrailers = on"));
|
|
assert!(prepare(&p, &read).unwrap().contains("MTU = 1280"));
|
|
}
|
|
|
|
#[test]
|
|
fn settings_render() {
|
|
let s: AwgSettings = serde_json::from_value(serde_json::json!({
|
|
"addresses": ["10.9.0.2/32"],
|
|
"privateKey": "PRIV",
|
|
"obfuscation": { "jc": 3, "h1": "100-200", "randomTrailers": true },
|
|
"peers": [{ "publicKey": "PUB", "allowedIPs": ["0.0.0.0/0"], "endpoint": "198.51.100.1:51820", "persistentKeepalive": 25 }],
|
|
}))
|
|
.unwrap();
|
|
let c = render_settings(&s, &read).unwrap();
|
|
assert_eq!(
|
|
c,
|
|
"[Interface]\nPrivateKey = PRIV\nAddress = 10.9.0.2/32\nJc = 3\nH1 = 100-200\nRandomTrailers = on\n\n[Peer]\nPublicKey = PUB\nAllowedIPs = 0.0.0.0/0\nEndpoint = 198.51.100.1:51820\nPersistentKeepalive = 25\n"
|
|
);
|
|
}
|
|
}
|