windows: AmneziaWG outbounds, and WARP through wireproxy

- 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>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-27 12:32:43 +03:00
1 parent 62adadc207
commit 2c4cdee7d3
15 files changed
+980 -10

No files matched your search

+1
View File
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
base64.workspace = true
flate2 = "1"
serde.workspace = true
serde_json.workspace = true
regex.workspace = true
+635
View File
@@ -0,0 +1,635 @@
//! 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"
);
}
}
@@ -113,8 +113,7 @@ fn not_ported(cfg: &Config, v: &mut Issues) {
v.warn("killSwitch.enable", "the kill switch is not on Windows yet: nothing blocks traffic that bypasses the tunnel");
}
for (on, path, what) in [
(cfg.amnezia_wg.enable, "amneziaWg.enable", "AmneziaWG"),
(cfg.warp.enable && cfg.warp.as_outbound.is_some_and(|k| k != crate::config::WarpOutboundKind::SingBox), "warp.asOutbound", "WARP through AmneziaWG (userspace, interface)"),
(cfg.amnezia_wg.enable && cfg.amnezia_wg.profiles.values().any(|p| p.as_outbound.is_none()), "amneziaWg.profiles", "AmneziaWG as a system-wide VPN (its driver; as outbounds it is here)"),
(cfg.warp.enable && cfg.warp.as_amnezia_wg, "warp.asAmneziaWg", "WARP as an AmneziaWG profile"),
(cfg.tor.enable && cfg.tor.onion_service.enable, "tor.onionService.enable", "Tor's onion service (it serves the inbounds)"),
(cfg.whitelist_bypass.enable, "whitelistBypass.enable", "whitelist-bypass"),
@@ -817,10 +816,11 @@ mod tests {
let mut cfg = Config::default();
cfg.kill_switch.enable = true;
cfg.amnezia_wg.enable = true;
cfg.amnezia_wg.profiles.insert("vpn".into(), Default::default());
cfg.zapret.enable = true;
cfg.proxy.tun.enable = true;
let paths: Vec<String> = validate(&cfg).into_iter().filter(|i| i.severity == Severity::Warning && i.message.contains("Windows yet")).map(|i| i.path).collect();
for want in ["killSwitch.enable", "amneziaWg.enable", "proxy.tun.enable"] {
for want in ["killSwitch.enable", "amneziaWg.profiles", "proxy.tun.enable"] {
assert!(paths.iter().any(|p| p == want), "{want} not in {paths:?}");
}
}
+1
View File
@@ -4,6 +4,7 @@
//! subscription parsing, and the sing-box and XRay configs the service runs. Nothing here
//! touches the network, the file system or processes; the service does that.
pub mod awg;
pub mod components;
pub mod config;
pub mod derived;
+143
View File
@@ -295,3 +295,146 @@ fn an_ssh_tunnel() {
assert_eq!(logins, 2, "{}", diagnose());
let _ = std::fs::remove_dir_all(&dir);
}
/// GET http://<host>:<port>/ through a SOCKS5 proxy that wants a login (RFC 1929).
fn socks_get_login(proxy: u16, login: (&str, &str), host: &str, port: u16) -> std::io::Result<String> {
let mut s = TcpStream::connect(("127.0.0.1", proxy))?;
s.set_read_timeout(Some(Duration::from_secs(10)))?;
s.write_all(&[5, 1, 2])?;
let mut buf = [0u8; 2];
s.read_exact(&mut buf)?;
let (u, p) = login;
let mut auth = vec![1, u.len() as u8];
auth.extend_from_slice(u.as_bytes());
auth.push(p.len() as u8);
auth.extend_from_slice(p.as_bytes());
s.write_all(&auth)?;
s.read_exact(&mut buf)?;
if buf[1] != 0 {
return Err(std::io::Error::other("SOCKS login refused"));
}
let ip: std::net::Ipv4Addr = host.parse().map_err(std::io::Error::other)?;
let mut req = vec![5, 1, 0, 1];
req.extend_from_slice(&ip.octets());
req.extend_from_slice(&port.to_be_bytes());
s.write_all(&req)?;
let mut reply = [0u8; 10];
s.read_exact(&mut reply)?;
if reply[1] != 0 {
return Err(std::io::Error::other(format!("SOCKS reply {}", reply[1])));
}
s.write_all(format!("GET / HTTP/1.0\r\nHost: {host}\r\n\r\n").as_bytes())?;
let mut body = String::new();
s.read_to_string(&mut body)?;
Ok(body)
}
fn wg_keypair() -> (String, String) {
let out = Command::new("sing-box").args(["generate", "wg-keypair"]).output().unwrap();
let text = String::from_utf8_lossy(&out.stdout).into_owned();
let field = |name: &str| text.lines().find_map(|l| l.strip_prefix(name)).unwrap_or_else(|| panic!("{text}")).trim().to_owned();
(field("PrivateKey:"), field("PublicKey:"))
}
/// AmneziaWG of the "userspace" kind, offline: sing-box as the WireGuard server on loopback
/// (answering for web.test, and taking 10.66.0.1 to this machine), the service running
/// wireproxy-awg as its client, a page through wireproxy's listener and through the proxy.
#[test]
fn an_amneziawg_tunnel() {
if Command::new("sing-box").arg("version").output().is_err() || on_path("wireproxy").is_none() {
eprintln!("sing-box or wireproxy (tools/build-wireproxy-awg.sh OUT linux) is not on PATH: skipping");
return;
}
let dir = std::env::temp_dir().join(format!("ps-e2e-awg-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let (wg_port, web_port, proxy_port, clash_port, test_port) = (free_port(), free_port(), free_port(), free_port(), free_port());
let web = TcpListener::bind(("127.0.0.1", web_port)).unwrap();
std::thread::spawn(move || {
for mut s in web.incoming().flatten() {
let mut buf = [0u8; 1024];
let _ = s.read(&mut buf);
let _ = s.write_all(b"HTTP/1.0 200 OK\r\nContent-Length: 16\r\n\r\nhello-through-wg");
}
});
let (srv_priv, srv_pub) = wg_keypair();
let (cli_priv, cli_pub) = wg_keypair();
let server = serde_json::json!({
"log": { "level": "warn" },
// web.test is the server's own tunnel address, which it takes to this machine's
// loopback (a tunnel's packet to 127.0.0.1 itself would be dropped as martian).
"dns": { "servers": [{ "type": "hosts", "tag": "hosts", "predefined": { "web.test": ["10.66.0.1"] } }] },
"endpoints": [{ "type": "wireguard", "tag": "wg-in", "address": ["10.66.0.1/32"], "private_key": srv_priv,
"listen_port": wg_port, "peers": [{ "public_key": cli_pub, "allowed_ips": ["10.66.0.2/32"] }] }],
"outbounds": [{ "type": "direct", "tag": "direct" }],
"route": {
"default_domain_resolver": "hosts",
"rules": [
{ "port": 53, "action": "hijack-dns" },
{ "ip_cidr": ["10.66.0.1/32"], "action": "route", "outbound": "direct", "override_address": "127.0.0.1" },
],
"final": "direct",
},
});
std::fs::write(dir.join("server.json"), server.to_string()).unwrap();
let _server = Kill(Command::new("sing-box").args(["run", "-c"]).arg(dir.join("server.json")).stderr(std::fs::File::create(dir.join("server.log")).unwrap()).spawn().unwrap());
let profile = format!(
"[Interface]\nPrivateKey = {cli_priv}\nAddress = 10.66.0.2/32\nDNS = 10.66.0.1\n\n[Peer]\nPublicKey = {srv_pub}\nAllowedIPs = 0.0.0.0/0\nEndpoint = 127.0.0.1:{wg_port}\nPersistentKeepalive = 25\n"
);
let state = dir.join("state");
std::fs::create_dir_all(&state).unwrap();
let config = serde_json::json!({
"proxy": {
"enable": true,
"listener": { "port": proxy_port },
"singBox": { "clashApiPort": clash_port, "testPort": test_port },
"routing": { "directRu": false },
},
"amneziaWg": { "enable": true, "profiles": { "vpn": { "config": profile, "asOutbound": "userspace" } } },
});
std::fs::write(state.join("config.json"), config.to_string()).unwrap();
let socket = dir.join("api.sock");
let _service = Kill(
Command::new(service_binary())
.args(["--console", "--state-dir"])
.arg(&state)
.arg("--socket")
.arg(&socket)
.stderr(std::fs::File::create(dir.join("service.log")).unwrap())
.spawn()
.unwrap(),
);
wait_for("the service's API", Duration::from_secs(10), || ctl(&socket, &["status"]).0);
let diagnose = || {
format!(
"status:\n{}\nlogs:\n{}\nserver:\n{}",
ctl(&socket, &["status"]).1,
ctl(&socket, &["logs", "-n", "40"]).1,
std::fs::read_to_string(dir.join("server.log")).unwrap_or_default()
)
};
// wireproxy's own listener, with the login the service gave it.
let conf = state.join("run").join("awg").join("vpn.conf");
wait_for("wireproxy's configuration", Duration::from_secs(10), || conf.is_file());
let text = std::fs::read_to_string(&conf).unwrap();
let field = |name: &str| text.lines().find_map(|l| l.strip_prefix(name)).unwrap().trim().to_owned();
let (user, password) = (field("Username ="), field("Password ="));
let port: u16 = field("BindAddress =").rsplit(':').next().unwrap().parse().unwrap();
let body = (0..40).find_map(|_| {
std::thread::sleep(Duration::from_millis(250));
socks_get_login(port, (&user, &password), "10.66.0.1", web_port).ok().filter(|b| b.ends_with("hello-through-wg"))
});
assert!(body.is_some(), "no page through wireproxy\n{}", diagnose());
// The proxy's outbound "vpn", a name resolved inside the tunnel.
assert!(ctl(&socket, &["proxy", "pin", "vpn"]).0, "{}", diagnose());
let body = (0..40).find_map(|_| {
std::thread::sleep(Duration::from_millis(250));
socks_get(proxy_port, "web.test", web_port).ok().filter(|b| b.ends_with("hello-through-wg"))
});
assert!(body.is_some(), "no page through the proxy's AmneziaWG outbound\n{}", diagnose());
let _ = std::fs::remove_dir_all(&dir);
}
+94
View File
@@ -0,0 +1,94 @@
//! AmneziaWG outbounds and WARP devices of the "userspace" kind: wireproxy-awg, a SOCKS
//! listener on loopback in front of each tunnel, with the hop login, as upstream's
//! wg-tunnel.nix runs it. The "singBox" kind needs only the profile's `.conf`, which the
//! renderer makes a WireGuard endpoint of (AmneziaWG's obfuscation dropped, with a warning).
//! AmneziaWG as a system-wide VPN needs its driver, which is not here yet.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use ps_core::config::{AwgOutboundKind, Config, WarpOutboundKind};
use ps_core::derived::{self, ExtraKind};
use crate::paths::{Paths, write_atomic};
use crate::units::UnitSpec;
pub const UNIT_PREFIX: &str = "proxy-suite-awg-";
fn read(f: &str) -> Result<String, String> {
std::fs::read_to_string(f).map_err(|e| format!("{f}: {e}"))
}
/// Each "singBox" AmneziaWG outbound's `.conf`, by profile, and why any could not be read.
pub fn sing_box_profiles(cfg: &Config) -> (BTreeMap<String, String>, Vec<String>) {
let mut out = BTreeMap::new();
let mut errors = Vec::new();
for (name, kind, _) in derived::awg_outbounds(cfg) {
if kind != AwgOutboundKind::SingBox {
continue;
}
match ps_core::awg::prepare(&cfg.amnezia_wg.profiles[&name], &read) {
Ok(conf) => {
out.insert(name, conf);
}
Err(e) => errors.push(format!("AmneziaWG profile '{name}': {e}")),
}
}
(out, errors)
}
/// The wireproxy units: one per "userspace" AmneziaWG outbound and WARP device, with what
/// could not be made of the rest. `warp` holds the WARP devices' profiles.
pub fn units(cfg: &Config, paths: &Paths, program: &Path, login: (&str, &str), warp: &BTreeMap<String, String>) -> (Vec<UnitSpec>, Vec<String>) {
let mut tunnels: Vec<(String, Result<String, String>, u16)> = Vec::new();
for extra in derived::extra_outbounds(cfg) {
match extra.kind {
ExtraKind::Awg { profile, kind: AwgOutboundKind::Userspace, port } => {
let conf = ps_core::awg::prepare(&cfg.amnezia_wg.profiles[&profile], &read).map_err(|e| format!("AmneziaWG profile '{profile}': {e}"));
tunnels.push((profile, conf, port));
}
ExtraKind::Warp { device } if device.kind == WarpOutboundKind::Userspace => {
// A device registered (or given) only: until then the outbound waits.
if let Some(profile) = warp.get(&device.tag) {
let conf = ps_core::awg::validate(profile, false).map(|()| profile.clone()).map_err(|e| format!("WARP device '{}': {e}", device.tag));
tunnels.push((device.tag.clone(), conf, device.port));
}
}
_ => {}
}
}
let mut units = Vec::new();
let mut errors = Vec::new();
for (name, conf, port) in tunnels {
let made = conf.and_then(|c| ps_core::awg::as_wireproxy(&c, &format!("127.0.0.1:{port}"), Some(login))).and_then(|text| {
write(paths, &name, &text).map_err(|e| format!("'{name}': {e:#}"))
});
match made {
Ok((file, text)) => units.push(UnitSpec {
name: format!("{UNIT_PREFIX}{name}"),
program: program.to_path_buf(),
args: vec!["-c".into(), file.display().to_string()],
env: Vec::new(),
cwd: None,
generation: text,
}),
Err(e) => errors.push(e),
}
}
(units, errors)
}
/// The configuration, below the protected state root: it holds the tunnel's private key.
fn write(paths: &Paths, name: &str, text: &str) -> Result<(PathBuf, String)> {
let dir = paths.run().join("awg");
std::fs::create_dir_all(&dir)?;
let file = dir.join(format!("{name}.conf"));
write_atomic(&file, text.as_bytes()).with_context(|| format!("writing {}", file.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600))?;
}
Ok((file, text.to_owned()))
}
+1
View File
@@ -4,6 +4,7 @@
//! it); `--console` runs it in the foreground, which is also how it runs off Windows.
mod api;
mod awg;
mod clash;
mod components;
mod fetch;
+48 -2
View File
@@ -93,6 +93,12 @@ impl Service {
{
direct.push(p.to_string_lossy().into_owned());
}
// wireproxy's tunnels, like the sidecar's, would loop back into the TUN.
if derived_userspace(cfg)
&& let Some(p) = self.comps.find("wireproxy-awg", "wireproxy")
{
direct.push(p.to_string_lossy().into_owned());
}
// Tor's own connections, unless it is to go through the proxy (upstream = "proxy").
if cfg.tor.enable
&& cfg.tor.upstream == ps_core::config::Upstream::Direct
@@ -112,10 +118,10 @@ impl Service {
groups_watched: false,
sidecar_secret: self.sidecar_secret.clone(),
warp_profiles: crate::warp::profiles(cfg, paths),
awg_profiles: crate::awg::sing_box_profiles(cfg).0,
ssh_identity_path: cfg.ssh_proxy.identity_file.as_ref().map(|_| crate::ssh::identity_path(paths).to_string_lossy().into_owned()),
ssh_host_keys: if cfg.ssh_proxy.enable { crate::ssh::host_keys(cfg, |f| std::fs::read_to_string(f).ok()) } else { Vec::new() },
windows: cfg!(windows),
..Default::default()
}
}
@@ -153,8 +159,40 @@ impl Service {
if let Err(e) = &tor {
self.sup.note(crate::tor::UNIT, format!("proxy-suite: Tor: {e:#}"));
}
let awg = self.apply_awg().await;
if let Err(e) = &awg {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: AmneziaWG: {e:#}"));
}
let proxy = self.apply_proxy().await;
zapret.and(tg).and(ssh).and(tor).and(proxy)
zapret.and(tg).and(ssh).and(tor).and(awg).and(proxy)
}
/// The wireproxy tunnels behind "userspace" AmneziaWG outbounds and WARP devices, while
/// the proxy they serve runs; the ones no longer wanted stopped.
async fn apply_awg(&mut self) -> Result<()> {
let cfg = self.cfg().clone();
let userspace = derived_userspace(&cfg);
let (units, errors) = if self.proxy_wanted() && userspace {
let program = self.comps.program("wireproxy-awg", "wireproxy")?;
let login = (self.store.secrets.hop_user.clone(), self.store.secrets.hop_password.clone());
let warp = crate::warp::profiles(&cfg, self.paths());
crate::awg::units(&cfg, self.paths(), &program, (&login.0, &login.1), &warp)
} else {
(Vec::new(), Vec::new())
};
for e in errors {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: {e}; leaving it out"));
}
let wanted: Vec<String> = units.iter().map(|u| u.name.clone()).collect();
for name in self.sup.names() {
if name.starts_with(crate::awg::UNIT_PREFIX) && !wanted.contains(&name) {
self.sup.stop(&name).await;
}
}
for unit in units {
self.sup.ensure(unit);
}
Ok(())
}
async fn apply_tor(&mut self) -> Result<()> {
@@ -506,6 +544,14 @@ async fn decompile(sing_box: &PathBuf, srs: &std::path::Path) -> Result<Value> {
Ok(v)
}
/// Whether any outbound runs in wireproxy: a "userspace" AmneziaWG profile or WARP device.
fn derived_userspace(cfg: &Config) -> bool {
ps_core::derived::extra_outbounds(cfg).iter().any(|e| {
matches!(&e.kind, ps_core::derived::ExtraKind::Awg { kind: ps_core::config::AwgOutboundKind::Userspace, .. })
|| matches!(&e.kind, ps_core::derived::ExtraKind::Warp { device } if device.kind == ps_core::config::WarpOutboundKind::Userspace)
})
}
/// WARP devices with no profile, registered (outside the lock: it is the network), and the
/// proxy applied again with them.
pub async fn register_warp(shared: &Shared) {