From 033213d8a57d7f09da56be404f8d692f6566c07c Mon Sep 17 00:00:00 2001 From: eric Date: Sun, 12 Oct 2025 13:43:57 +0800 Subject: [PATCH] Support PROCESS-NAME rule --- leaf/Cargo.toml | 5 +- leaf/src/app/dispatcher.rs | 47 ++++++++++--- leaf/src/app/nat_manager.rs | 26 ++++--- leaf/src/app/router.rs | 42 +++++++++++ leaf/src/config/conf/config.rs | 6 +- leaf/src/config/internal/config.proto | 1 + leaf/src/config/internal/config.rs | 13 ++++ leaf/src/config/json/config.rs | 8 +++ leaf/src/proxy/nf/inbound/datagram.rs | 7 +- leaf/src/proxy/nf/inbound/mod.rs | 93 +++++++++++++++++++++++-- leaf/src/proxy/nf/inbound/stream.rs | 5 +- leaf/src/proxy/trojan/inbound/stream.rs | 2 +- leaf/src/session.rs | 25 ++++++- 13 files changed, 244 insertions(+), 36 deletions(-) diff --git a/leaf/Cargo.toml b/leaf/Cargo.toml index ef36db1..bef3b41 100644 --- a/leaf/Cargo.toml +++ b/leaf/Cargo.toml @@ -95,6 +95,9 @@ openssl-tls = ["openssl", "tokio-openssl", "openssl-probe"] config-conf = ["regex"] config-json = ["serde", "serde_derive", "serde_json"] +# Router rules +rule-process-name = ["regex"] + # Outbounds outbound-direct = [] outbound-drop = [] @@ -164,6 +167,7 @@ colored = "2.1" maxminddb = { version = "0.24", features = ["mmap"] } memmap2 = "0.9" cidr = "0.2" +regex = { version = "1.10", optional = true } # outbound-select directories = { version = "4.0", optional = true } @@ -178,7 +182,6 @@ serde_derive = { version = "1.0", optional = true } serde = { version = "1.0", optional = true } # config-conf -regex = { version = "1.10", optional = true } openssl = { version = "0.10", features = ["vendored"], optional = true } diff --git a/leaf/src/app/dispatcher.rs b/leaf/src/app/dispatcher.rs index 8c018b7..8f50d59 100644 --- a/leaf/src/app/dispatcher.rs +++ b/leaf/src/app/dispatcher.rs @@ -1,5 +1,6 @@ use std::convert::TryFrom; use std::io::{self, ErrorKind}; +use std::path::Path; use std::sync::Arc; use std::time::Duration; @@ -43,15 +44,43 @@ fn log_request( } else { (sess.network.to_string(), outbound_tag.to_string()) }; - info!( - "[{}] [{}] [{}] [{}] [{}] [{}]", - sess.forwarded_source.unwrap_or_else(|| sess.source.ip()), - network, - &sess.inbound_tag, - outbound_tag, - hs, - &sess.destination, - ); + + #[cfg(feature = "rule-process-name")] + { + let process_name = sess + .process_name + .as_ref() + .map(|x| { + Path::new(x) + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or(x) + }) + .unwrap_or(""); + info!( + "[{}] [{}] [{}] [{}] [{}] [{}] [{}]", + process_name, + sess.forwarded_source.unwrap_or_else(|| sess.source.ip()), + network, + &sess.inbound_tag, + outbound_tag, + hs, + &sess.destination, + ); + } + + #[cfg(not(feature = "rule-process-name"))] + { + info!( + "[{}] [{}] [{}] [{}] [{}] [{}]", + sess.forwarded_source.unwrap_or_else(|| sess.source.ip()), + network, + &sess.inbound_tag, + outbound_tag, + hs, + &sess.destination, + ); + } } pub struct Dispatcher { diff --git a/leaf/src/app/nat_manager.rs b/leaf/src/app/nat_manager.rs index 27f4192..a5bdabf 100644 --- a/leaf/src/app/nat_manager.rs +++ b/leaf/src/app/nat_manager.rs @@ -133,13 +133,14 @@ impl NatManager { source: dgram_src.address, destination: pkt.dst_addr.clone(), inbound_tag: inbound_tag.to_string(), + process_name: dgram_src.process_name.clone(), ..Default::default() }); if sess.inbound_tag.is_empty() { sess.inbound_tag = inbound_tag.to_string(); } - self.add_session(sess, *dgram_src, client_ch_tx.clone(), &mut guard) + self.add_session(sess, dgram_src.clone(), client_ch_tx.clone(), &mut guard) .await; debug!( @@ -170,7 +171,7 @@ impl NatManager { mpsc::channel(*crate::option::UDP_UPLINK_CHANNEL_SIZE); let (downlink_abort_tx, downlink_abort_rx) = oneshot::channel(); - guard.insert(raddr, (target_ch_tx, downlink_abort_tx, Instant::now())); + guard.insert(raddr.clone(), (target_ch_tx, downlink_abort_tx, Instant::now())); let dispatcher = self.dispatcher.clone(); let sessions = self.sessions.clone(); @@ -178,13 +179,14 @@ impl NatManager { // Spawns a new task for dispatching to avoid blocking the current task, // because we have stream type transports for UDP traffic, establishing a // TCP stream would block the task. + let raddr_cloned = raddr.clone(); tokio::spawn(async move { // new socket to communicate with the target. let socket = match dispatcher.dispatch_datagram(sess).await { Ok(s) => s, Err(e) => { - debug!("dispatch {} failed: {}", &raddr, e); - sessions.lock().await.remove(&raddr); + debug!("dispatch {} failed: {}", &raddr_cloned, e); + sessions.lock().await.remove(&raddr_cloned); return; } }; @@ -192,6 +194,7 @@ impl NatManager { let (mut target_sock_recv, mut target_sock_send) = socket.split(); // downlink + let raddr_downlink = raddr_cloned.clone(); let downlink_task = async move { let mut buf = vec![0u8; *crate::option::DATAGRAM_BUFFER_SIZE * 1024]; loop { @@ -199,7 +202,7 @@ impl NatManager { Err(err) => { debug!( "Failed to receive downlink packets on session {}: {}", - &raddr, err + &raddr_downlink, err ); break; } @@ -208,12 +211,12 @@ impl NatManager { let pkt = UdpPacket::new( buf[..n].to_vec(), addr.clone(), - SocksAddr::from(raddr.address), + SocksAddr::from(raddr_downlink.address), ); if let Err(err) = client_ch_tx.send(pkt).await { debug!( "Failed to send downlink packets on session {} to {}: {}", - &raddr, &addr, err + &raddr_downlink, &addr, err ); break; } @@ -221,7 +224,7 @@ impl NatManager { // activity update { let mut sessions = sessions.lock().await; - if let Some(sess) = sessions.get_mut(&raddr) { + if let Some(sess) = sessions.get_mut(&raddr_downlink) { if addr.port() == 53 { // If the destination port is 53, we assume it's a // DNS query and set a negative timeout so it will @@ -237,7 +240,7 @@ impl NatManager { } } } - sessions.lock().await.remove(&raddr); + sessions.lock().await.remove(&raddr_downlink); }; let (downlink_task, downlink_task_handle) = abortable(downlink_task); @@ -250,6 +253,7 @@ impl NatManager { }); // uplink + let raddr_uplink = raddr_cloned.clone(); tokio::spawn(async move { while let Some(pkt) = target_ch_rx.recv().await { trace!( @@ -260,13 +264,13 @@ impl NatManager { if let Err(e) = target_sock_send.send_to(&pkt.data, &pkt.dst_addr).await { debug!( "Failed to send uplink packets on session {} to {}: {:?}", - &raddr, &pkt.dst_addr, e + &raddr_uplink, &pkt.dst_addr, e ); break; } } if let Err(e) = target_sock_send.close().await { - debug!("Failed to close outbound datagram {}: {}", &raddr, e); + debug!("Failed to close outbound datagram {}: {}", &raddr_uplink, e); } }); }); diff --git a/leaf/src/app/router.rs b/leaf/src/app/router.rs index f0a0abb..377d368 100644 --- a/leaf/src/app/router.rs +++ b/leaf/src/app/router.rs @@ -7,6 +7,8 @@ use cidr::IpCidr; use futures::TryFutureExt; use maxminddb::geoip2::Country; use maxminddb::Mmap; +#[cfg(feature = "rule-process-name")] +use regex::Regex; use tracing::{debug, warn}; use crate::app::SyncDnsClient; @@ -354,6 +356,41 @@ impl Condition for DomainMatcher { } } +#[cfg(feature = "rule-process-name")] +pub struct ProcessNameMatcher { + regexes: Vec, +} + +#[cfg(feature = "rule-process-name")] +impl ProcessNameMatcher { + pub fn new(patterns: Vec) -> Self { + let mut regexes = Vec::new(); + for pattern in patterns { + if let Ok(regex) = Regex::new(&pattern) { + regexes.push(regex); + } else { + warn!("Invalid regex pattern: {}", pattern); + } + } + Self { regexes } + } +} + +#[cfg(feature = "rule-process-name")] +impl Condition for ProcessNameMatcher { + fn apply(&self, sess: &Session) -> bool { + if let Some(process_name) = sess.process_name.as_ref() { + for regex in &self.regexes { + if regex.is_match(process_name) { + debug!("Matched process_name={} with regex", process_name); + return true; + } + } + } + false + } +} + struct ConditionAnd { conditions: Vec>, } @@ -467,6 +504,11 @@ impl Router { cond_and.add(Box::new(InboundTagMatcher::new(&mut rr.inbound_tags))); } + #[cfg(feature = "rule-process-name")] + if !rr.process_names.is_empty() { + cond_and.add(Box::new(ProcessNameMatcher::new(rr.process_names.clone()))); + } + if cond_and.is_empty() { warn!("empty rule at target {}", rr.target_tag); continue; diff --git a/leaf/src/config/conf/config.rs b/leaf/src/config/conf/config.rs index 60f4847..7814bc6 100644 --- a/leaf/src/config/conf/config.rs +++ b/leaf/src/config/conf/config.rs @@ -724,7 +724,7 @@ pub fn from_lines(lines: Vec>) -> Result { match rule.type_field.as_str() { "IP-CIDR" | "DOMAIN" | "DOMAIN-SUFFIX" | "DOMAIN-KEYWORD" | "GEOIP" | "EXTERNAL" - | "PORT-RANGE" | "NETWORK" | "INBOUND-TAG" => { + | "PORT-RANGE" | "NETWORK" | "INBOUND-TAG" | "PROCESS-NAME" => { rule.filter = Some(params[1].to_string()); } _ => {} @@ -1493,6 +1493,10 @@ pub fn to_internal(conf: &mut Config) -> Result { "INBOUND-TAG" => { rule.inbound_tags.push(ext_filter); } + #[cfg(feature = "rule-process-name")] + "PROCESS-NAME" => { + rule.process_names.push(ext_filter); + } _ => {} } rules.push(rule); diff --git a/leaf/src/config/internal/config.proto b/leaf/src/config/internal/config.proto index 5fe53a3..9ae9c93 100644 --- a/leaf/src/config/internal/config.proto +++ b/leaf/src/config/internal/config.proto @@ -264,6 +264,7 @@ message Router { repeated string port_ranges = 5; repeated string networks = 6; repeated string inbound_tags = 7; + repeated string process_names = 8; } repeated Rule rules = 1; diff --git a/leaf/src/config/internal/config.rs b/leaf/src/config/internal/config.rs index 55b0280..b5c1348 100644 --- a/leaf/src/config/internal/config.rs +++ b/leaf/src/config/internal/config.rs @@ -4053,6 +4053,8 @@ pub mod router { pub networks: ::std::vec::Vec<::std::string::String>, // @@protoc_insertion_point(field:Router.Rule.inbound_tags) pub inbound_tags: ::std::vec::Vec<::std::string::String>, + // @@protoc_insertion_point(field:Router.Rule.process_names) + pub process_names: ::std::vec::Vec<::std::string::String>, // special fields // @@protoc_insertion_point(special_field:Router.Rule.special_fields) pub special_fields: ::protobuf::SpecialFields, @@ -4101,6 +4103,9 @@ pub mod router { 58 => { self.inbound_tags.push(is.read_string()?); }, + 66 => { + self.process_names.push(is.read_string()?); + }, tag => { ::protobuf::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, @@ -4136,6 +4141,9 @@ pub mod router { for value in &self.inbound_tags { my_size += ::protobuf::rt::string_size(7, &value); }; + for value in &self.process_names { + my_size += ::protobuf::rt::string_size(8, &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 @@ -4163,6 +4171,9 @@ pub mod router { for v in &self.inbound_tags { os.write_string(7, &v)?; }; + for v in &self.process_names { + os.write_string(8, &v)?; + }; os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } @@ -4187,6 +4198,7 @@ pub mod router { self.port_ranges.clear(); self.networks.clear(); self.inbound_tags.clear(); + self.process_names.clear(); self.special_fields.clear(); } @@ -4199,6 +4211,7 @@ pub mod router { port_ranges: ::std::vec::Vec::new(), networks: ::std::vec::Vec::new(), inbound_tags: ::std::vec::Vec::new(), + process_names: ::std::vec::Vec::new(), special_fields: ::protobuf::SpecialFields::new(), }; &instance diff --git a/leaf/src/config/json/config.rs b/leaf/src/config/json/config.rs index b2c6217..664a707 100644 --- a/leaf/src/config/json/config.rs +++ b/leaf/src/config/json/config.rs @@ -275,6 +275,8 @@ pub struct Rule { pub network: Option>, #[serde(rename = "inboundTag")] pub inbound_tag: Option>, + #[serde(rename = "processName")] + pub process_name: Option>, pub target: String, } @@ -1076,6 +1078,12 @@ pub fn to_internal(json: &mut Config) -> Result { rule.inbound_tags.push(it); } } + #[cfg(feature = "rule-process-name")] + if let Some(ext_process_names) = ext_rule.process_name.as_mut() { + for process_name in ext_process_names.drain(0..) { + rule.process_names.push(process_name); + } + } rules.push(rule); } } diff --git a/leaf/src/proxy/nf/inbound/datagram.rs b/leaf/src/proxy/nf/inbound/datagram.rs index 5383a78..7e2ae1d 100644 --- a/leaf/src/proxy/nf/inbound/datagram.rs +++ b/leaf/src/proxy/nf/inbound/datagram.rs @@ -78,8 +78,8 @@ impl InboundDatagramRecvHalf for DatagramRecvHalf { 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() + let (local_addr, process_name) = if let Some(info) = super::UDP_LOCAL_INFO.lock().unwrap().get(&id) { + (info.local_address.clone(), info.process_name.clone()) } else { return Err(ProxyError::DatagramWarn(anyhow!(format!( "local socket not found id={}", @@ -87,8 +87,9 @@ impl InboundDatagramRecvHalf for DatagramRecvHalf { )))); }; - // Override with real source address. + // Override with real source address and process name. src_addr.address = local_addr; + src_addr.process_name = process_name; if dst_addr.port() == 53 { match self.1.generate_fake_response(real_payload).await { diff --git a/leaf/src/proxy/nf/inbound/mod.rs b/leaf/src/proxy/nf/inbound/mod.rs index 9227d96..92c71e8 100644 --- a/leaf/src/proxy/nf/inbound/mod.rs +++ b/leaf/src/proxy/nf/inbound/mod.rs @@ -109,6 +109,8 @@ 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; +type NfGetProcessNameFn = unsafe extern "C" fn(u32, *mut u8, u32) -> bool; +type NfGetProcessNameFromKernelFn = unsafe extern "C" fn(u32, *mut u8, u32) -> bool; // FIXME Ensure no concurrent access to these fns from different threads. static NFAPI: RwLock> = RwLock::new(None); @@ -123,17 +125,21 @@ 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 NF_GET_PROCESS_NAME: Option = None; +static mut NF_GET_PROCESS_NAME_FROM_KERNEL: Option = None; static mut TX: Option> = None; static UDP_SEND_SOCKET: RwLock> = RwLock::new(None); struct ConnInfo { remote_addr: SocketAddr, + process_name: Option, } #[derive(Debug)] pub struct UdpLocalInfo { local_address: SocketAddr, + process_name: Option, } pub static UDP_LOCAL_INFO: LazyLock>> = @@ -283,11 +289,33 @@ unsafe extern "C" fn tcpConnectRequest(id: EndpointId, conn_info: *mut NfTcpConn return; } + let process_id = addr_of!((*conn_info).processId).read_unaligned(); + let process_name = if let Ok(name) = get_process_name(process_id) { + Some(name) + } else { + None + }; + + debug!( + "tcpConnectRequest id={} local={} remote={} process_id={} process_name={}", + id, + &local_addr, + &remote_addr, + process_id, + process_name.as_deref().unwrap_or("Unknown") + ); + // TODO Remove timeout items. if TCP_INFO .lock() .unwrap() - .insert(local_addr.port(), ConnInfo { remote_addr }) + .insert( + local_addr.port(), + ConnInfo { + remote_addr, + process_name, + }, + ) .is_some() { warn!("duplicated local_addr.port={}", local_addr.port()); @@ -364,12 +392,30 @@ unsafe extern "C" fn udpCreated(id: EndpointId, conn_info: *mut NfUdpConnInfo) { debug!("unable to get local address"); return; }; - trace!("udpCreated id={} local={}", id, &local_address); + + let process_id = addr_of!((*conn_info).processId).read_unaligned(); + let process_name = if let Ok(name) = get_process_name(process_id) { + Some(name) + } else { + None + }; + + debug!( + "udpCreated id={} local={} process_id={} process_name={}", + id, + &local_address, + process_id, + process_name.as_deref().unwrap_or("Unknown") + ); + // 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_LOCAL_INFO.lock().unwrap().insert( + id, + UdpLocalInfo { + local_address, + process_name, + }, + ); UDP_ENDPOINT.lock().unwrap().insert(local_address, id); } @@ -750,6 +796,18 @@ unsafe fn init_nf_fns>(nfapi: P) -> Result<()> { .into_raw(), )); + let nf_get_process_name: libloading::Symbol = + nfapi.get(b"nf_getProcessNameW\0")?; + NF_GET_PROCESS_NAME = Some(std::mem::transmute(nf_get_process_name.into_raw())); + + NF_GET_PROCESS_NAME_FROM_KERNEL = Some(transmute( + nfapi + .get::>( + b"nf_getProcessNameFromKernel\0", + )? + .into_raw(), + )); + *NFAPI.write() = Some(nfapi); Ok(()) @@ -874,3 +932,26 @@ unsafe fn uninit_nf() { pub fn uninit() { unsafe { uninit_nf() }; } + +/// # Safety +pub unsafe fn get_process_name(pid: u32) -> Result { + let mut process_name_buf = vec![0u16; MAX_PATH]; + let process_name_len = process_name_buf.len() as u32; + if !NF_GET_PROCESS_NAME_FROM_KERNEL.unwrap()( + pid, + process_name_buf.as_mut_ptr() as _, + process_name_len, + ) && !NF_GET_PROCESS_NAME.unwrap()(pid, process_name_buf.as_mut_ptr() as _, process_name_len) + { + return Err(anyhow!("Unable to get process name pid={}", pid)); + } + let process_name: OsString = OsString::from_wide( + process_name_buf + .into_iter() + .take_while(|x| *x != 0) + .collect::>() + .as_slice(), + ); + // Return the full path instead of just the filename + Ok(process_name.to_string_lossy().to_string()) +} diff --git a/leaf/src/proxy/nf/inbound/stream.rs b/leaf/src/proxy/nf/inbound/stream.rs index 4d598eb..c0e6e93 100644 --- a/leaf/src/proxy/nf/inbound/stream.rs +++ b/leaf/src/proxy/nf/inbound/stream.rs @@ -14,9 +14,9 @@ impl InboundStreamHandler for Handler { mut sess: Session, stream: AnyStream, ) -> std::io::Result { - let remote_addr = + let (remote_addr, process_name) = if let Some(info) = super::TCP_INFO.lock().unwrap().remove(&sess.source.port()) { - info.remote_addr + (info.remote_addr, info.process_name) } else { return Err(std::io::Error::other(format!( "tcp conn not found, source={} ", @@ -25,6 +25,7 @@ impl InboundStreamHandler for Handler { }; sess.destination = crate::session::SocksAddr::from(remote_addr); + sess.process_name = process_name; let remote_ip = remote_addr.ip(); if self.fake_dns.is_fake_ip(&remote_ip).await { diff --git a/leaf/src/proxy/trojan/inbound/stream.rs b/leaf/src/proxy/trojan/inbound/stream.rs index 9e7cf1d..7a81d66 100644 --- a/leaf/src/proxy/trojan/inbound/stream.rs +++ b/leaf/src/proxy/trojan/inbound/stream.rs @@ -78,7 +78,7 @@ where payload_len, &dst_addr ); - Ok((payload_len, self.1, dst_addr)) + Ok((payload_len, self.1.clone(), dst_addr)) } } diff --git a/leaf/src/session.rs b/leaf/src/session.rs index 810f4ed..f222a51 100644 --- a/leaf/src/session.rs +++ b/leaf/src/session.rs @@ -25,15 +25,32 @@ impl std::fmt::Display for Network { pub type StreamId = u64; -#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)] +#[derive(PartialEq, Eq, Hash, Clone, Debug)] pub struct DatagramSource { pub address: SocketAddr, pub stream_id: Option, + pub process_name: Option, } impl DatagramSource { pub fn new(address: SocketAddr, stream_id: Option) -> Self { - DatagramSource { address, stream_id } + DatagramSource { + address, + stream_id, + process_name: None, + } + } + + pub fn new_with_process_name( + address: SocketAddr, + stream_id: Option, + process_name: Option, + ) -> Self { + DatagramSource { + address, + stream_id, + process_name, + } } } @@ -64,6 +81,8 @@ pub struct Session { pub stream_id: Option, /// Optional source address which is forwarded via HTTP reverse proxy. pub forwarded_source: Option, + /// Optional process name that initiated this connection. + pub process_name: Option, /// Instructs a multiplexed transport should creates a new underlying /// connection for this session, and it will be used only once. pub new_conn_once: bool, @@ -80,6 +99,7 @@ impl Clone for Session { outbound_tag: self.outbound_tag.clone(), stream_id: self.stream_id, forwarded_source: self.forwarded_source, + process_name: self.process_name.clone(), new_conn_once: self.new_conn_once, } } @@ -96,6 +116,7 @@ impl Default for Session { outbound_tag: "".to_string(), stream_id: None, forwarded_source: None, + process_name: None, new_conn_once: false, } }