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:
1 parent
d9d52c49b6
commit
62adadc207
12 files changed
+323
-7
No files matched your search
@@ -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),
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user