Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
use std::{
collections::HashMap,
fmt::Display,
net::{IpAddr, Ipv4Addr},
sync::Arc,
time::Duration,
};
use std::{collections::HashMap, fmt::Display, sync::Arc, time::Duration};

use async_trait::async_trait;
use erased_serde::Serialize as ESerialize;
Expand Down Expand Up @@ -339,11 +333,10 @@ impl RuleProvider for RuleProviderImpl {
match inner {
Ok(inner) => match &inner.content {
RuleContent::Domain(set) => set.has(&sess.destination.host()),
RuleContent::Ipcidr(trie) => trie.contains(
sess.destination
.ip()
.unwrap_or(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))),
),
RuleContent::Ipcidr(trie) => sess
.resolved_ip
.or(sess.destination.ip())
.is_some_and(|ip| trie.contains(ip)),
RuleContent::Classical(fast) => fast.search(sess),
},
Err(_) => {
Expand Down Expand Up @@ -762,6 +755,38 @@ mod tests {
);
}

#[tokio::test]
async fn test_ipcidr_provider_uses_resolved_ip() {
let provider = RuleProviderImpl::new(
"ipcidr-test".to_string(),
RuleSetBehavior::Ipcidr,
RuleSetFormat::Text,
None,
None,
Some(Arc::new(MockMmdbLookupTrait::new())),
Some(Arc::new(MockGeoDataLookupTrait::new())),
Some(vec!["10.0.0.0/8".to_owned(), "0.0.0.0/8".to_owned()]),
);
assert_ok!(provider.initialize().await);

// IP destination
assert!(provider.search(&Session {
destination: SocksAddr::Ip("10.1.2.3:443".parse().unwrap()),
..Default::default()
}));
// domain destination matched via the router-resolved IP
assert!(provider.search(&Session {
destination: SocksAddr::Domain("internal.example".to_owned(), 443),
resolved_ip: Some("10.1.2.3".parse().unwrap()),
..Default::default()
}));
// unresolved domain must not fall back to 0.0.0.0 and hit 0.0.0.0/8
assert!(!provider.search(&Session {
destination: SocksAddr::Domain("internal.example".to_owned(), 443),
..Default::default()
}));
}

