Support PROCESS-NAME rule

This commit is contained in:
eric committed 2025-10-12 13:44:36 +08:00
1 parent e588194cc1
commit 033213d8a5
13 files changed
+244 -36

No files matched your search

+4 -1
View File
@@ -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 }
+38 -9
View File
@@ -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 {
+15 -11
View File
@@ -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);
}
});
});
+42
View File
@@ -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<Regex>,
}
#[cfg(feature = "rule-process-name")]
impl ProcessNameMatcher {
pub fn new(patterns: Vec<String>) -> 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<Box<dyn Condition>>,
}
@@ -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;
+5 -1
View File
@@ -724,7 +724,7 @@ pub fn from_lines(lines: Vec<io::Result<String>>) -> Result<Config> {
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<internal::Config> {
"INBOUND-TAG" => {
rule.inbound_tags.push(ext_filter);
}
#[cfg(feature = "rule-process-name")]
"PROCESS-NAME" => {
rule.process_names.push(ext_filter);
}
_ => {}
}
rules.push(rule);
+1
View File
@@ -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;
+13
View File
@@ -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
+8
View File
@@ -275,6 +275,8 @@ pub struct Rule {
pub network: Option<Vec<String>>,
#[serde(rename = "inboundTag")]
pub inbound_tag: Option<Vec<String>>,
#[serde(rename = "processName")]
pub process_name: Option<Vec<String>>,
pub target: String,
}
@@ -1076,6 +1078,12 @@ pub fn to_internal(json: &mut Config) -> Result<internal::Config> {
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);
}
}
+4 -3
View File
@@ -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 {
+87 -6
View File
@@ -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<Option<libloading::Library>> = RwLock::new(None);
@@ -123,17 +125,21 @@ static mut NF_TCP_DISABLE_FILTERING: Option<NfTcpDisableFilteringFn> = None;
static mut NF_UDP_DISABLE_FILTERING: Option<NfUdpDisableFilteringFn> = None;
static mut NF_ADJUST_PROCESS_PRIVILEDGES: Option<NfAdjustProcessPriviledgesFn> = None;
static mut NF_GET_UDP_CONN_INFO: Option<NfGetUdpConnInfoFn> = None;
static mut NF_GET_PROCESS_NAME: Option<NfGetProcessNameFn> = None;
static mut NF_GET_PROCESS_NAME_FROM_KERNEL: Option<NfGetProcessNameFromKernelFn> = None;
static mut TX: Option<std::sync::mpsc::Sender<bool>> = None;
static UDP_SEND_SOCKET: RwLock<Option<std::net::UdpSocket>> = RwLock::new(None);
struct ConnInfo {
remote_addr: SocketAddr,
process_name: Option<String>,
}
#[derive(Debug)]
pub struct UdpLocalInfo {
local_address: SocketAddr,
process_name: Option<String>,
}
pub static UDP_LOCAL_INFO: LazyLock<Mutex<HashMap<EndpointId, UdpLocalInfo>>> =
@@ -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<P: AsRef<OsStr>>(nfapi: P) -> Result<()> {
.into_raw(),
));
let nf_get_process_name: libloading::Symbol<NfGetProcessNameFn> =
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::<libloading::Symbol<NfGetProcessNameFromKernelFn>>(
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<String> {
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::<Vec<_>>()
.as_slice(),
);
// Return the full path instead of just the filename
Ok(process_name.to_string_lossy().to_string())
}
+3 -2
View File
@@ -14,9 +14,9 @@ impl InboundStreamHandler for Handler {
mut sess: Session,
stream: AnyStream,
) -> std::io::Result<AnyInboundTransport> {
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 {
+1 -1
View File
@@ -78,7 +78,7 @@ where
payload_len,
&dst_addr
);
Ok((payload_len, self.1, dst_addr))
Ok((payload_len, self.1.clone(), dst_addr))
}
}
+23 -2
View File
@@ -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<StreamId>,
pub process_name: Option<String>,
}
impl DatagramSource {
pub fn new(address: SocketAddr, stream_id: Option<StreamId>) -> Self {
DatagramSource { address, stream_id }
DatagramSource {
address,
stream_id,
process_name: None,
}
}
pub fn new_with_process_name(
address: SocketAddr,
stream_id: Option<StreamId>,
process_name: Option<String>,
) -> Self {
DatagramSource {
address,
stream_id,
process_name,
}
}
}
@@ -64,6 +81,8 @@ pub struct Session {
pub stream_id: Option<StreamId>,
/// Optional source address which is forwarded via HTTP reverse proxy.
pub forwarded_source: Option<IpAddr>,
/// Optional process name that initiated this connection.
pub process_name: Option<String>,
/// 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,
}
}