From 93000df6aaefdf95e08bc8d87ef3b7a105e7afa3 Mon Sep 17 00:00:00 2001 From: eric Date: Tue, 30 Sep 2025 17:46:58 +0800 Subject: [PATCH] Support NetFilter inbound --- leaf-cli/Cargo.toml | 33 +- leaf-ffi/Cargo.toml | 2 +- leaf/Cargo.toml | 8 +- leaf/src/app/api/api_server.rs | 179 ++--- leaf/src/app/fake_dns.rs | 16 +- leaf/src/app/inbound/manager.rs | 49 +- leaf/src/app/inbound/mod.rs | 3 + leaf/src/app/inbound/network_listener.rs | 45 +- leaf/src/app/outbound/selector_cache.rs | 2 +- leaf/src/config/conf/config.rs | 61 ++ leaf/src/config/geosite.rs | 2 +- leaf/src/config/internal/config.proto | 7 + leaf/src/config/internal/config.rs | 131 +++- leaf/src/config/json/config.rs | 42 ++ leaf/src/proxy/mod.rs | 9 +- leaf/src/proxy/nf/inbound/datagram.rs | 220 ++++++ leaf/src/proxy/nf/inbound/mod.rs | 876 +++++++++++++++++++++++ leaf/src/proxy/nf/inbound/stream.rs | 45 ++ leaf/src/proxy/nf/mod.rs | 2 + leaf/src/proxy/tun/inbound.rs | 12 +- 20 files changed, 1570 insertions(+), 174 deletions(-) create mode 100644 leaf/src/proxy/nf/inbound/datagram.rs create mode 100644 leaf/src/proxy/nf/inbound/mod.rs create mode 100644 leaf/src/proxy/nf/inbound/stream.rs create mode 100644 leaf/src/proxy/nf/mod.rs diff --git a/leaf-cli/Cargo.toml b/leaf-cli/Cargo.toml index dc01230..a584598 100644 --- a/leaf-cli/Cargo.toml +++ b/leaf-cli/Cargo.toml @@ -8,16 +8,29 @@ edition = "2021" name = "leaf" path = "src/main.rs" -[features] -default = [ - "leaf/default-ring", - "leaf/outbound-quic", - "leaf/outbound-quic", - "leaf/ctrlc", - "leaf/auto-reload", -] - [dependencies] -leaf = { path = "../leaf", default-features = false, optional = true } tokio = { version = "1", features = ["rt"] } argh = "0.1" + +[target.'cfg(not(windows))'.dependencies.leaf] +path = "../leaf" +default-features = false +features = [ + "default-ring", + "outbound-quic", + "outbound-quic", + "ctrlc", + "auto-reload" +] + +[target.'cfg(windows)'.dependencies.leaf] +path = "../leaf" +default-features = false +features = [ + "default-ring", + "outbound-quic", + "outbound-quic", + "ctrlc", + "auto-reload", + "inbound-nf" +] diff --git a/leaf-ffi/Cargo.toml b/leaf-ffi/Cargo.toml index 73e657d..6b11610 100644 --- a/leaf-ffi/Cargo.toml +++ b/leaf-ffi/Cargo.toml @@ -2,7 +2,7 @@ name = "leaf-ffi" version = "0.1.0" authors = ["eycorsican "] -edition = "2018" +edition = "2021" [lib] name = "leaf" diff --git a/leaf/Cargo.toml b/leaf/Cargo.toml index 27f1667..ef36db1 100644 --- a/leaf/Cargo.toml +++ b/leaf/Cargo.toml @@ -111,7 +111,7 @@ outbound-tryall = [] outbound-chain = [] outbound-amux= ["tokio-util"] outbound-quic = ["quinn", "rustls", "webpki-roots-old", "rustls-pemfile-old"] -outbound-select = ["directories"] +outbound-select = ["directories", "axum/query"] outbound-vmess = ["lz_fnv", "cfb-mode", "hmac", "aes", "sha3", "digest", "uuid", "md-5", "tokio-util", "byteorder"] # Inbounds @@ -126,10 +126,11 @@ inbound-quic = ["quinn", "rustls", "rustls-pemfile-old"] inbound-tls = [] inbound-chain = [] inbound-cat = ["tokio/io-std"] +inbound-nf = ["libloading"] plugin = ["async-ffi", "libloading"] stat = [] -api = ["warp"] +api = ["axum"] auto-reload = ["notify"] ctrlc = ["tokio/signal"] @@ -146,6 +147,7 @@ anyhow = "1.0" rand = "0.8" socket2 = "0.5" async-recursion = "1.1" +parking_lot = "*" # DNS trust-dns-proto = { version = "0.23", default-features = false } @@ -241,7 +243,7 @@ quinn = { version = "0.10", default-features = false, features = ["tls-rustls", rustls = { version = "0.21", optional = true } # API -warp = { version = "0.3", default-features = false, optional = true } +axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "json"], optional = true } # Auto reload notify = { version = "6", optional = true } diff --git a/leaf/src/app/api/api_server.rs b/leaf/src/app/api/api_server.rs index d01928b..81103db 100644 --- a/leaf/src/app/api/api_server.rs +++ b/leaf/src/app/api/api_server.rs @@ -4,8 +4,17 @@ use std::iter::FromIterator; use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; +use axum::{ + extract::State, + http::StatusCode, + response::{Html, Json}, + routing::{get, post}, + Router, +}; use tracing::info; -use warp::Filter; + +#[cfg(feature = "outbound-select")] +use axum::extract::Query; use crate::RuntimeManager; @@ -43,13 +52,12 @@ mod models { mod handlers { use super::*; - use warp::http::StatusCode; #[cfg(feature = "outbound-select")] pub async fn select_update( - opts: models::SelectOptions, - rm: Arc, - ) -> Result { + Query(opts): Query, + State(rm): State>, + ) -> Result { if let models::SelectOptions { outbound: Some(outbound), select: Some(select), @@ -64,41 +72,43 @@ mod handlers { #[cfg(feature = "outbound-select")] pub async fn select_get( - opts: models::SelectOptions, - rm: Arc, - ) -> Result { + Query(opts): Query, + State(rm): State>, + ) -> Result, Infallible> { if let models::SelectOptions { outbound: Some(outbound), .. } = opts { if let Ok(selected) = rm.get_outbound_selected(&outbound).await { - return Ok(warp::reply::json(&models::SelectReply { + return Ok(Json(models::SelectReply { selected: Some(selected), })); } } - Ok(warp::reply::json(&models::SelectReply { selected: None })) + Ok(Json(models::SelectReply { selected: None })) } #[cfg(feature = "outbound-select")] pub async fn select_list( - opts: models::SelectOptions, - rm: Arc, - ) -> Result { + Query(opts): Query, + State(rm): State>, + ) -> Result>, Infallible> { if let models::SelectOptions { outbound: Some(outbound), .. } = opts { if let Ok(selects) = rm.get_outbound_selects(&outbound).await { - return Ok(warp::reply::json(&selects)); + return Ok(Json(selects)); } } - Ok(warp::reply::json(&models::SelectReply { selected: None })) + Ok(Json(Vec::new())) } - pub async fn runtime_reload(rm: Arc) -> Result { + pub async fn runtime_reload( + State(rm): State>, + ) -> Result { if rm.reload().await.is_ok() { Ok(StatusCode::OK) } else { @@ -106,7 +116,9 @@ mod handlers { } } - pub async fn runtime_shutdown(rm: Arc) -> Result { + pub async fn runtime_shutdown( + State(rm): State>, + ) -> Result { if rm.shutdown().await { Ok(StatusCode::OK) } else { @@ -115,7 +127,9 @@ mod handlers { } #[cfg(feature = "stat")] - pub async fn stat_json(rm: Arc) -> Result { + pub async fn stat_json( + State(rm): State>, + ) -> Result>, Infallible> { let mut stats = Vec::new(); let sm = rm.stat_manager(); let sm = sm.read().await; @@ -133,11 +147,13 @@ mod handlers { recv_completed: c.recv_completed(), }); } - Ok(warp::reply::json(&stats)) + Ok(Json(stats)) } #[cfg(feature = "stat")] - pub async fn stat_html(rm: Arc) -> Result { + pub async fn stat_html( + State(rm): State>, + ) -> Result, Infallible> { let mut body = String::from( r#" - +
"#, ); let sm = rm.stat_manager(); @@ -198,95 +214,7 @@ table, th, td { )); } body.push_str("
"); - Ok(warp::reply::html(body)) - } -} - -mod filters { - use super::*; - - fn with_runtime_manager( - rm: Arc, - ) -> impl Filter,), Error = Infallible> + Clone { - warp::any().map(move || rm.clone()) - } - - // POST /api/v1/app/outbound/select?outbound=Proxy&select=p3 - #[cfg(feature = "outbound-select")] - pub fn select_update( - rm: Arc, - ) -> impl Filter + Clone { - warp::path!("api" / "v1" / "app" / "outbound" / "select") - .and(warp::post()) - .and(warp::query::()) - .and(with_runtime_manager(rm)) - .and_then(handlers::select_update) - } - - // GET /api/v1/app/outbound/select?outbound=Proxy - #[cfg(feature = "outbound-select")] - pub fn select_get( - rm: Arc, - ) -> impl Filter + Clone { - warp::path!("api" / "v1" / "app" / "outbound" / "select") - .and(warp::get()) - .and(warp::query::()) - .and(with_runtime_manager(rm)) - .and_then(handlers::select_get) - } - - // GET /api/v1/app/outbound/selects?outbound=Proxy - #[cfg(feature = "outbound-select")] - pub fn select_list( - rm: Arc, - ) -> impl Filter + Clone { - warp::path!("api" / "v1" / "app" / "outbound" / "selects") - .and(warp::get()) - .and(warp::query::()) - .and(with_runtime_manager(rm)) - .and_then(handlers::select_list) - } - - // POST /api/v1/runtime/reload - pub fn runtime_reload( - rm: Arc, - ) -> impl Filter + Clone { - warp::path!("api" / "v1" / "runtime" / "reload") - .and(warp::post()) - .and(with_runtime_manager(rm)) - .and_then(handlers::runtime_reload) - } - - // POST /api/v1/runtime/shutdown - pub fn runtime_shutdown( - rm: Arc, - ) -> impl Filter + Clone { - warp::path!("api" / "v1" / "runtime" / "shutdown") - .and(warp::post()) - .and(with_runtime_manager(rm)) - .and_then(handlers::runtime_shutdown) - } - - // GET /api/v1/runtime/stat/html - #[cfg(feature = "stat")] - pub fn stat_html( - rm: Arc, - ) -> impl Filter + Clone { - warp::path!("api" / "v1" / "runtime" / "stat" / "html") - .and(warp::get()) - .and(with_runtime_manager(rm)) - .and_then(handlers::stat_html) - } - - // GET /api/v1/runtime/stat/json - #[cfg(feature = "stat")] - pub fn stat_json( - rm: Arc, - ) -> impl Filter + Clone { - warp::path!("api" / "v1" / "runtime" / "stat" / "json") - .and(warp::get()) - .and(with_runtime_manager(rm)) - .and_then(handlers::stat_json) + Ok(Html(body)) } } @@ -300,21 +228,32 @@ impl ApiServer { } pub fn serve(&self, listen_addr: SocketAddr) -> crate::Runner { - let routes = filters::runtime_reload(self.runtime_manager.clone()) - .or(filters::runtime_shutdown(self.runtime_manager.clone())); + let mut app = Router::new() + .route("/api/v1/runtime/reload", post(handlers::runtime_reload)) + .route("/api/v1/runtime/shutdown", post(handlers::runtime_shutdown)); #[cfg(feature = "outbound-select")] - let routes = routes - .or(filters::select_update(self.runtime_manager.clone())) - .or(filters::select_get(self.runtime_manager.clone())) - .or(filters::select_list(self.runtime_manager.clone())); + { + app = app + .route("/api/v1/app/outbound/select", post(handlers::select_update)) + .route("/api/v1/app/outbound/select", get(handlers::select_get)) + .route("/api/v1/app/outbound/selects", get(handlers::select_list)); + } #[cfg(feature = "stat")] - let routes = routes - .or(filters::stat_html(self.runtime_manager.clone())) - .or(filters::stat_json(self.runtime_manager.clone())); + { + app = app + .route("/api/v1/runtime/stat/html", get(handlers::stat_html)) + .route("/api/v1/runtime/stat/json", get(handlers::stat_json)); + } + + let app = app.with_state(self.runtime_manager.clone()); info!("api server listening tcp {}", &listen_addr); - Box::pin(warp::serve(routes).bind(listen_addr)) + + Box::pin(async move { + let listener = tokio::net::TcpListener::bind(listen_addr).await.unwrap(); + axum::serve(listener, app).await.unwrap(); + }) } } diff --git a/leaf/src/app/fake_dns.rs b/leaf/src/app/fake_dns.rs index 8ac9d30..022241d 100644 --- a/leaf/src/app/fake_dns.rs +++ b/leaf/src/app/fake_dns.rs @@ -19,12 +19,8 @@ pub enum FakeDnsMode { pub struct FakeDns(RwLock); impl FakeDns { - pub fn new(mode: FakeDnsMode) -> Self { - Self(RwLock::new(FakeDnsImpl::new(mode))) - } - - pub async fn add_filter(&self, filter: String) { - self.0.write().await.add_filter(filter) + pub fn new(mode: FakeDnsMode, filters: Vec) -> Self { + Self(RwLock::new(FakeDnsImpl::new(mode, filters))) } pub async fn query_domain(&self, ip: &IpAddr) -> Option { @@ -56,7 +52,7 @@ struct FakeDnsImpl { } impl FakeDnsImpl { - pub(self) fn new(mode: FakeDnsMode) -> Self { + pub(self) fn new(mode: FakeDnsMode, filters: Vec) -> Self { let min_cursor = Self::ip_to_u32(&Ipv4Addr::new(198, 18, 0, 0)); let max_cursor = Self::ip_to_u32(&Ipv4Addr::new(198, 18, 255, 255)); Self { @@ -66,15 +62,11 @@ impl FakeDnsImpl { min_cursor, max_cursor, ttl: 1, - filters: Vec::new(), + filters, mode, } } - pub(self) fn add_filter(&mut self, filter: String) { - self.filters.push(filter); - } - pub(self) fn query_domain(&self, ip: &IpAddr) -> Option { let ip = match ip { IpAddr::V4(ip) => ip, diff --git a/leaf/src/app/inbound/manager.rs b/leaf/src/app/inbound/manager.rs index 8c71cd5..c43703b 100644 --- a/leaf/src/app/inbound/manager.rs +++ b/leaf/src/app/inbound/manager.rs @@ -15,6 +15,8 @@ use crate::Runner; use crate::proxy::amux; #[cfg(feature = "inbound-http")] use crate::proxy::http; +#[cfg(feature = "inbound-nf")] +use crate::proxy::nf; #[cfg(feature = "inbound-quic")] use crate::proxy::quic; #[cfg(feature = "inbound-shadowsocks")] @@ -80,6 +82,33 @@ impl InboundManager { )); handlers.insert(tag.clone(), handler); } + #[cfg(feature = "inbound-nf")] + "nf" => { + let settings: crate::config::NfInboundSettings = + protobuf::Message::parse_from_bytes(&inbound.settings)?; + nf::inbound::init(settings.driver_name.clone(), &settings.nfapi)?; + + use crate::app::fake_dns::{FakeDns, FakeDnsMode}; + let fake_dns_exclude = settings.fake_dns_exclude.clone(); + let fake_dns_include = settings.fake_dns_include.clone(); + let (mode, filters) = if !fake_dns_include.is_empty() { + (FakeDnsMode::Include, fake_dns_include) + } else { + (FakeDnsMode::Exclude, fake_dns_exclude) + }; + let fake_dns = Arc::new(FakeDns::new(mode, filters)); + + let stream = Arc::new(nf::inbound::StreamHandler { + fake_dns: fake_dns.clone(), + }); + let datagram = Arc::new(nf::inbound::DatagramHandler { fake_dns }); + let handler = Arc::new(crate::proxy::inbound::Handler::new( + tag.clone(), + Some(stream), + Some(datagram), + )); + handlers.insert(tag.clone(), handler); + } #[cfg(feature = "inbound-shadowsocks")] "shadowsocks" => { let settings = @@ -262,17 +291,15 @@ impl InboundManager { cat_listener.replace(listener); } _ => { - if inbound.port != 0 { - if let Some(h) = handlers.get(&tag) { - let listener = NetworkInboundListener { - address: inbound.address.clone(), - port: inbound.port as u16, - handler: h.clone(), - dispatcher: dispatcher.clone(), - nat_manager: nat_manager.clone(), - }; - network_listeners.insert(tag.clone(), listener); - } + if let Some(h) = handlers.get(&tag) { + let listener = NetworkInboundListener { + address: inbound.address.clone(), + port: inbound.port as u16, + handler: h.clone(), + dispatcher: dispatcher.clone(), + nat_manager: nat_manager.clone(), + }; + network_listeners.insert(tag.clone(), listener); } } } diff --git a/leaf/src/app/inbound/mod.rs b/leaf/src/app/inbound/mod.rs index a1c99ad..e6f138b 100644 --- a/leaf/src/app/inbound/mod.rs +++ b/leaf/src/app/inbound/mod.rs @@ -7,3 +7,6 @@ mod tun_listener; mod cat_listener; pub mod manager; + +#[cfg(feature = "inbound-nf")] +pub use network_listener::get_network_listen_addr; diff --git a/leaf/src/app/inbound/network_listener.rs b/leaf/src/app/inbound/network_listener.rs index da10319..3fbf1db 100644 --- a/leaf/src/app/inbound/network_listener.rs +++ b/leaf/src/app/inbound/network_listener.rs @@ -18,6 +18,22 @@ use crate::proxy::*; use crate::session::{Network, Session, SocksAddr}; use crate::Runner; +#[cfg(feature = "inbound-nf")] +lazy_static::lazy_static! { + pub static ref TCP_LISTENING_ADDRESSES: std::sync::RwLock> = + std::sync::RwLock::new(std::collections::HashMap::new()); + pub static ref UDP_LISTENING_ADDRESSES: std::sync::RwLock> = + std::sync::RwLock::new(std::collections::HashMap::new()); +} + +#[cfg(feature = "inbound-nf")] +pub fn get_network_listen_addr(tag: &str, kind: Network) -> Option { + match kind { + Network::Tcp => TCP_LISTENING_ADDRESSES.read().unwrap().get(tag).copied(), + Network::Udp => UDP_LISTENING_ADDRESSES.read().unwrap().get(tag).copied(), + } +} + // Handle an inbound datagram, which is similar to a UDP socket, managed by NAT // manager. async fn handle_inbound_datagram( @@ -48,12 +64,11 @@ async fn handle_inbound_datagram( pkt.data.len() ); if let Err(e) = ls.send_to(&pkt.data[..], &pkt.src_addr, dst_addr).await { - debug!("Send datagram failed: {}", e); - break; + debug!("send datagram failed: {}", e); } } if let Err(e) = ls.close().await { - debug!("Failed to close inbound datagram: {}", e); + debug!("failed to close inbound datagram: {}", e); } }); @@ -61,11 +76,11 @@ async fn handle_inbound_datagram( loop { match lr.recv_from(&mut buf).await { Err(ProxyError::DatagramFatal(e)) => { - debug!("Fatal error when receiving datagram: {}", e); + debug!("fatal error when receiving datagram: {}", e); break; } Err(ProxyError::DatagramWarn(e)) => { - debug!("Warning when receiving datagram: {}", e); + debug!("warning when receiving datagram: {}", e); continue; } Ok((n, dgram_src, dst_addr)) => { @@ -168,7 +183,17 @@ async fn handle_tcp_listen( nat_manager: Arc, ) -> io::Result<()> { let listener = crate::proxy::TcpListener::bind(&listen_addr).await?; + let listen_addr = listener.io().local_addr()?; info!("listening tcp {}", &listen_addr); + + #[cfg(feature = "inbound-nf")] + { + TCP_LISTENING_ADDRESSES + .write() + .unwrap() + .insert(handler.tag().clone(), listen_addr); + } + loop { let (stream, _) = listener.accept().await?; let handler_cloned = handler.clone(); @@ -198,7 +223,17 @@ async fn handle_udp_listen( nat_manager: Arc, ) -> io::Result<()> { let socket = UdpSocket::bind(&listen_addr).await?; + let listen_addr = socket.local_addr()?; info!("listening udp {}", &listen_addr); + + #[cfg(feature = "inbound-nf")] + { + UDP_LISTENING_ADDRESSES + .write() + .unwrap() + .insert(handler.tag().clone(), listen_addr); + } + // Transforms the UDP socket into an inbound transport. let transport = handler .datagram()? diff --git a/leaf/src/app/outbound/selector_cache.rs b/leaf/src/app/outbound/selector_cache.rs index 84dbea2..f64586c 100644 --- a/leaf/src/app/outbound/selector_cache.rs +++ b/leaf/src/app/outbound/selector_cache.rs @@ -1,5 +1,5 @@ // This file is generated by rust-protobuf 3.6.0. Do not edit -// .proto file is parsed by protoc 29.3 +// .proto file is parsed by protoc 32.1 // @generated // https://github.com/rust-lang/rust-clippy/issues/702 diff --git a/leaf/src/config/conf/config.rs b/leaf/src/config/conf/config.rs index 1519c85..60f4847 100644 --- a/leaf/src/config/conf/config.rs +++ b/leaf/src/config/conf/config.rs @@ -19,9 +19,16 @@ pub struct Tun { pub mtu: Option, } +#[derive(Debug, Default)] +pub struct Nf { + pub driver_name: String, + pub nfapi: Option, +} + #[derive(Debug, Default)] pub struct General { pub tun: Option, + pub nf: Option, pub tun_fd: Option, pub tun_auto: Option, pub loglevel: Option, @@ -308,6 +315,21 @@ pub fn from_lines(lines: Vec>) -> Result { general.tun = Some(tun); } } + "nf" => { + // nf = driver_name, path/to/nfapi.dll + if let Some(items) = get_char_sep_slice(parts[1], ',') { + let nfapi = if items.len() >= 2 { + Some(items[1].trim().to_owned()) + } else { + None + }; + let nf = Nf { + driver_name: items[0].trim().to_owned(), + nfapi, + }; + general.nf = Some(nf); + } + } "loglevel" => { general.loglevel = Some(parts[1].to_string()); } @@ -782,6 +804,45 @@ pub fn to_internal(conf: &mut Config) -> Result { inbounds.push(inbound); } + if let Some(nf) = ext_general.nf.as_ref() { + let mut inbound = internal::Inbound::new(); + inbound.protocol = "nf".to_string(); + inbound.tag = "nf".to_string(); + inbound.address = "127.0.0.1".to_string(); + inbound.port = 0; + let mut settings = internal::NfInboundSettings::new(); + + let mut fake_dns_exclude = Vec::new(); + if let Some(ext_always_real_ip) = &ext_general.always_real_ip { + for item in ext_always_real_ip { + fake_dns_exclude.push(item.clone()) + } + if !fake_dns_exclude.is_empty() { + settings.fake_dns_exclude = fake_dns_exclude; + } + } + + let mut fake_dns_include = Vec::new(); + if let Some(ext_always_fake_ip) = &ext_general.always_fake_ip { + for item in ext_always_fake_ip { + fake_dns_include.push(item.clone()) + } + if !fake_dns_include.is_empty() { + settings.fake_dns_include = fake_dns_include; + } + } + + settings.driver_name = nf.driver_name.clone(); + settings.nfapi = nf + .nfapi + .as_ref() + .cloned() + .unwrap_or("nfapi.dll".to_string()); + let settings = settings.write_to_bytes().unwrap(); + inbound.settings = settings; + inbounds.push(inbound); + } + if ext_general.tun_fd.is_some() || ext_general.tun_auto.is_some() || ext_general.tun.is_some() diff --git a/leaf/src/config/geosite.rs b/leaf/src/config/geosite.rs index 7ca8989..7874162 100644 --- a/leaf/src/config/geosite.rs +++ b/leaf/src/config/geosite.rs @@ -1,5 +1,5 @@ // This file is generated by rust-protobuf 3.6.0. Do not edit -// .proto file is parsed by protoc 29.3 +// .proto file is parsed by protoc 32.1 // @generated // https://github.com/rust-lang/rust-clippy/issues/702 diff --git a/leaf/src/config/internal/config.proto b/leaf/src/config/internal/config.proto index 5d1e9f1..5fe53a3 100644 --- a/leaf/src/config/internal/config.proto +++ b/leaf/src/config/internal/config.proto @@ -66,6 +66,13 @@ message AMuxInboundSettings { repeated string actors = 1; } +message NfInboundSettings { + string driver_name = 1; + string nfapi = 2; + repeated string fake_dns_exclude = 3; + repeated string fake_dns_include = 4; +} + message QuicInboundSettings { string certificate = 1; string certificate_key = 2; diff --git a/leaf/src/config/internal/config.rs b/leaf/src/config/internal/config.rs index fe22415..55b0280 100644 --- a/leaf/src/config/internal/config.rs +++ b/leaf/src/config/internal/config.rs @@ -1,5 +1,5 @@ // This file is generated by rust-protobuf 3.6.0. Do not edit -// .proto file is parsed by protoc 29.3 +// .proto file is parsed by protoc 32.1 // @generated // https://github.com/rust-lang/rust-clippy/issues/702 @@ -1152,6 +1152,135 @@ impl ::protobuf::Message for AMuxInboundSettings { } } +// @@protoc_insertion_point(message:NfInboundSettings) +#[derive(PartialEq,Clone,Default,Debug)] +pub struct NfInboundSettings { + // message fields + // @@protoc_insertion_point(field:NfInboundSettings.driver_name) + pub driver_name: ::std::string::String, + // @@protoc_insertion_point(field:NfInboundSettings.nfapi) + pub nfapi: ::std::string::String, + // @@protoc_insertion_point(field:NfInboundSettings.fake_dns_exclude) + pub fake_dns_exclude: ::std::vec::Vec<::std::string::String>, + // @@protoc_insertion_point(field:NfInboundSettings.fake_dns_include) + pub fake_dns_include: ::std::vec::Vec<::std::string::String>, + // special fields + // @@protoc_insertion_point(special_field:NfInboundSettings.special_fields) + pub special_fields: ::protobuf::SpecialFields, +} + +impl<'a> ::std::default::Default for &'a NfInboundSettings { + fn default() -> &'a NfInboundSettings { + ::default_instance() + } +} + +impl NfInboundSettings { + pub fn new() -> NfInboundSettings { + ::std::default::Default::default() + } +} + +impl ::protobuf::Message for NfInboundSettings { + const NAME: &'static str = "NfInboundSettings"; + + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.driver_name = is.read_string()?; + }, + 18 => { + self.nfapi = is.read_string()?; + }, + 26 => { + self.fake_dns_exclude.push(is.read_string()?); + }, + 34 => { + self.fake_dns_include.push(is.read_string()?); + }, + tag => { + ::protobuf::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + if !self.driver_name.is_empty() { + my_size += ::protobuf::rt::string_size(1, &self.driver_name); + } + if !self.nfapi.is_empty() { + my_size += ::protobuf::rt::string_size(2, &self.nfapi); + } + for value in &self.fake_dns_exclude { + my_size += ::protobuf::rt::string_size(3, &value); + }; + for value in &self.fake_dns_include { + my_size += ::protobuf::rt::string_size(4, &value); + }; + my_size += ::protobuf::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::Result<()> { + if !self.driver_name.is_empty() { + os.write_string(1, &self.driver_name)?; + } + if !self.nfapi.is_empty() { + os.write_string(2, &self.nfapi)?; + } + for v in &self.fake_dns_exclude { + os.write_string(3, &v)?; + }; + for v in &self.fake_dns_include { + os.write_string(4, &v)?; + }; + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &::protobuf::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut ::protobuf::SpecialFields { + &mut self.special_fields + } + + fn new() -> NfInboundSettings { + NfInboundSettings::new() + } + + fn clear(&mut self) { + self.driver_name.clear(); + self.nfapi.clear(); + self.fake_dns_exclude.clear(); + self.fake_dns_include.clear(); + self.special_fields.clear(); + } + + fn default_instance() -> &'static NfInboundSettings { + static instance: NfInboundSettings = NfInboundSettings { + driver_name: ::std::string::String::new(), + nfapi: ::std::string::String::new(), + fake_dns_exclude: ::std::vec::Vec::new(), + fake_dns_include: ::std::vec::Vec::new(), + special_fields: ::protobuf::SpecialFields::new(), + }; + &instance + } +} + // @@protoc_insertion_point(message:QuicInboundSettings) #[derive(PartialEq,Clone,Default,Debug)] pub struct QuicInboundSettings { diff --git a/leaf/src/config/json/config.rs b/leaf/src/config/json/config.rs index 261ba7f..b2c6217 100644 --- a/leaf/src/config/json/config.rs +++ b/leaf/src/config/json/config.rs @@ -28,6 +28,17 @@ pub struct CatInboundSettings { pub port: u16, } +#[derive(Serialize, Deserialize, Debug)] +pub struct NfInboundSettings { + #[serde(rename = "driverName")] + pub driver_name: String, + pub nfapi: Option, + #[serde(rename = "fakeDnsExclude")] + pub fake_dns_exclude: Option>, + #[serde(rename = "fakeDnsInclude")] + pub fake_dns_include: Option>, +} + #[derive(Serialize, Deserialize, Debug)] pub struct ShadowsocksInboundSettings { pub method: Option, @@ -402,6 +413,37 @@ pub fn to_internal(json: &mut Config) -> Result { inbound.settings = settings; inbounds.push(inbound); } + "nf" => { + let mut settings = internal::NfInboundSettings::new(); + let ext_settings: NfInboundSettings = + serde_json::from_str(ext_inbound.settings.as_ref().unwrap().get()).unwrap(); + + let mut fake_dns_exclude = Vec::new(); + if let Some(ext_excludes) = ext_settings.fake_dns_exclude { + for ext_exclude in ext_excludes { + fake_dns_exclude.push(ext_exclude); + } + } + if !fake_dns_exclude.is_empty() { + settings.fake_dns_exclude = fake_dns_exclude; + } + + let mut fake_dns_include = Vec::new(); + if let Some(ext_includes) = ext_settings.fake_dns_include { + for ext_include in ext_includes { + fake_dns_include.push(ext_include); + } + } + if !fake_dns_include.is_empty() { + settings.fake_dns_include = fake_dns_include; + } + + settings.driver_name = ext_settings.driver_name; + settings.nfapi = ext_settings.nfapi.unwrap_or("nfapi.dll".to_string()); + let settings = settings.write_to_bytes().unwrap(); + inbound.settings = settings; + inbounds.push(inbound); + } "http" => { inbounds.push(inbound); } diff --git a/leaf/src/proxy/mod.rs b/leaf/src/proxy/mod.rs index 4f9d76c..ada2f0a 100644 --- a/leaf/src/proxy/mod.rs +++ b/leaf/src/proxy/mod.rs @@ -48,6 +48,8 @@ pub mod drop; pub mod failover; #[cfg(feature = "inbound-http")] pub mod http; +#[cfg(feature = "inbound-nf")] +pub mod nf; #[cfg(feature = "outbound-obfs")] pub mod obfs; #[cfg(any(feature = "inbound-quic", feature = "outbound-quic"))] @@ -183,6 +185,10 @@ impl TcpListener { }) } + pub fn io(&self) -> &tokio::net::TcpListener { + &self.inner + } + pub async fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { let (stream, addr) = self.inner.accept().await?; apply_socket_opts(&stream)?; @@ -306,7 +312,8 @@ pub async fn new_udp_socket(indicator: &SocketAddr) -> io::Result { } fn apply_socket_opts_internal(s: SockRef) -> io::Result<()> { - s.set_keepalive(true) + s.set_keepalive(true)?; + s.set_nodelay(true) } #[cfg(unix)] diff --git a/leaf/src/proxy/nf/inbound/datagram.rs b/leaf/src/proxy/nf/inbound/datagram.rs new file mode 100644 index 0000000..5383a78 --- /dev/null +++ b/leaf/src/proxy/nf/inbound/datagram.rs @@ -0,0 +1,220 @@ +use std::convert::TryFrom; +use std::io; +use std::net::SocketAddr; + +use anyhow::anyhow; +use async_trait::async_trait; +use tracing::{trace, warn}; + +use crate::{ + app::fake_dns::FakeDns, + proxy::*, + session::{SocksAddr, SocksAddrWireType}, +}; + +use super::packed::{SOCKADDR_IN, SOCKADDR_IN6}; + +pub struct Handler { + pub fake_dns: Arc, +} + +#[async_trait] +impl InboundDatagramHandler for Handler { + async fn handle<'a>(&'a self, socket: AnyInboundDatagram) -> io::Result { + Ok(InboundTransport::Datagram( + Box::new(Datagram { + socket, + fake_dns: self.fake_dns.clone(), + }), + None, + )) + } +} + +pub struct Datagram { + socket: Box, + fake_dns: Arc, +} + +impl InboundDatagram for Datagram { + fn split( + self: Box, + ) -> ( + Box, + Box, + ) { + let (rh, sh) = self.socket.split(); + ( + Box::new(DatagramRecvHalf(rh, self.fake_dns.clone())), + Box::new(DatagramSendHalf(sh, self.fake_dns)), + ) + } + + fn into_std(self: Box) -> io::Result { + self.socket.into_std() + } +} + +pub struct DatagramRecvHalf(Box, Arc); + +#[async_trait] +impl InboundDatagramRecvHalf for DatagramRecvHalf { + async fn recv_from( + &mut self, + buf: &mut [u8], + ) -> ProxyResult<(usize, DatagramSource, SocksAddr)> { + let mut recv_buf = vec![0u8; buf.len()]; + let (n, mut src_addr, _) = self.0.recv_from(&mut recv_buf).await?; + let dst_addr = SocksAddr::try_from((&recv_buf[0..], SocksAddrWireType::PortLast)) + .map_err(|e| ProxyError::DatagramWarn(anyhow!("parse target address failed: {}", e)))?; + let id = u64::from_be_bytes( + recv_buf[dst_addr.size()..dst_addr.size() + 8] + .try_into() + .unwrap(), + ); + + let header_size = dst_addr.size() + 8; + let payload_size = n - header_size; + assert!(buf.len() >= payload_size); + let real_payload = &recv_buf[header_size..header_size + payload_size]; + + let local_addr = if let Some(info) = super::UDP_LOCAL_INFO.lock().unwrap().get(&id) { + info.local_address.clone() + } else { + return Err(ProxyError::DatagramWarn(anyhow!(format!( + "local socket not found id={}", + id + )))); + }; + + // Override with real source address. + src_addr.address = local_addr; + + if dst_addr.port() == 53 { + match self.1.generate_fake_response(real_payload).await { + Ok(resp) => { + if let Err(e) = udp_post_receive(&local_addr, *dst_addr.must_ip(), &resp) { + warn!("send to local failed: {}", e); + } + return Err(ProxyError::DatagramWarn(anyhow!(format!( + "responsed with fake ip, id={}", + id + )))); + } + Err(e) => { + debug!("generate fake ip failed: {}", e); + } + } + } + + let dst_addr = match dst_addr { + SocksAddr::Domain(domain, port) => SocksAddr::Domain(domain, port), + SocksAddr::Ip(addr) => { + if self.1.is_fake_ip(&addr.ip()).await { + if let Some(domain) = self.1.query_domain(&addr.ip()).await { + SocksAddr::Domain(domain, addr.port()) + } else { + return Err(ProxyError::DatagramWarn(anyhow!(format!( + "paired domain not found ip={}", + &addr.ip() + )))); + } + } else { + SocksAddr::Ip(addr) + } + } + }; + + buf[..payload_size].copy_from_slice(real_payload); + Ok((payload_size, src_addr, dst_addr)) + } +} + +pub struct DatagramSendHalf(Box, Arc); + +fn udp_post_receive( + local_addr: &SocketAddr, + src_addr: SocketAddr, + buf: &[u8], +) -> io::Result { + if let Some(id) = super::UDP_ENDPOINT.lock().unwrap().get(local_addr) { + if let Some(options) = super::UDP_OPTIONS.lock().unwrap().get(id) { + let status = unsafe { + match src_addr { + SocketAddr::V4(addr) => { + let addr: SOCKADDR_IN = addr.into(); + let addr = &addr as *const SOCKADDR_IN as *const u8; + super::NF_UDP_POST_RECEIVE.unwrap()( + *id, + addr, + buf.as_ptr(), + buf.len() as _, + options.as_ptr() as *const _ as *mut _, + ) + } + SocketAddr::V6(addr) => { + let addr: SOCKADDR_IN6 = addr.into(); + let addr = &addr as *const SOCKADDR_IN6 as *const u8; + super::NF_UDP_POST_RECEIVE.unwrap()( + *id, + addr, + buf.as_ptr(), + buf.len() as _, + options.as_ptr() as *const _ as *mut _, + ) + } + } + }; + if status != super::NF_STATUS_SUCCESS { + Err(io::Error::new( + io::ErrorKind::Other, + format!("status={}", status), + )) + } else { + Ok(buf.len()) + } + } else { + Err(io::Error::new( + io::ErrorKind::Other, + format!("local socket not found, id={}", id), + )) + } + } else { + Err(io::Error::new( + io::ErrorKind::Other, + format!("local socket not found, local_addr={}", local_addr), + )) + } +} + +#[async_trait] +impl InboundDatagramSendHalf for DatagramSendHalf { + async fn send_to( + &mut self, + buf: &[u8], + src_addr: &SocksAddr, + dst_addr: &SocketAddr, + ) -> io::Result { + if buf.is_empty() { + return Ok(0); + } + let src_addr = match src_addr { + SocksAddr::Ip(a) => *a, + SocksAddr::Domain(domain, port) => { + if let Some(ip) = self.1.query_fake_ip(&domain).await { + SocketAddr::new(ip, *port) + } else { + return Err(io::Error::other(format!( + "paired fake ip not found, addr={}:{}", + &domain, &port + ))); + } + } + }; + udp_post_receive(dst_addr, src_addr, buf) + } + + async fn close(&mut self) -> io::Result<()> { + self.0.close().await + } +} diff --git a/leaf/src/proxy/nf/inbound/mod.rs b/leaf/src/proxy/nf/inbound/mod.rs new file mode 100644 index 0000000..9227d96 --- /dev/null +++ b/leaf/src/proxy/nf/inbound/mod.rs @@ -0,0 +1,876 @@ +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] + +use std::collections::{hash_map::Entry, HashMap}; +use std::ffi::CString; +use std::ffi::OsStr; +use std::ffi::OsString; +use std::mem::transmute; +use std::net::{IpAddr, SocketAddr}; +use std::os::windows::ffi::OsStringExt; +use std::path::Path; +use std::ptr::{addr_of, addr_of_mut}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::sync::LazyLock; +use std::sync::Mutex; +use std::thread; + +mod datagram; +mod stream; + +pub use datagram::Handler as DatagramHandler; +pub use stream::Handler as StreamHandler; + +use anyhow::{anyhow, Result}; +use bytes::{BufMut, BytesMut}; +use parking_lot::RwLock; +use tracing::{debug, instrument, trace, warn}; + +use packed::{SOCKADDR, SOCKADDR_IN, SOCKADDR_IN6}; + +const MAX_PATH: usize = 260; +const IPPROTO_TCP: i32 = 6; + +pub const NF_STATUS_SUCCESS: NfStatus = 0; + +#[allow(dead_code)] +#[derive(Debug)] +enum NfDirection { + In, + Out, + Both, + Unknown(u8), +} + +impl NfDirection { + fn value(&self) -> u8 { + match self { + Self::In => 1, + Self::Out => 2, + Self::Both => 3, + Self::Unknown(v) => *v, + } + } +} + +#[allow(dead_code)] +#[derive(Debug)] +enum NfFilteringFlag { + NfAllow, // Allow the activity without filtering transmitted packets + NfBlock, // Block the activity + NfFilter, // Filter the transmitted packets + NfSuspended, // Suspend receives from server and sends from client + NfOffline, // Emulate establishing a TCP connection with remote server + NfIndicateConnectRequests, // Indicate outgoing connect requests to API + NfDisableRedirectProtection, // Disable blocking indicating connect requests for outgoing connections of local proxies + NfPendConnectRequest, // Pend outgoing connect request to complete it later using nf_complete(TCP|UDP)ConnectRequest + NfFilterAsIpPackets, // Indicate the traffic as IP packets via ipSend/ipReceive + NfReadonly, // Don't block the IP packets and indicate them to ipSend/ipReceive only for monitoring + NfControlFlow, // Use the flow limit rules even without NF_FILTER flag + NfRedirect, // Redirect the outgoing TCP connections to address specified in redirectTo + NfBypassIpPackets, // Bypass the traffic as IP packets, when used with NF_FILTER_AS_IP_PACKETS flag + Unknown(u32), +} + +impl NfFilteringFlag { + fn value(&self) -> u32 { + match self { + Self::NfAllow => 0, + Self::NfBlock => 1, + Self::NfFilter => 2, + Self::NfSuspended => 4, + Self::NfOffline => 8, + Self::NfIndicateConnectRequests => 16, + Self::NfDisableRedirectProtection => 32, + Self::NfPendConnectRequest => 64, + Self::NfFilterAsIpPackets => 128, + Self::NfReadonly => 256, + Self::NfControlFlow => 512, + Self::NfRedirect => 1024, + Self::NfBypassIpPackets => 2048, + Self::Unknown(v) => *v, + } + } +} + +pub type NfStatus = i32; + +type NfInitFn = unsafe extern "C" fn(*const u8, *const NfEventHandler) -> NfStatus; +type NfFreeFn = unsafe extern "C" fn(); +type NfAddRuleFn = unsafe extern "C" fn(*const NfRule, i32) -> NfStatus; +type NfTcpPostReceiveFn = unsafe extern "C" fn(EndpointId, *const u8, i32) -> NfStatus; +type NfTcpPostSendFn = unsafe extern "C" fn(EndpointId, *const u8, i32) -> NfStatus; +type NfUdpPostReceiveFn = + unsafe extern "C" fn(EndpointId, *const u8, *const u8, i32, *mut NfUdpOptions) -> NfStatus; +type NfUdpPostSendFn = + unsafe extern "C" fn(EndpointId, *const u8, *const u8, i32, *mut NfUdpOptions) -> NfStatus; +type NfTcpDisableFilteringFn = unsafe extern "C" fn(EndpointId); +type NfUdpDisableFilteringFn = unsafe extern "C" fn(EndpointId); +type NfAdjustProcessPriviledgesFn = unsafe extern "C" fn(); +type NfGetUdpConnInfoFn = unsafe extern "C" fn(EndpointId, *mut NfUdpConnInfo) -> NfStatus; + +// FIXME Ensure no concurrent access to these fns from different threads. +static NFAPI: RwLock> = RwLock::new(None); +static mut NF_INIT: Option = None; +static mut NF_FREE: Option = None; +static mut NF_ADD_RULE: Option = None; +static mut NF_TCP_POST_RECEIVE: Option = None; +static mut NF_TCP_POST_SEND: Option = None; +static mut NF_UDP_POST_RECEIVE: Option = None; +static mut NF_UDP_POST_SEND: Option = None; +static mut NF_TCP_DISABLE_FILTERING: Option = None; +static mut NF_UDP_DISABLE_FILTERING: Option = None; +static mut NF_ADJUST_PROCESS_PRIVILEDGES: Option = None; +static mut NF_GET_UDP_CONN_INFO: Option = None; + +static mut TX: Option> = None; +static UDP_SEND_SOCKET: RwLock> = RwLock::new(None); + +struct ConnInfo { + remote_addr: SocketAddr, +} + +#[derive(Debug)] +pub struct UdpLocalInfo { + local_address: SocketAddr, +} + +pub static UDP_LOCAL_INFO: LazyLock>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +pub static UDP_ENDPOINT: LazyLock>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +pub static UDP_OPTIONS: LazyLock>>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +static TCP_INFO: LazyLock>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +type EndpointId = u64; + +#[repr(C, packed)] +#[derive(Default)] +struct NfRule { + protocol: i32, + processId: u32, + direction: u8, + localPort: u16, + remotePort: u16, + ip_family: u16, + localIpAddress: [u8; 16], + localIpAddressMask: [u8; 16], + remoteIpAddress: [u8; 16], + remoteIpAddressMask: [u8; 16], + filteringFlag: u32, +} + +#[repr(C, packed)] +struct NfTcpConnInfo { + filteringFlag: u32, + processId: u32, + direction: u8, + ip_family: u16, + localAddress: [u8; 28], + remoteAddress: [u8; 28], +} + +impl NfTcpConnInfo { + unsafe fn get_local_address(info: *const NfTcpConnInfo) -> Result { + sockaddr_to_socketaddr( + &addr_of!((*info).localAddress).read_unaligned() as *const [u8; 28] as *const SOCKADDR, + ) + } + + unsafe fn get_remote_address(info: *const NfTcpConnInfo) -> Result { + sockaddr_to_socketaddr( + &addr_of!((*info).remoteAddress).read_unaligned() as *const [u8; 28] as *const SOCKADDR, + ) + } +} + +#[repr(C, packed)] +struct NfUdpConnInfo { + processId: u32, + ip_family: u16, + localAddress: [u8; 28], +} + +impl NfUdpConnInfo { + unsafe fn get_local_address(info: *const NfUdpConnInfo) -> Result { + sockaddr_to_socketaddr( + &addr_of!((*info).localAddress).read_unaligned() as *const [u8; 28] as *const SOCKADDR, + ) + } +} + +impl Default for NfUdpConnInfo { + fn default() -> Self { + unsafe { core::mem::zeroed() } + } +} + +#[repr(C, packed)] +struct NfUdpConnRequest { + filteringFlag: u32, + processId: u32, + ip_family: u16, + localAddress: [u8; 28], + remoteAddress: [u8; 28], +} + +#[repr(C, packed)] +#[derive(Clone, Copy, Debug)] +pub struct NfUdpOptions { + flags: u32, + optionsLength: i32, + options: [u8; 1], +} + +#[repr(C, packed)] +struct NfEventHandler { + threadStart: unsafe extern "C" fn(), + threadEnd: unsafe extern "C" fn(), + tcpConnectRequest: unsafe extern "C" fn(EndpointId, *mut NfTcpConnInfo), + tcpConnected: unsafe extern "C" fn(EndpointId, *mut NfTcpConnInfo), + tcpClosed: unsafe extern "C" fn(EndpointId, *mut NfTcpConnInfo), + tcpReceive: unsafe extern "C" fn(EndpointId, *const u8, i32), + tcpSend: unsafe extern "C" fn(EndpointId, *const u8, i32), + tcpCanReceive: unsafe extern "C" fn(EndpointId), + tcpCanSend: unsafe extern "C" fn(EndpointId), + udpCreated: unsafe extern "C" fn(EndpointId, *mut NfUdpConnInfo), + udpConnectRequest: unsafe extern "C" fn(EndpointId, *mut NfUdpConnRequest), + udpClosed: unsafe extern "C" fn(EndpointId, *mut NfUdpConnInfo), + udpReceive: unsafe extern "C" fn(EndpointId, *const u8, *const u8, i32, *mut NfUdpOptions), + udpSend: unsafe extern "C" fn(EndpointId, *const u8, *const u8, i32, *mut NfUdpOptions), + udpCanReceive: unsafe extern "C" fn(EndpointId), + udpCanSend: unsafe extern "C" fn(EndpointId), +} + +unsafe extern "C" fn threadStart() { + trace!("threadStart tid={:?}", thread::current().id()); +} + +unsafe extern "C" fn threadEnd() { + trace!("threadEnd tid={:?}", thread::current().id()); +} + +unsafe extern "C" fn tcpConnectRequest(id: EndpointId, conn_info: *mut NfTcpConnInfo) { + let Ok(local_addr) = NfTcpConnInfo::get_local_address(conn_info) else { + debug!("unable to get local address"); + return; + }; + let Ok(remote_addr) = NfTcpConnInfo::get_remote_address(conn_info) else { + debug!("unable to get remote address"); + return; + }; + + trace!( + "tcpConnectRequest id={} local={} remote={}", + id, + &local_addr, + &remote_addr + ); + + if remote_addr.is_ipv6() { + // Block IPv6. + addr_of_mut!((*conn_info).filteringFlag).write_unaligned(NfFilteringFlag::NfBlock.value()); + return; + } + + if remote_addr.ip().is_loopback() { + return; + } + + // TODO Remove timeout items. + if TCP_INFO + .lock() + .unwrap() + .insert(local_addr.port(), ConnInfo { remote_addr }) + .is_some() + { + warn!("duplicated local_addr.port={}", local_addr.port()); + } + + let tag = "nf"; + let network = crate::session::Network::Tcp; + let Some(new_remote_addr) = crate::app::inbound::get_network_listen_addr(tag, network) else { + debug!("cannot get listen address, tag={} network={}", tag, network); + return; + }; + + match new_remote_addr { + SocketAddr::V4(addr) => { + let new_remote_addr: SOCKADDR_IN = addr.into(); + let addr_ptr = &new_remote_addr as *const SOCKADDR_IN as *const u8; + let addr_len = std::mem::size_of::(); + let new_remote_addr_data = std::slice::from_raw_parts(addr_ptr, addr_len); + let mut write_buf = [0u8; 28]; + write_buf[..addr_len].copy_from_slice(&new_remote_addr_data[..addr_len]); + addr_of_mut!((*conn_info).remoteAddress).write_unaligned(write_buf); + } + SocketAddr::V6(addr) => { + let new_remote_addr: SOCKADDR_IN6 = addr.into(); + let addr_ptr = &new_remote_addr as *const SOCKADDR_IN6 as *const u8; + let addr_len = std::mem::size_of::(); + let new_remote_addr_data = std::slice::from_raw_parts(addr_ptr, addr_len); + let mut write_buf = [0u8; 28]; + write_buf[..addr_len].copy_from_slice(&new_remote_addr_data[..addr_len]); + addr_of_mut!((*conn_info).remoteAddress).write_unaligned(write_buf); + } + } + + NF_TCP_DISABLE_FILTERING.unwrap()(id); +} + +unsafe extern "C" fn tcpConnected(id: EndpointId, _conn_info: *mut NfTcpConnInfo) { + trace!("tcpConnected id={}", id); +} + +unsafe extern "C" fn tcpClosed(id: EndpointId, _conn_info: *mut NfTcpConnInfo) { + trace!("tcpClosed id={}", id); +} + +unsafe extern "C" fn tcpReceive(id: EndpointId, buf: *const u8, len: i32) { + trace!( + "tcpReceive tid={:?} id={} len={}", + thread::current().id(), + id, + len + ); + NF_TCP_POST_RECEIVE.unwrap()(id, buf, len); +} + +unsafe extern "C" fn tcpSend(id: EndpointId, _buf: *const u8, len: i32) { + trace!( + "tcpSend tid={:?} id={} len={}", + thread::current().id(), + id, + len + ); +} + +unsafe extern "C" fn tcpCanReceive(id: EndpointId) { + trace!("tcpCanReceive id={}", id); +} + +unsafe extern "C" fn tcpCanSend(id: EndpointId) { + trace!("tcpCanSend id={}", id); +} + +unsafe extern "C" fn udpCreated(id: EndpointId, conn_info: *mut NfUdpConnInfo) { + let Ok(local_address) = NfUdpConnInfo::get_local_address(conn_info) else { + debug!("unable to get local address"); + return; + }; + trace!("udpCreated id={} local={}", id, &local_address); + // The local address here can be 0.0.0.0:0, we will check and override in udpSend. + UDP_LOCAL_INFO + .lock() + .unwrap() + .insert(id, UdpLocalInfo { local_address }); + UDP_ENDPOINT.lock().unwrap().insert(local_address, id); +} + +unsafe extern "C" fn udpConnectRequest(id: EndpointId, _conn_req: *mut NfUdpConnRequest) { + trace!("udpConnectRequest id={}", id); +} + +unsafe extern "C" fn udpClosed(id: EndpointId, _conn_info: *mut NfUdpConnInfo) { + UDP_OPTIONS.lock().unwrap().remove(&id); + if let Some(info) = UDP_LOCAL_INFO.lock().unwrap().remove(&id) { + UDP_ENDPOINT.lock().unwrap().remove(&info.local_address); + } +} + +unsafe extern "C" fn udpReceive( + id: EndpointId, + remote_address: *const u8, + buf: *const u8, + len: i32, + options: *mut NfUdpOptions, +) { + trace!("udpReceive id={}", id); + NF_UDP_POST_RECEIVE.unwrap()(id, remote_address, buf, len, options); +} + +unsafe extern "C" fn udpSend( + id: EndpointId, + remote_address: *const u8, + buf: *const u8, + len: i32, + options: *mut NfUdpOptions, +) { + let Ok(remote_addr) = + sockaddr_to_socketaddr(transmute::<*const u8, *const SOCKADDR>(remote_address)) + else { + debug!("unable to get remote address"); + return; + }; + + trace!("udpSend id={} remote={} len={}", id, &remote_addr, len); + + // Drop IPv6 + if remote_addr.is_ipv6() { + trace!("Pass IPv6"); + let status = NF_UDP_POST_SEND.unwrap()(id, remote_address, buf, len, options); + if status != NF_STATUS_SUCCESS { + debug!("send to local failed, status={}", status); + } + return; + } + + if remote_addr.ip().is_loopback() { + NF_UDP_DISABLE_FILTERING.unwrap()(id); + return; + } + + let mut conn_info = NfUdpConnInfo::default(); + let status = NF_GET_UDP_CONN_INFO.unwrap()(id, &mut conn_info as *mut _); + if status != NF_STATUS_SUCCESS { + debug!("get udp conn info failed id={} status={}", id, status); + return; + } + let Ok(local_address) = NfUdpConnInfo::get_local_address(&conn_info as *const NfUdpConnInfo) + else { + debug!("unable to get local address"); + return; + }; + + UDP_LOCAL_INFO.lock().unwrap().entry(id).and_modify(|x| { + if x.local_address.port() == 0 { + x.local_address = local_address; + UDP_ENDPOINT.lock().unwrap().insert(local_address, id); + } + }); + + UDP_OPTIONS.lock().unwrap().entry(id).or_insert_with(|| { + let opts_len = (*options).optionsLength; + let opts_data_len = std::mem::size_of::() - 1 + opts_len as usize; + let mut opts_buf = vec![0u8; opts_data_len]; + let options_data = std::slice::from_raw_parts(options as *mut u8, opts_data_len); + opts_buf[..opts_data_len] + .as_mut() + .copy_from_slice(&options_data[..opts_data_len]); + opts_buf + }); + + let Ok(original_remote_addr) = + sockaddr_to_socketaddr(transmute::<*const u8, *const SOCKADDR>(remote_address)) + else { + debug!("unable to get original remote address"); + return; + }; + + let mut new_buf = BytesMut::new(); + let dst_addr = crate::session::SocksAddr::from(original_remote_addr); + dst_addr.write_buf(&mut new_buf, crate::session::SocksAddrWireType::PortLast); + new_buf.put_u64(id); + let buf = std::slice::from_raw_parts(buf, len as _); + new_buf.put_slice(buf); + + // FIXME retrieve from inbound settings + let tag = "nf"; + let network = crate::session::Network::Udp; + let Some(new_remote_addr) = crate::app::inbound::get_network_listen_addr(tag, network) else { + debug!("cannot get listen address tag={} network={}", tag, network); + return; + }; + + if let Err(e) = UDP_SEND_SOCKET + .read() + .as_ref() + .unwrap() + .send_to(&new_buf, new_remote_addr) + { + debug!("send to local failed: {}", e); + } +} + +unsafe extern "C" fn udpCanReceive(id: EndpointId) { + trace!("udpCanReceive id={}", id); +} + +unsafe extern "C" fn udpCanSend(id: EndpointId) { + trace!("udpCanSend id={}", id); +} + +pub mod packed { + pub type ADDRESS_FAMILY = u16; + + pub const AF_INET: ADDRESS_FAMILY = 2u16; + pub const AF_INET6: ADDRESS_FAMILY = 23u16; + + #[repr(C, packed)] + #[derive(Clone, Copy)] + pub struct SOCKADDR { + pub sa_family: ADDRESS_FAMILY, + pub sa_data: [i8; 14], + } + + #[repr(C, packed)] + #[derive(Clone, Copy)] + pub struct IN_ADDR_0_0 { + pub s_b1: u8, + pub s_b2: u8, + pub s_b3: u8, + pub s_b4: u8, + } + + #[repr(C, packed)] + #[derive(Clone, Copy)] + pub struct IN_ADDR_0_1 { + pub s_w1: u16, + pub s_w2: u16, + } + + #[repr(C, packed)] + #[derive(Clone, Copy)] + pub union IN_ADDR_0 { + pub S_un_b: IN_ADDR_0_0, + pub S_un_w: IN_ADDR_0_1, + pub S_addr: u32, + } + + #[repr(C, packed)] + #[derive(Clone, Copy)] + pub struct IN_ADDR { + pub S_un: IN_ADDR_0, + } + + #[repr(C, packed)] + #[derive(Clone, Copy)] + pub struct SOCKADDR_IN { + pub sin_family: ADDRESS_FAMILY, + pub sin_port: u16, + pub sin_addr: IN_ADDR, + pub sin_zero: [i8; 8], + } + + impl Default for SOCKADDR_IN { + fn default() -> Self { + unsafe { core::mem::zeroed() } + } + } + + #[repr(C, packed)] + #[derive(Clone, Copy)] + pub union IN6_ADDR_0 { + pub Byte: [u8; 16], + pub Word: [u16; 8], + } + + #[repr(C, packed)] + #[derive(Clone, Copy)] + pub struct SCOPE_ID_0_0 { + pub _bitfield: u32, + } + + #[repr(C, packed)] + #[derive(Clone, Copy)] + pub union SCOPE_ID_0 { + pub Anonymous: SCOPE_ID_0_0, + pub Value: u32, + } + + #[repr(C, packed)] + #[derive(Clone, Copy)] + pub struct SCOPE_ID { + pub Anonymous: SCOPE_ID_0, + } + + #[repr(C, packed)] + #[derive(Clone, Copy)] + pub union SOCKADDR_IN6_0 { + pub sin6_scope_id: u32, + pub sin6_scope_struct: SCOPE_ID, + } + + #[repr(C, packed)] + #[derive(Clone, Copy)] + pub struct IN6_ADDR { + pub u: IN6_ADDR_0, + } + + #[repr(C, packed)] + #[derive(Clone, Copy)] + pub struct SOCKADDR_IN6 { + pub sin6_family: ADDRESS_FAMILY, + pub sin6_port: u16, + pub sin6_flowinfo: u32, + pub sin6_addr: IN6_ADDR, + pub Anonymous: SOCKADDR_IN6_0, + } + + impl Default for SOCKADDR_IN6 { + fn default() -> Self { + unsafe { core::mem::zeroed() } + } + } + + impl From for SOCKADDR_IN { + fn from(addr: std::net::SocketAddrV4) -> Self { + // addr.port() is in host byte order + // sin_port must be big-endian, network byte order + SOCKADDR_IN { + sin_family: AF_INET, + sin_port: addr.port().to_be(), + sin_addr: (*addr.ip()).into(), + ..Default::default() + } + } + } + + impl From for SOCKADDR_IN6 { + fn from(addr: std::net::SocketAddrV6) -> Self { + // addr.port() and addr.flowinfo() are in host byte order + // sin6_port and sin6_flowinfo must be big-endian, network byte order + // sin6_scope_id is a bitfield without endianness + SOCKADDR_IN6 { + sin6_family: AF_INET6, + sin6_port: addr.port().to_be(), + sin6_flowinfo: addr.flowinfo().to_be(), + sin6_addr: (*addr.ip()).into(), + Anonymous: SOCKADDR_IN6_0 { + sin6_scope_id: addr.scope_id(), + }, + } + } + } + + impl From for std::net::Ipv4Addr { + fn from(in_addr: IN_ADDR) -> Self { + // SAFETY: this is safe because the union variants are just views of the same exact data + // in_addr.S_un.S_addr is big-endian, network byte order + // Ipv4Addr::new() expects the parameter in host byte order + Self::from(u32::from_be(unsafe { in_addr.S_un.S_addr })) + } + } + + impl From for IN_ADDR { + fn from(addr: std::net::Ipv4Addr) -> Self { + // u32::from(addr) is in host byte order + // S_addr must be big-endian, network byte order + Self { + S_un: IN_ADDR_0 { + S_addr: u32::from(addr).to_be(), + }, + } + } + } + + impl From for std::net::Ipv6Addr { + fn from(in6_addr: IN6_ADDR) -> Self { + // SAFETY: this is safe because the union variants are just views of the same exact data + Self::from(unsafe { in6_addr.u.Byte }) + } + } + + impl From for IN6_ADDR { + fn from(addr: std::net::Ipv6Addr) -> Self { + Self { + u: IN6_ADDR_0 { + Byte: addr.octets(), + }, + } + } + } +} + +unsafe fn sockaddr_to_socketaddr(addr: *const packed::SOCKADDR) -> Result { + match addr_of!((*addr).sa_family).read_unaligned() { + packed::AF_INET => { + let addr: *const packed::SOCKADDR_IN = transmute(addr); + Ok(SocketAddr::new( + IpAddr::V4(addr_of!((*addr).sin_addr).read_unaligned().into()), + u16::from_be(addr_of!((*addr).sin_port).read_unaligned()), + )) + } + packed::AF_INET6 => { + let addr: *const packed::SOCKADDR_IN6 = transmute(addr); + Ok(SocketAddr::new( + IpAddr::V6(addr_of!((*addr).sin6_addr).read_unaligned().into()), + u16::from_be(addr_of!((*addr).sin6_port).read_unaligned()), + )) + } + _ => Err(anyhow!("unknown address family")), + } +} + +#[allow(clippy::missing_transmute_annotations)] +unsafe fn init_nf_fns>(nfapi: P) -> Result<()> { + let nfapi = libloading::Library::new(nfapi)?; + + NF_INIT = Some(transmute( + nfapi + .get::>(b"nf_init\0")? + .into_raw(), + )); + + let nf_free: libloading::Symbol = nfapi.get(b"nf_free\0")?; + NF_FREE = Some(transmute(nf_free.into_raw())); + + let nf_add_rule: libloading::Symbol = nfapi.get(b"nf_addRule\0")?; + NF_ADD_RULE = Some(transmute(nf_add_rule.into_raw())); + + let nf_tcp_post_receive: libloading::Symbol = + nfapi.get(b"nf_tcpPostReceive\0")?; + NF_TCP_POST_RECEIVE = Some(transmute(nf_tcp_post_receive.into_raw())); + + let nf_tcp_post_send: libloading::Symbol = nfapi.get(b"nf_tcpPostSend\0")?; + NF_TCP_POST_SEND = Some(transmute(nf_tcp_post_send.into_raw())); + + let nf_udp_post_receive: libloading::Symbol = + nfapi.get(b"nf_udpPostReceive\0")?; + NF_UDP_POST_RECEIVE = Some(transmute(nf_udp_post_receive.into_raw())); + + let nf_udp_post_send: libloading::Symbol = nfapi.get(b"nf_udpPostSend\0")?; + NF_UDP_POST_SEND = Some(transmute(nf_udp_post_send.into_raw())); + + NF_TCP_DISABLE_FILTERING = Some(std::mem::transmute( + nfapi + .get::>(b"nf_tcpDisableFiltering\0")? + .into_raw(), + )); + + NF_UDP_DISABLE_FILTERING = Some(std::mem::transmute( + nfapi + .get::>(b"nf_udpDisableFiltering\0")? + .into_raw(), + )); + + let nf_adjust_process_priviledges: libloading::Symbol = + nfapi.get(b"nf_adjustProcessPriviledges\0")?; + NF_ADJUST_PROCESS_PRIVILEDGES = Some(transmute(nf_adjust_process_priviledges.into_raw())); + + NF_GET_UDP_CONN_INFO = Some(transmute( + nfapi + .get::>(b"nf_getUDPConnInfo\0")? + .into_raw(), + )); + + *NFAPI.write() = Some(nfapi); + + Ok(()) +} + +unsafe fn init_nf>( + driver_name: String, + nfapi: P, + res_tx: std::sync::mpsc::Sender, +) -> Result<()> { + init_nf_fns(nfapi)?; + + NF_ADJUST_PROCESS_PRIVILEDGES.unwrap()(); + + let eh = NfEventHandler { + threadStart, + threadEnd, + tcpConnectRequest, + tcpConnected, + tcpClosed, + tcpReceive, + tcpSend, + tcpCanReceive, + tcpCanSend, + udpCreated, + udpConnectRequest, + udpClosed, + udpReceive, + udpSend, + udpCanReceive, + udpCanSend, + }; + + let status = NF_INIT.unwrap()( + CString::new(driver_name) + .unwrap() + .as_bytes_with_nul() + .as_ptr(), + &eh as *const _, + ); + if status != NF_STATUS_SUCCESS { + return Err(anyhow!("nf_init failed, status={}", status)); + } + + // Required for the `tcpConnectRequest` handler to be called. + let rule = NfRule { + protocol: IPPROTO_TCP, + direction: NfDirection::Out.value(), + filteringFlag: NfFilteringFlag::NfIndicateConnectRequests.value(), + ..Default::default() + }; + let status = NF_ADD_RULE.unwrap()(&rule as *const _, 0); + if status != NF_STATUS_SUCCESS { + return Err(anyhow!("adding rule failed: {}", status)); + } + + let rule = NfRule { + filteringFlag: NfFilteringFlag::NfFilter.value(), + ..Default::default() + }; + let status = NF_ADD_RULE.unwrap()(&rule as *const _, 0); + if status != NF_STATUS_SUCCESS { + return Err(anyhow!("adding rule failed: {}", status)); + } + + *UDP_SEND_SOCKET.write() = Some(std::net::UdpSocket::bind("0.0.0.0:0")?); + + let (tx, rx) = std::sync::mpsc::channel(); + TX = Some(tx); + + if let Err(e) = res_tx.send(true) { + debug!("unable to send nf init result: {}", e); + } + + let _ = rx.recv(); + + Ok(()) +} + +fn init_if_needed>(driver_name: String, nfapi: P) -> Result<()> { + let nfapi = nfapi.as_ref().to_string_lossy().to_string(); + let (res_tx, res_rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + unsafe { + if let Err(e) = init_nf(driver_name, nfapi, res_tx.clone()) { + debug!("initialize nf failed: {}", e); + let _ = res_tx.send(false); + } + }; + }); + if let Ok(res) = res_rx.recv() { + if res { + return Ok(()); + } + } + Err(anyhow!("initialize nf failed")) +} + +static IS_NF_INITIALIZED: AtomicBool = AtomicBool::new(false); + +// TODO Guard initializing. +pub fn init>(driver_name: String, nfapi: P) -> Result<()> { + if !IS_NF_INITIALIZED.load(Ordering::Relaxed) { + init_if_needed(driver_name, nfapi)?; + IS_NF_INITIALIZED.store(true, Ordering::Relaxed); + } + Ok(()) +} + +unsafe fn uninit_nf() { + if IS_NF_INITIALIZED.load(Ordering::Relaxed) { + NF_FREE.unwrap()(); + if let Some(nfapi) = NFAPI.write().take() { + if let Err(e) = nfapi.close() { + debug!("close nf failed: {}", e); + } + } + IS_NF_INITIALIZED.store(false, Ordering::Relaxed); + } +} + +pub fn uninit() { + unsafe { uninit_nf() }; +} diff --git a/leaf/src/proxy/nf/inbound/stream.rs b/leaf/src/proxy/nf/inbound/stream.rs new file mode 100644 index 0000000..4d598eb --- /dev/null +++ b/leaf/src/proxy/nf/inbound/stream.rs @@ -0,0 +1,45 @@ +use async_trait::async_trait; + +use crate::app::fake_dns::FakeDns; +use crate::{proxy::*, session::Session}; + +pub struct Handler { + pub fake_dns: Arc, +} + +#[async_trait] +impl InboundStreamHandler for Handler { + async fn handle<'a>( + &'a self, + mut sess: Session, + stream: AnyStream, + ) -> std::io::Result { + let remote_addr = + if let Some(info) = super::TCP_INFO.lock().unwrap().remove(&sess.source.port()) { + info.remote_addr + } else { + return Err(std::io::Error::other(format!( + "tcp conn not found, source={} ", + &sess.source + ))); + }; + + sess.destination = crate::session::SocksAddr::from(remote_addr); + + let remote_ip = remote_addr.ip(); + if self.fake_dns.is_fake_ip(&remote_ip).await { + if let Some(domain) = self.fake_dns.query_domain(&remote_ip).await { + sess.destination = SocksAddr::Domain(domain, remote_addr.port()); + } else { + if remote_addr.port() != 443 && remote_addr.port() != 80 { + return Err(std::io::Error::other(format!( + "paired domain not found, addr={}", + &remote_addr.ip() + ))); + } + } + } + + Ok(InboundTransport::Stream(stream, sess)) + } +} diff --git a/leaf/src/proxy/nf/mod.rs b/leaf/src/proxy/nf/mod.rs new file mode 100644 index 0000000..f4a67a0 --- /dev/null +++ b/leaf/src/proxy/nf/mod.rs @@ -0,0 +1,2 @@ +#[cfg(feature = "inbound-nf")] +pub mod inbound; diff --git a/leaf/src/proxy/tun/inbound.rs b/leaf/src/proxy/tun/inbound.rs index dd5dcc0..d0ea5bb 100644 --- a/leaf/src/proxy/tun/inbound.rs +++ b/leaf/src/proxy/tun/inbound.rs @@ -7,7 +7,7 @@ use futures::{sink::SinkExt, stream::StreamExt}; use protobuf::Message; use tokio::sync::mpsc::channel as tokio_channel; use tokio::sync::mpsc::{Receiver as TokioReceiver, Sender as TokioSender}; -use tracing::{debug, error, info, trace, warn}; +use tracing::{debug, error, info, warn}; use crate::{ app::dispatcher::Dispatcher, @@ -48,7 +48,7 @@ async fn handle_inbound_stream( // likely caused by poisoned DNS cache records, we // still have a chance to sniff the request domain // for TLS traffic in dispatcher. - if remote_addr.port() != 443 { + if remote_addr.port() != 443 && remote_addr.port() != 80 { debug!( "No paired domain found for this fake IP: {}, connection is rejected.", &remote_addr.ip() @@ -116,7 +116,7 @@ async fn handle_inbound_datagram( continue; } Err(err) => { - trace!("generate fake ip failed: {}", err); + debug!("generate fake ip failed: {}", err); } } } @@ -206,6 +206,7 @@ pub fn new( } else { (FakeDnsMode::Exclude, fake_dns_exclude) }; + let fakedns = Arc::new(FakeDns::new(fake_dns_mode, fake_dns_filters)); let tun = tun::create_as_async(&cfg).map_err(|e| anyhow!("create tun failed: {}", e))?; @@ -219,11 +220,6 @@ pub fn new( )?; Ok(Box::pin(async move { - let fakedns = Arc::new(FakeDns::new(fake_dns_mode)); - for filter in fake_dns_filters.into_iter() { - fakedns.add_filter(filter).await; - } - let inbound_tag = inbound.tag.clone(); let framed = tun.into_framed(); let (mut tun_sink, mut tun_stream) = framed.split();