feat: support custom bypass rules and mesh routing policies

This commit is contained in:
shen
2026-10-15 07:06:34 -07:00
parent dc1bfc99d2
commit c1d0739b95
14 changed files with 621 additions and 89 deletions
+58 -11
View File
@@ -3,6 +3,7 @@ package bridge
import (
"context"
"encoding/json"
"fmt"
D "github.com/miekg/dns"
box "github.com/sagernet/sing-box"
M "github.com/sagernet/sing/common/metadata"
@@ -38,14 +39,14 @@ func TestBypassChinaPresetAndGlobalIsolation(t *testing.T) {
t.Fatal("preset did not force proxy fallback")
}
sets := route["rule_set"].([]any)
set := sets[0].(map[string]any)
if len(sets) != 1 || set["tag"] != "meshport-geoip-cn" || set["format"] != "binary" || set["download_detour"] != "proxy" || set["update_interval"] != "24h" {
set := sets[1].(map[string]any)
if len(sets) != 2 || sets[0].(map[string]any)["tag"] != "custom" || set["tag"] != "meshport-geoip-cn" || set["format"] != "binary" || set["download_detour"] != "proxy" || set["update_interval"] != "24h" {
t.Fatal("managed GeoIP update missing")
}
rules := route["rules"].([]any)
// DNS hijack/real-IP resolution precede mesh, withdrawn-prefix protection,
// ordinary private addresses and finally the China IP rule.
if len(rules) != 6 || rules[1].(map[string]any)["action"] != "resolve" || rules[2].(map[string]any)["outbound"] != "meshport" || rules[3].(map[string]any)["action"] != "reject" || rules[4].(map[string]any)["ip_is_private"] != true || rules[5].(map[string]any)["outbound"] != "direct" {
// custom rules/sets, ordinary private addresses and finally the China IP rule.
if len(rules) != 8 || rules[1].(map[string]any)["action"] != "resolve" || rules[2].(map[string]any)["outbound"] != "meshport" || rules[3].(map[string]any)["action"] != "reject" || rules[4].(map[string]any)["action"] != "reject" || rules[5].(map[string]any)["rule_set"].([]any)[0] != "custom" || rules[6].(map[string]any)["ip_is_private"] != true || rules[7].(map[string]any)["outbound"] != "direct" {
t.Fatal("GeoIP or mesh priority broken")
}
if len(c.Rules) != 1 || c.RuleSets[0].Tag != "custom" {
@@ -83,6 +84,8 @@ func TestBypassChinaPresetAndGlobalIsolation(t *testing.T) {
// exits, so real-IP/FakeIP policy is exercised without public connections.
func TestBypassChinaRealIPAndFakeIPRouting(t *testing.T) {
for _, fake := range []bool{false, true} {
mesh, mc := socksEcho(t)
defer mesh.Close()
direct, dc := socksEcho(t)
defer direct.Close()
proxy, pc := socksEcho(t)
@@ -95,9 +98,12 @@ func TestBypassChinaRealIPAndFakeIPRouting(t *testing.T) {
m := new(D.Msg)
m.SetReply(r)
ip := "203.0.113.7"
if r.Question[0].Name == "china.test." {
if r.Question[0].Name == "china.test." || r.Question[0].Name == "china-proxy.test." || r.Question[0].Name == "blocked.test." {
ip = "198.51.100.7"
}
if r.Question[0].Name == "private-proxy.test." {
ip = "10.99.0.1"
}
if r.Question[0].Qtype == D.TypeA {
m.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: r.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP(ip)}}
}
@@ -107,7 +113,17 @@ func TestBypassChinaRealIPAndFakeIPRouting(t *testing.T) {
defer server.Shutdown()
listener, port := reservePort(t)
listener.Close()
c := Config{ListenPort: port, Feature: "proxy", Mode: "bypass_cn", FakeIP: fake, DNS: socket.LocalAddr().String(), Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}}
c := Config{ListenPort: port, Feature: "combined", MeshSOCKS: mesh.Addr().String(), MeshCIDRs: []string{"10.77.0.0/24"}, ProtectedCIDRs: []string{"10.88.0.0/24"}, Mode: "bypass_cn", FakeIP: fake, DNS: socket.LocalAddr().String(), Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}}
c.Rules = []Rule{
{Type: "ip_cidr", Value: "10.77.0.0/24", Action: "direct"},
{Type: "ip_cidr", Value: "10.88.0.0/24", Action: "proxy"},
{Type: "domain", Value: "china-proxy.test", Action: "proxy"},
{Type: "domain_suffix", Value: "foreign-direct.test", Action: "direct"},
{Type: "domain", Value: "private-proxy.test", Action: "proxy"},
{Type: "domain", Value: "blocked.test", Action: "reject"},
{Type: "ip_cidr", Value: "198.51.100.8/32", Action: "proxy"},
}
c.RuleSets = []RuleSet{{Tag: "user-direct", Enabled: true, Action: "direct", Rules: []map[string]any{{"domain": []string{"set-direct.test"}}}}}
data, err := c.managedJSON()
if err != nil {
t.Fatal(err)
@@ -115,9 +131,17 @@ func TestBypassChinaRealIPAndFakeIPRouting(t *testing.T) {
var generated map[string]any
json.Unmarshal(data, &generated)
route := generated["route"].(map[string]any)
route["rule_set"] = []any{map[string]any{"type": "inline", "tag": "meshport-geoip-cn", "rules": []any{map[string]any{"ip_cidr": []string{"198.51.100.0/24"}}}}}
for i, set := range route["rule_set"].([]any) {
if set.(map[string]any)["tag"] == "meshport-geoip-cn" {
route["rule_set"].([]any)[i] = map[string]any{"type": "inline", "tag": "meshport-geoip-cn", "rules": []any{map[string]any{"ip_cidr": []string{"198.51.100.0/24"}}}}
}
}
outbounds := generated["outbounds"].([]any)
outbounds[0] = map[string]any{"type": "socks", "tag": "direct", "server": "127.0.0.1", "server_port": direct.Addr().(*net.TCPAddr).Port}
for i, outbound := range outbounds {
if outbound.(map[string]any)["tag"] == "direct" {
outbounds[i] = map[string]any{"type": "socks", "tag": "direct", "server": "127.0.0.1", "server_port": direct.Addr().(*net.TCPAddr).Port}
}
}
data, _ = json.Marshal(generated)
ctx := registryContext(context.Background())
options, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
@@ -131,7 +155,7 @@ func TestBypassChinaRealIPAndFakeIPRouting(t *testing.T) {
if err = instance.Start(); err != nil {
t.Fatal(err)
}
for _, domain := range []string{"china.test", "foreign.test"} {
for _, domain := range []string{"china.test", "foreign.test", "china-proxy.test", "foreign-direct.test", "private-proxy.test", "set-direct.test", "blocked.test"} {
target := domain
if fake {
conn, err := net.Dial("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(int(port))))
@@ -156,11 +180,34 @@ func TestBypassChinaRealIPAndFakeIPRouting(t *testing.T) {
}
target = answer.Answer[0].(*D.A).A.String()
}
echoThrough(t, port, M.ParseSocksaddr(net.JoinHostPort(target, "443")), true)
echoThrough(t, port, M.ParseSocksaddr(net.JoinHostPort(target, "443")), domain != "blocked.test")
}
if dc.Load() != 1 || pc.Load() != 1 {
echoThrough(t, port, M.ParseSocksaddr("198.51.100.8:443"), true)
echoThrough(t, port, M.ParseSocksaddr("10.77.0.8:443"), true)
echoThrough(t, port, M.ParseSocksaddr("10.88.0.8:443"), false)
if dc.Load() != 3 || pc.Load() != 4 || mc.Load() != 1 {
t.Fatalf("fake=%v direct=%d proxy=%d", fake, dc.Load(), pc.Load())
}
instance.Close()
}
}
func TestBypassCustomRuleValidationAndReservedTag(t *testing.T) {
c := Config{ListenPort: 12345, Feature: "proxy", Mode: "bypass_cn", Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": 12346}}
c.Rules = []Rule{{Type: "domain", Value: "*.example.com", Action: "direct"}}
if _, err := c.managedJSON(); err == nil {
t.Fatal("invalid custom rule was ignored")
}
c.Rules = nil
c.RuleSets = []RuleSet{{Tag: "meshport-geoip-cn", Enabled: true, Action: "proxy", Rules: []map[string]any{{"domain": []string{"example.com"}}}}}
if _, err := c.managedJSON(); err == nil {
t.Fatal("reserved GeoIP tag accepted")
}
c.RuleSets = nil
for i := 0; i < 32; i++ {
c.RuleSets = append(c.RuleSets, RuleSet{Tag: fmt.Sprintf("user-%d", i), Enabled: true, Action: "direct", Rules: []map[string]any{{"domain": []string{"example.com"}}}})
}
if _, err := c.managedJSON(); err != nil {
t.Fatal("managed set consumed a user slot", err)
}
}
+24 -12
View File
@@ -238,15 +238,11 @@ func (c Config) managedJSONForPlatform(platform string) ([]byte, error) {
if mode != "rule" && mode != "global" && mode != "direct" && mode != "bypass_cn" {
return nil, errors.New("invalid proxy mode")
}
// A managed preset must not inherit custom rules that could override GeoIP.
// User rules override the managed preset, but never mesh routing/protection.
bypassCN := mode == "bypass_cn"
if bypassCN {
mode = "rule"
c.DefaultAction = "proxy"
c.Rules = nil
c.RuleSets = []RuleSet{{Tag: "meshport-geoip-cn", Enabled: true,
URL: "https://raw.githubusercontent.com/SagerNet/sing-geoip/rule-set/geoip-cn.srs",
Format: "binary", Action: "direct", DownloadDetour: "proxy", UpdateHours: 24}}
}
active, err := prefixes(c.MeshCIDRs)
if err != nil {
@@ -292,7 +288,7 @@ func (c Config) managedJSONForPlatform(platform string) ([]byte, error) {
if action == "" {
action = "proxy"
}
if action != "proxy" && action != "direct" && action != "reject" {
if action != "proxy" && action != "direct" && action != "mesh" && action != "reject" {
return nil, errors.New("invalid default action")
}
if internet && mode == "global" {
@@ -301,6 +297,11 @@ func (c Config) managedJSONForPlatform(platform string) ([]byte, error) {
if internet && mode == "direct" {
action = "direct"
}
// Active mesh prefixes are always routed before ordinary policies. A mesh
// fallback therefore rejects everything that did not match that projection.
if action == "mesh" {
action = "reject"
}
routeRules := []any{}
dns := map[string]any{}
defaultResolver := "bootstrap"
@@ -402,9 +403,6 @@ func (c Config) managedJSONForPlatform(platform string) ([]byte, error) {
if mesh && len(protected) > 0 {
routeRules = append(routeRules, map[string]any{"ip_cidr": protected, "action": "reject"})
}
if internet && bypassCN {
routeRules = append(routeRules, map[string]any{"ip_is_private": true, "action": "route", "outbound": "direct"})
}
usedProxy := internet && action == "proxy"
if internet && mode == "rule" {
if len(c.Rules) > 256 {
@@ -428,7 +426,9 @@ func (c Config) managedJSONForPlatform(platform string) ([]byte, error) {
return nil, errors.New("unsupported rule type")
}
switch r.Action {
case "reject":
case "reject", "mesh":
// Routable mesh destinations were handled by the managed rules
// above. Never send an unknown mesh target to another outlet.
item["action"] = "reject"
case "direct", "proxy":
item["action"] = "route"
@@ -451,11 +451,14 @@ func (c Config) managedJSONForPlatform(platform string) ([]byte, error) {
if !set.Enabled || !internet || mode != "rule" {
continue
}
if bypassCN && set.Tag == "meshport-geoip-cn" {
return nil, errors.New("reserved managed rule set tag: meshport-geoip-cn")
}
if !domain(set.Tag) || tags[set.Tag] {
return nil, errors.New("invalid or duplicate rule set tag")
}
tags[set.Tag] = true
if set.Action != "proxy" && set.Action != "direct" && set.Action != "reject" {
if set.Action != "proxy" && set.Action != "direct" && set.Action != "mesh" && set.Action != "reject" {
return nil, errors.New("invalid rule set action")
}
item := map[string]any{"tag": set.Tag}
@@ -495,7 +498,7 @@ func (c Config) managedJSONForPlatform(platform string) ([]byte, error) {
if internet && mode == "rule" {
ruleSets = append(ruleSets, item)
match := map[string]any{"rule_set": []string{set.Tag}, "action": "route", "outbound": set.Action}
if set.Action == "reject" {
if set.Action == "reject" || set.Action == "mesh" {
delete(match, "outbound")
match["action"] = "reject"
}
@@ -505,6 +508,15 @@ func (c Config) managedJSONForPlatform(platform string) ([]byte, error) {
routeRules = append(routeRules, match)
}
}
if internet && bypassCN {
routeRules = append(routeRules, map[string]any{"ip_is_private": true, "action": "route", "outbound": "direct"})
ruleSets = append(ruleSets, map[string]any{
"tag": "meshport-geoip-cn", "type": "remote", "format": "binary",
"url": "https://raw.githubusercontent.com/SagerNet/sing-geoip/rule-set/geoip-cn.srs",
"download_detour": "proxy", "update_interval": "24h",
})
routeRules = append(routeRules, map[string]any{"rule_set": []string{"meshport-geoip-cn"}, "action": "route", "outbound": "direct"})
}
if usedProxy && c.Proxy == nil {
return nil, errors.New("selected proxy node required")
}
+128
View File
@@ -0,0 +1,128 @@
package bridge
import (
"context"
"encoding/json"
"net"
"testing"
D "github.com/miekg/dns"
box "github.com/sagernet/sing-box"
"github.com/sagernet/sing-box/option"
sjson "github.com/sagernet/sing/common/json"
M "github.com/sagernet/sing/common/metadata"
)
func TestMeshPoliciesNeverFallBackToInternet(t *testing.T) {
for _, mode := range []string{"rule", "bypass_cn"} {
for _, state := range []string{"active", "withdrawn", "proxy-only", "mesh-default"} {
if mode == "bypass_cn" && state == "mesh-default" {
continue
}
t.Run(mode+"/"+state, func(t *testing.T) {
mesh, mc := socksEcho(t)
defer mesh.Close()
proxy, pc := socksEcho(t)
defer proxy.Close()
direct, dc := socksEcho(t)
defer direct.Close()
dnsSocket, err := net.ListenPacket("udp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
dnsServer := &D.Server{PacketConn: dnsSocket, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) {
m := new(D.Msg)
m.SetReply(r)
if r.Question[0].Qtype == D.TypeA {
m.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: r.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP("203.0.113.33")}}
}
w.WriteMsg(m)
})}
go dnsServer.ActivateAndServe()
defer dnsServer.Shutdown()
entry, port := reservePort(t)
entry.Close()
c := Config{ListenPort: port, Feature: "combined", Mode: mode, DefaultAction: "direct", DNS: dnsSocket.LocalAddr().String(),
MeshSOCKS: mesh.Addr().String(), MeshCIDRs: []string{"10.77.0.0/24"}, ProtectedCIDRs: []string{"10.77.0.0/24"},
Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port},
Rules: []Rule{{Type: "ip_cidr", Value: "10.77.0.0/24", Action: "mesh"}, {Type: "ip_cidr", Value: "10.44.0.0/24", Action: "mesh"}, {Type: "domain_suffix", Value: "mesh-policy.test", Action: "mesh"}},
RuleSets: []RuleSet{{Tag: "group-subnets", Enabled: true, Action: "mesh", Rules: []map[string]any{{"ip_cidr": []string{"10.55.0.0/24"}}}}},
}
if state == "withdrawn" {
c.MeshCIDRs = nil
}
if state == "proxy-only" {
c.Feature = "proxy"
c.MeshCIDRs = nil
c.ProtectedCIDRs = nil
}
if state == "mesh-default" {
c.DefaultAction = "mesh"
}
data, err := c.managedJSON()
if err != nil {
t.Fatal(err)
}
var generated map[string]any
if err = json.Unmarshal(data, &generated); err != nil {
t.Fatal(err)
}
route := generated["route"].(map[string]any)
if sets, ok := route["rule_set"].([]any); ok {
for i, set := range sets {
if set.(map[string]any)["tag"] == "meshport-geoip-cn" {
sets[i] = map[string]any{"type": "inline", "tag": "meshport-geoip-cn", "rules": []any{map[string]any{"ip_cidr": []string{"198.51.100.0/24"}}}}
}
}
}
for i, out := range generated["outbounds"].([]any) {
if out.(map[string]any)["tag"] == "direct" {
generated["outbounds"].([]any)[i] = map[string]any{"type": "socks", "tag": "direct", "server": "127.0.0.1", "server_port": direct.Addr().(*net.TCPAddr).Port}
}
}
data, _ = json.Marshal(generated)
ctx := registryContext(context.Background())
options, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
if err != nil {
t.Fatal(err)
}
instance, err := box.New(box.Options{Context: ctx, Options: options})
if err != nil {
t.Fatal(err)
}
defer instance.Close()
if err = instance.Start(); err != nil {
t.Fatal(err)
}
active := state == "active" || state == "mesh-default"
echoThrough(t, port, M.ParseSocksaddr("10.77.0.8:443"), active)
for _, target := range []string{"10.44.0.8:443", "10.55.0.8:443", "host.mesh-policy.test:443"} {
echoThrough(t, port, M.ParseSocksaddr(target), false)
}
echoThrough(t, port, M.ParseSocksaddr("203.0.113.9:443"), state != "mesh-default")
wantMesh := int32(0)
if active {
wantMesh = 1
}
wantProxy, wantDirect := int32(0), int32(0)
if state != "mesh-default" {
if mode == "bypass_cn" {
wantProxy = 1
} else {
wantDirect = 1
}
}
if mc.Load() != wantMesh || pc.Load() != wantProxy || dc.Load() != wantDirect {
t.Fatalf("unexpected outlet: mesh=%d proxy=%d direct=%d", mc.Load(), pc.Load(), dc.Load())
}
if active {
mesh.Close()
echoThrough(t, port, M.ParseSocksaddr("10.77.0.8:443"), false)
if pc.Load() != wantProxy || dc.Load() != wantDirect {
t.Fatal("unavailable mesh bridge fell back to internet")
}
}
})
}
}
}