#[tokio::test]
async fn test_classical_rule_provider() {
let mock_mmdb = MockMmdbLookupTrait::new();
Expand Down
117 changes: 117 additions & 0 deletions clash-lib/src/app/router/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,7 @@ pub fn map_rule_type(
print_and_exit!("rule provider {} not found", rule_set)
})
.clone(),
options.no_resolve,
)),
None => {
// this is called in remote rule provider with no rule provider
Expand Down Expand Up @@ -538,6 +539,122 @@ mod tests {
assert_eq!(entry.interface(), Some("en0"));
}

#[test]
fn test_rule_set_should_resolve_ip() {
use crate::app::remote_content_manager::providers::rule_provider::{
RuleProviderImpl, RuleSetBehavior, RuleSetFormat, ThreadSafeRuleProvider,
};
use std::collections::HashMap;

let mut registry: HashMap<String, ThreadSafeRuleProvider> = HashMap::new();
for (name, behavior) in [
("cidr", RuleSetBehavior::Ipcidr),
("classical", RuleSetBehavior::Classical),
("domains", RuleSetBehavior::Domain),
] {
registry.insert(
name.to_owned(),
Arc::new(RuleProviderImpl::new(
name.to_owned(),
behavior,
RuleSetFormat::Text,
None,
None,
None,
None,
Some(vec![]),
)),
);
}

let should_resolve = |line: &str| {
super::map_rule_type(
RuleType::try_from(line.to_string()).unwrap(),
None,
None,
Some(&registry),
)
.should_resolve_ip()
};

assert!(should_resolve("RULE-SET,cidr,DIRECT"));
assert!(!should_resolve("RULE-SET,cidr,DIRECT,no-resolve"));
assert!(should_resolve("RULE-SET,classical,DIRECT"));
assert!(!should_resolve("RULE-SET,classical,DIRECT,no-resolve"));
assert!(!should_resolve("RULE-SET,domains,DIRECT"));
}

#[tokio::test]
async fn test_rule_set_resolution_in_match_route() {
use crate::{
app::remote_content_manager::providers::rule_provider::RuleSetBehavior,
config::internal::config::{InlineRuleProvider, RuleProviderDef},
};
use std::collections::HashMap;

async fn route(rule: &str, expected_resolves: usize) -> String {
let mut resolver = MockClashResolver::new();
resolver
.expect_resolve()
.times(expected_resolves)
.returning(|_, _| Ok(Some("10.1.2.3".parse().unwrap())));

let providers = HashMap::from([
(
"cidr".to_owned(),
RuleProviderDef::Inline(InlineRuleProvider {
path: String::new(),
behavior: RuleSetBehavior::Ipcidr,
inline_rules: vec!["10.0.0.0/8".to_owned()],
}),
),
(
"domains".to_owned(),
RuleProviderDef::Inline(InlineRuleProvider {
path: String::new(),
behavior: RuleSetBehavior::Domain,
inline_rules: vec!["+.other.example".to_owned()],
}),
),
]);

let router = super::Router::new(
vec![RuleType::try_from(rule.to_owned()).unwrap()],
providers,
Arc::new(resolver),
None,
None,
None,
String::new(),
)
.await;
// providers are initialized in the background; make sure they are
// loaded before matching
for p in router.get_rule_providers().values() {
p.initialize().await.unwrap();
}

router
.match_route(&mut Session {
destination: crate::session::SocksAddr::Domain(
"internal.example".to_owned(),
443,
),
..Default::default()
})
.await
.0
.to_owned()
}

// resolves the domain and matches the resolved IP
assert_eq!(route("RULE-SET,cidr,PROXY", 1).await, "PROXY");
// no-resolve: no DNS lookup, so the domain cannot match
assert_eq!(route("RULE-SET,cidr,PROXY,no-resolve", 0).await, "MATCH");
// domain rule-sets never trigger a lookup
assert_eq!(route("RULE-SET,domains,PROXY", 0).await, "MATCH");
}

#[tokio::test]
async fn test_route_match() {
initialize();
Expand Down
15 changes: 14 additions & 1 deletion clash-lib/src/app/router/rules/ruleset.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use crate::{
app::{
remote_content_manager::providers::rule_provider::ThreadSafeRuleProvider,
remote_content_manager::providers::rule_provider::{
RuleSetBehavior, ThreadSafeRuleProvider,
},
router::rules::RuleMatcher,
},
session::Session,
Expand All @@ -11,18 +13,21 @@ pub struct RuleSet {
pub rule_set: String,
pub target: String,
pub rule_provider: ThreadSafeRuleProvider,
pub no_resolve: bool,
}

impl RuleSet {
pub fn new(
rule_set: String,
target: String,
rule_provider: ThreadSafeRuleProvider,
no_resolve: bool,
) -> Self {
Self {
rule_set,
target,
rule_provider,
no_resolve,
}
}
}
Expand All @@ -49,4 +54,12 @@ impl RuleMatcher for RuleSet {
fn type_name(&self) -> &str {
"RuleSet"
}

/// Resolve the destination domain before matching unless `no-resolve` is
/// set. Domain rule-sets never match on IPs, so they never
/// need resolution.
fn should_resolve_ip(&self) -> bool {
!self.no_resolve
&& !matches!(self.rule_provider.behavior(), RuleSetBehavior::Domain)
}
}
20 changes: 20 additions & 0 deletions clash-lib/src/config/internal/rule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,12 +402,16 @@ impl RuleType {
))),
}?;

// `no-resolve` applies to IP based rules and to RULE-SET (commonly
// used with ipcidr providers, e.g.
// `RULE-SET,cncidr,DIRECT,no-resolve`).
if options.no_resolve
&& !matches!(
&kind,
RuleKind::GeoIP { .. }
| RuleKind::IpCidr { .. }
| RuleKind::SrcCidr { .. }
| RuleKind::RuleSet { .. }
)
{
return Err(Error::InvalidConfig(format!(
Expand Down Expand Up @@ -510,6 +514,22 @@ mod tests {
assert_eq!(rule.interface(), None);
}

#[test]
fn test_no_resolve_option_accepted() {
let rule =
RuleType::try_from("RULE-SET,cncidr,DIRECT,no-resolve".to_string())
.unwrap();
assert_eq!(rule.target(), "DIRECT");
assert!(rule.options.no_resolve);

assert!(
RuleType::try_from(
"IP-CIDR,10.0.0.0/8,DIRECT,no-resolve,no-resolve".to_string()
)
.is_err()
);
}

#[test]
fn test_match_interface_option() {
let rule =
Expand Down
Loading