windows: WARP as a sing-box outbound

- Devices registered as wgcf registers them: an X25519 key made by the
  service, its public half posted to Cloudflare's client API (through the
  local proxy first, as upstream, then directly, then warp.generatorUrl),
  the answer made into wgcf's profile and kept below the protected state
  root; or a profile given (config, configFile). The renderer's endpoint
  for it was there; the service now supplies the profiles.
- Registration runs outside the service's lock, at start, after a change,
  and every ten minutes until it succeeds; the proxy is applied again
  with the new device.
- Checked: a device registered live with Cloudflare, its profile rendered
  as a sing-box WireGuard endpoint and the proxy running with it.
  WARP through AmneziaWG (userspace, interface) is still to come, and said.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-27 08:13:29 +03:00
1 parent d9d52c49b6
commit 62adadc207
12 files changed
+323 -7

No files matched your search

@@ -114,7 +114,8 @@ fn not_ported(cfg: &Config, v: &mut Issues) {
}
for (on, path, what) in [
(cfg.amnezia_wg.enable, "amneziaWg.enable", "AmneziaWG"),
(cfg.warp.enable, "warp.enable", "WARP"),
(cfg.warp.enable && cfg.warp.as_outbound.is_some_and(|k| k != crate::config::WarpOutboundKind::SingBox), "warp.asOutbound", "WARP through AmneziaWG (userspace, interface)"),
(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"),
(cfg.inbounds.enable, "inbounds.enable", "Serving inbounds"),
@@ -815,11 +816,11 @@ mod tests {
assert!(quiet.is_empty(), "{quiet:?}");
let mut cfg = Config::default();
cfg.kill_switch.enable = true;
cfg.warp.enable = true;
cfg.amnezia_wg.enable = true;
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", "warp.enable", "proxy.tun.enable"] {
for want in ["killSwitch.enable", "amneziaWg.enable", "proxy.tun.enable"] {
assert!(paths.iter().any(|p| p == want), "{want} not in {paths:?}");
}
}
+1
View File
@@ -10,6 +10,7 @@ pub mod derived;
pub mod duration;
pub mod links;
pub mod render;
pub mod warp;
pub mod wg;
pub mod zapret;
pub mod zapret2;
+94
View File
@@ -0,0 +1,94 @@
//! Cloudflare WARP's registration, as wgcf makes it: a device's public key sent to Cloudflare's
//! client API, and the answer turned into the WireGuard profile `wgcf generate` writes.
use serde_json::{Value, json};
/// Cloudflare's client API, the version wgcf speaks.
pub const API: &str = "https://api.cloudflareclient.com/v0a2158/reg";
/// The headers wgcf sends: the API answers the clients it knows.
pub const HEADERS: [(&str, &str); 2] = [("User-Agent", "okhttp/3.12.1"), ("CF-Client-Version", "a-6.30-3596")];
/// The registration's body: the device's public key (base64), the time the terms were
/// accepted (RFC 3339).
pub fn registration(public_key: &str, tos: &str) -> Value {
json!({
"install_id": "",
"fcm_token": "",
"tos": tos,
"key": public_key,
"type": "Android",
"model": "PC",
"locale": "en_US",
})
}
/// The WireGuard profile of a registration's answer, with the device's private key: as
/// `wgcf generate` writes it.
pub fn profile(answer: &Value, private_key: &str) -> Result<String, String> {
let c = &answer["config"];
let v4 = c["interface"]["addresses"]["v4"].as_str().ok_or("the answer has no IPv4 address")?;
let v6 = c["interface"]["addresses"]["v6"].as_str();
let peer = &c["peers"][0];
let public_key = peer["public_key"].as_str().ok_or("the answer has no peer key")?;
let endpoint = peer["endpoint"]["host"].as_str().unwrap_or("engage.cloudflareclient.com:2408");
let mut address = format!("{v4}/32");
if let Some(v6) = v6 {
address.push_str(&format!(", {v6}/128"));
}
Ok(format!(
"[Interface]\nPrivateKey = {private_key}\nAddress = {address}\nDNS = 1.1.1.1, 1.0.0.1, 2606:4700:4700::1111, 2606:4700:4700::1001\nMTU = 1280\n\n\
[Peer]\nPublicKey = {public_key}\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = {endpoint}\n"
))
}
/// What a generator (`warp.generatorUrl`) hands back: the profile, or `{"content": base64}`.
pub fn generated(body: &str) -> Result<String, String> {
let text = if body.trim_start().starts_with("[Interface]") {
body.to_owned()
} else {
let v: Value = serde_json::from_str(body).map_err(|_| "the generator's answer is neither a profile nor JSON")?;
let content = v["content"].as_str().ok_or("the generator's JSON has no content")?;
use base64::Engine;
let bytes = base64::engine::general_purpose::STANDARD.decode(content.trim()).map_err(|_| "the generator's content is not base64")?;
String::from_utf8(bytes).map_err(|_| "the generator's profile is not text")?
};
if !text.lines().any(|l| l.trim_start().starts_with("PrivateKey")) {
return Err("the generator's profile has no private key".into());
}
Ok(text)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_answer_becomes_wgcfs_profile() {
let answer = json!({
"config": {
"interface": { "addresses": { "v4": "172.16.0.2", "v6": "2606:4700:110:8a36::1" } },
"peers": [{ "public_key": "bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=", "endpoint": { "host": "engage.cloudflareclient.com:2408" } }],
}
});
let p = profile(&answer, "PRIV").unwrap();
assert!(p.contains("PrivateKey = PRIV\n"));
assert!(p.contains("Address = 172.16.0.2/32, 2606:4700:110:8a36::1/128\n"));
assert!(p.contains("PublicKey = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=\n"));
// What sing-box gets of it.
let (ep, _) = crate::wg::sing_box_endpoint(&p, "warp", None).unwrap();
assert_eq!(ep["peers"][0]["address"], "engage.cloudflareclient.com");
assert_eq!(ep["peers"][0]["port"], 2408);
assert!(profile(&json!({}), "PRIV").is_err());
}
#[test]
fn a_generators_answer_either_way() {
let p = "[Interface]\nPrivateKey = K\n";
assert_eq!(generated(p).unwrap(), p);
use base64::Engine;
let b = base64::engine::general_purpose::STANDARD.encode(p);
assert_eq!(generated(&format!(r#"{{"content":"{b}"}}"#)).unwrap(), p);
assert!(generated("<html>").is_err());
}
}
+2
View File
@@ -22,6 +22,8 @@ rustls.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
rand.workspace = true
base64.workspace = true
x25519-dalek = { version = "2", features = ["static_secrets"] }
sha2.workspace = true
zip.workspace = true
flate2 = "1"
+4
View File
@@ -281,6 +281,10 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
let shared = shared.clone();
tokio::spawn(async move { service::update_rule_sets(&shared, true).await });
}
{
let shared = shared.clone();
tokio::spawn(async move { service::register_warp(&shared).await });
}
Response::ok(json!({
"revision": revision,
"issues": issues_json(&issues),
+17
View File
@@ -69,6 +69,23 @@ pub async fn get(url: &str, route: &Route, limit: usize) -> Result<Vec<u8>> {
Ok(body)
}
/// `body` posted as JSON to `url` with `headers`, and the JSON answer.
pub async fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)], route: &Route) -> Result<serde_json::Value> {
let mut req = client(route)?.post(url).json(body);
for (k, v) in headers {
req = req.header(*k, *v);
}
let resp = req.send().await.map_err(|e| anyhow::anyhow!(describe(&e)))?;
if !resp.status().is_success() {
bail!("the server answered {}", resp.status());
}
let bytes = resp.bytes().await.map_err(|e| anyhow::anyhow!(describe(&e)))?;
if bytes.len() > 1 << 20 {
bail!("the answer is larger than a MiB");
}
Ok(serde_json::from_slice(&bytes)?)
}
/// A reqwest error without the URL it carries.
fn describe(e: &reqwest::Error) -> String {
let kind = if e.is_timeout() {
+2
View File
@@ -17,6 +17,7 @@ mod store;
mod tg;
mod tor;
mod units;
mod warp;
#[cfg(windows)]
mod winsvc;
mod zapret;
@@ -112,6 +113,7 @@ pub async fn run(
service::update_subscriptions(&shared, Some(&tag)).await;
}
service::update_rule_sets(&shared, true).await;
service::register_warp(&shared).await;
service::timers(shared).await;
});
}
+49 -2
View File
@@ -111,6 +111,7 @@ impl Service {
direct_processes: direct,
groups_watched: false,
sidecar_secret: self.sidecar_secret.clone(),
warp_profiles: crate::warp::profiles(cfg, paths),
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),
@@ -505,11 +506,52 @@ async fn decompile(sing_box: &PathBuf, srs: &std::path::Path) -> Result<Value> {
Ok(v)
}
/// 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) {
let (todo, routes, generator) = {
let s = shared.lock().await;
if !s.cfg().enable {
return;
}
(crate::warp::unregistered(s.cfg(), s.paths()), s.fetch_routes(true), s.cfg().warp.generator_url.clone())
};
let mut any = false;
for (tag, file) in todo {
let result = crate::warp::register(&routes, generator.as_deref()).await;
let mut s = shared.lock().await;
s.last_fetch.insert("warp".into(), SystemTime::now());
match result.and_then(|profile| {
std::fs::create_dir_all(file.parent().unwrap())?;
write_atomic(&file, profile.as_bytes())?;
// It holds the device's private key (on Windows the state root's ACL keeps it).
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600))?;
}
Ok(())
}) {
Ok(()) => {
s.sup.note(SOCKS_UNIT, format!("proxy-suite: WARP device '{tag}' is registered"));
any = true;
}
Err(e) => s.sup.note(SOCKS_UNIT, format!("proxy-suite: WARP device '{tag}' could not register: {e:#}")),
}
}
if any {
let mut s = shared.lock().await;
if let Err(e) = s.apply().await {
tracing::warn!("after WARP's registration: {e:#}");
}
}
}
/// The timers: subscriptions and rule sets, each on its interval.
pub async fn timers(shared: Shared) {
loop {
tokio::time::sleep(Duration::from_secs(60)).await;
let (sub_due, rules_due) = {
let (sub_due, rules_due, warp_due) = {
let s = shared.lock().await;
let cfg = s.cfg();
let every = |text: &str, default: u64| ps_core::duration::parse(text).unwrap_or(Duration::from_secs(default));
@@ -520,8 +562,13 @@ pub async fn timers(shared: Shared) {
};
let subs: Vec<String> =
cfg.proxy.subscriptions.iter().filter(|x| due(&format!("sub:{}", x.tag), sub_every)).map(|x| x.tag.clone()).collect();
(subs, due("rule-sets", rules_every))
// A registration that failed is tried again every ten minutes.
let warp = !crate::warp::unregistered(cfg, s.paths()).is_empty() && due("warp", Duration::from_secs(600));
(subs, due("rule-sets", rules_every), warp)
};
if warp_due {
register_warp(&shared).await;
}
for tag in sub_due {
update_subscriptions(&shared, Some(&tag)).await;
}
+99
View File
@@ -0,0 +1,99 @@
//! WARP devices: each one's WireGuard profile, given in the configuration or registered with
//! Cloudflare as wgcf registers (ps_core::warp), kept below the protected state root (it holds
//! the device's private key). The renderer makes each a sing-box WireGuard endpoint.
use std::collections::BTreeMap;
use std::path::PathBuf;
use anyhow::{Result, anyhow};
use base64::Engine;
use ps_core::config::Config;
use ps_core::derived::{self, WarpDeviceSpec};
use crate::fetch::{self, Route};
use crate::paths::Paths;
fn profile_file(paths: &Paths, device: &WarpDeviceSpec) -> PathBuf {
paths.root.join(&device.state_subdir).join("wgcf-profile.conf")
}
/// Each device's profile there is without the network: given, or registered before.
pub fn profiles(cfg: &Config, paths: &Paths) -> BTreeMap<String, String> {
derived::warp_devices(cfg)
.into_iter()
.filter_map(|d| {
let text = match (&d.config, &d.config_file) {
(Some(t), _) => Some(t.clone()),
(None, Some(f)) => std::fs::read_to_string(f).ok(),
(None, None) => std::fs::read_to_string(profile_file(paths, &d)).ok(),
};
text.map(|t| (d.tag, t))
})
.collect()
}
/// The devices to register, and where each one's profile goes: none given, none registered.
pub fn unregistered(cfg: &Config, paths: &Paths) -> Vec<(String, PathBuf)> {
derived::warp_devices(cfg)
.into_iter()
.filter(|d| d.auto_register())
.map(|d| {
let file = profile_file(paths, &d);
(d.tag, file)
})
.filter(|(_, file)| !file.is_file())
.collect()
}
/// Now as RFC 3339, the terms' acceptance time the API wants.
fn now() -> String {
let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);
let (days, rem) = (secs.div_euclid(86400), secs.rem_euclid(86400));
// Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.000Z", rem / 3600, rem % 3600 / 60, rem % 60)
}
/// A new device: a key made here, its public half registered through each route in turn
/// (the local proxy first: the API is blocked in some countries), then `generator` if given.
pub async fn register(routes: &[Route], generator: Option<&str>) -> Result<String> {
let mut seed = [0u8; 32];
rand::fill(&mut seed);
let secret = x25519_dalek::StaticSecret::from(seed);
let public = x25519_dalek::PublicKey::from(&secret);
let b64 = |b: &[u8]| base64::engine::general_purpose::STANDARD.encode(b);
let body = ps_core::warp::registration(&b64(public.as_bytes()), &now());
let mut last = None;
for route in routes {
match fetch::post_json(ps_core::warp::API, &body, &ps_core::warp::HEADERS, route).await {
Ok(answer) => return ps_core::warp::profile(&answer, &b64(&secret.to_bytes())).map_err(anyhow::Error::msg),
Err(e) => last = Some(e),
}
}
if let Some(url) = generator {
for route in routes {
if let Ok(body) = fetch::get(url, route, 64 * 1024).await {
return ps_core::warp::generated(&String::from_utf8_lossy(&body)).map_err(anyhow::Error::msg);
}
}
}
Err(last.unwrap_or_else(|| anyhow!("no way to reach it")).context("registering with Cloudflare"))
}
#[cfg(test)]
mod tests {
#[test]
fn now_is_rfc3339() {
let n = super::now();
assert_eq!(n.len(), 24, "{n}");
assert!(n.starts_with("20") && n.ends_with(".000Z") && &n[10..11] == "T", "{n}");
}
}