From 7daa8e4b6adb3a7098b43b192fd3175d8612a884 Mon Sep 17 00:00:00 2001 From: Meow <197331664+Meo597@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:39:20 +0800 Subject: [PATCH] Direct/Freedom outbound: Rename `finalRules` to `firewall`; Add `reply` to `firewall`; Merge Block/Blackhole outbound; Move `proxyProtocol` to "proxy-protocol" TCP finalmask (#7281) https://github.com/XTLS/Xray-core/pull/7238#issuecomment-6467092152 https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6484050347 https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6484439860 https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6621021705 https://github.com/XTLS/Xray-core/pull/7329#issuecomment-6623818990 https://github.com/XTLS/Xray-core/pull/7329#issuecomment-6624149740 https://github.com/XTLS/Xray-core/pull/7329#issuecomment-6625219097 https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6627156942 https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6850640864 https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6973501579 --------- Co-authored-by: Codex --- app/dns/dns_test.go | 16 +- app/proxyman/outbound/handler_test.go | 6 +- app/router/script_test.go | 5 +- core/functions_test.go | 6 +- infra/conf/blackhole.go | 18 +- infra/conf/blackhole_test.go | 35 ++- infra/conf/freedom.go | 96 ++++++--- infra/conf/freedom_test.go | 14 +- infra/conf/transport_finalmask.go | 39 +++- infra/conf/xray.go | 11 +- main/distro/all/all.go | 1 - proxy/blackhole/blackhole.go | 88 -------- proxy/blackhole/blackhole_test.go | 76 ------- proxy/blackhole/config.pb.go | 180 ---------------- proxy/blackhole/config.proto | 16 -- proxy/blackhole/config_test.go | 19 -- proxy/freedom/config.pb.go | 204 +++++++++++------- proxy/freedom/config.proto | 12 +- proxy/freedom/freedom.go | 137 +++++++----- proxy/freedom/freedom_test.go | 87 ++++++++ proxy/tun/tun_linux_dns_route_test.go | 3 +- testing/scenarios/command_test.go | 10 +- testing/scenarios/dns_test.go | 3 +- testing/scenarios/dokodemo_test.go | 4 +- testing/scenarios/feature_test.go | 21 +- testing/scenarios/http_test.go | 12 +- testing/scenarios/masque_test.go | 2 +- testing/scenarios/metrics_test.go | 2 +- testing/scenarios/policy_test.go | 4 +- testing/scenarios/reverse_test.go | 9 +- testing/scenarios/shadowsocks_2022_test.go | 4 +- testing/scenarios/shadowsocks_test.go | 8 +- testing/scenarios/socks_test.go | 13 +- testing/scenarios/tls_test.go | 20 +- testing/scenarios/transport_test.go | 2 +- testing/scenarios/vless_test.go | 16 +- testing/scenarios/vmess_test.go | 20 +- testing/scenarios/wireguard_test.go | 2 +- transport/internet/finalmask/finalmask.go | 5 + .../finalmask/proxyprotocol/config.go | 31 +++ .../finalmask/proxyprotocol/config.pb.go | 123 +++++++++++ .../finalmask/proxyprotocol/config.proto | 11 + .../finalmask/proxyprotocol/config_test.go | 93 ++++++++ .../internet/finalmask/sudoku/sudoku_test.go | 8 +- 44 files changed, 828 insertions(+), 664 deletions(-) delete mode 100644 proxy/blackhole/blackhole.go delete mode 100644 proxy/blackhole/blackhole_test.go delete mode 100644 proxy/blackhole/config.pb.go delete mode 100644 proxy/blackhole/config.proto delete mode 100644 proxy/blackhole/config_test.go create mode 100644 proxy/freedom/freedom_test.go create mode 100644 transport/internet/finalmask/proxyprotocol/config.go create mode 100644 transport/internet/finalmask/proxyprotocol/config.pb.go create mode 100644 transport/internet/finalmask/proxyprotocol/config.proto create mode 100644 transport/internet/finalmask/proxyprotocol/config_test.go diff --git a/app/dns/dns_test.go b/app/dns/dns_test.go index 8ccfe8407..575fda271 100644 --- a/app/dns/dns_test.go +++ b/app/dns/dns_test.go @@ -148,7 +148,7 @@ func TestUDPServerSubnet(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -210,7 +210,7 @@ func TestUDPServer(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -350,7 +350,7 @@ func TestPrioritizedDomain(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -421,7 +421,7 @@ func TestUDPServerIPv6(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -490,7 +490,7 @@ func TestStaticHostDomain(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -577,7 +577,7 @@ func TestIPMatch(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -696,7 +696,7 @@ func TestLocalDomain(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -953,7 +953,7 @@ func TestMultiMatchPrioritizedDomain(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, diff --git a/app/proxyman/outbound/handler_test.go b/app/proxyman/outbound/handler_test.go index 702944298..b9e6ecfa1 100644 --- a/app/proxyman/outbound/handler_test.go +++ b/app/proxyman/outbound/handler_test.go @@ -48,7 +48,7 @@ func TestOutboundWithoutStatCounter(t *testing.T) { ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{}}) h, _ := NewHandler(ctx, &core.OutboundHandlerConfig{ Tag: "tag", - ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}), }) conn, _ := h.(*Handler).Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146)) _, ok := conn.(*stat.CounterConnection) @@ -78,7 +78,7 @@ func TestOutboundWithStatCounter(t *testing.T) { ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{}}) h, _ := NewHandler(ctx, &core.OutboundHandlerConfig{ Tag: "tag", - ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}), }) conn, _ := h.(*Handler).Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146)) _, ok := conn.(*stat.CounterConnection) @@ -117,7 +117,7 @@ func TestTagsCache(t *testing.T) { tag := fmt.Sprintf("%s%d", tags_prefix, idx) cfg := &core.OutboundHandlerConfig{ Tag: tag, - ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}), } if h, err := NewHandler(ctx, cfg); err == nil { if err := ohm.AddHandler(ctx, h); err == nil { diff --git a/app/router/script_test.go b/app/router/script_test.go index 599ebbf7d..6d68b5eb0 100644 --- a/app/router/script_test.go +++ b/app/router/script_test.go @@ -24,7 +24,6 @@ import ( "github.com/xtls/xray-core/features/outbound" "github.com/xtls/xray-core/features/routing" routing_session "github.com/xtls/xray-core/features/routing/session" - "github.com/xtls/xray-core/proxy/blackhole" "github.com/xtls/xray-core/proxy/freedom" ) @@ -397,9 +396,9 @@ end`) serial.ToTypedMessage(&proxyman.OutboundConfig{}), }, Outbound: []*core.OutboundHandlerConfig{ - {Tag: "default", ProxySettings: serial.ToTypedMessage(&blackhole.Config{})}, + {Tag: "default", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})}, {Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, })}, }, }) diff --git a/core/functions_test.go b/core/functions_test.go index e1f13894c..030785dfb 100644 --- a/core/functions_test.go +++ b/core/functions_test.go @@ -53,7 +53,7 @@ func TestXrayDial(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -105,7 +105,7 @@ func TestXrayDialUDPConn(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -174,7 +174,7 @@ func TestXrayDialUDP(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, diff --git a/infra/conf/blackhole.go b/infra/conf/blackhole.go index 7046d1efe..c203927ca 100644 --- a/infra/conf/blackhole.go +++ b/infra/conf/blackhole.go @@ -5,7 +5,8 @@ import ( "strings" "github.com/xtls/xray-core/common/errors" - "github.com/xtls/xray-core/proxy/blackhole" + "github.com/xtls/xray-core/common/log" + "github.com/xtls/xray-core/proxy/freedom" "google.golang.org/protobuf/proto" ) @@ -19,24 +20,29 @@ type BlackholeConfig struct { } func (v *BlackholeConfig) Build() (proto.Message, error) { - config := new(blackhole.Config) + errors.PrintDeprecatedFeatureWarning(`"blackhole" outbound`, `"freedom" outbound with a blocking "firewall" rule`) + rule := &freedom.FirewallConfig{ + Action: freedom.RuleAction_Block, + Delay: &freedom.Range{}, + LogLevel: log.Severity_Unknown.Enum(), + } if v.Response != nil { responseName := strings.ToLower(v.Response.Type) switch responseName { case "none", "": - config.Response = &blackhole.Response{Type: "none"} + rule.Reply = &freedom.Reply{Type: "none"} case "http": - config.Response = &blackhole.Response{Type: "http"} + rule.Reply = &freedom.Reply{Type: "http"} case "custom": data, err := base64.StdEncoding.DecodeString(v.Response.CustomResponseData) if err != nil { return nil, errors.New("failed to decode custom response data: " + err.Error()) } - config.Response = &blackhole.Response{Type: "custom", CustomResponseData: data} + rule.Reply = &freedom.Reply{Type: "custom", CustomResponseData: data} default: return nil, errors.New("unknown blackhole response: " + responseName) } } - return config, nil + return &freedom.Config{Firewall: []*freedom.FirewallConfig{rule}}, nil } diff --git a/infra/conf/blackhole_test.go b/infra/conf/blackhole_test.go index 83e9b1f22..a959b9cff 100644 --- a/infra/conf/blackhole_test.go +++ b/infra/conf/blackhole_test.go @@ -3,8 +3,9 @@ package conf_test import ( "testing" + "github.com/xtls/xray-core/common/log" . "github.com/xtls/xray-core/infra/conf" - "github.com/xtls/xray-core/proxy/blackhole" + "github.com/xtls/xray-core/proxy/freedom" ) func TestHTTPResponseJSON(t *testing.T) { @@ -20,14 +21,25 @@ func TestHTTPResponseJSON(t *testing.T) { } }`, Parser: loadJSON(creator), - Output: &blackhole.Config{ - Response: &blackhole.Response{Type: "http"}, + Output: &freedom.Config{ + Firewall: []*freedom.FirewallConfig{{ + Action: freedom.RuleAction_Block, + Delay: &freedom.Range{}, + LogLevel: log.Severity_Unknown.Enum(), + Reply: &freedom.Reply{Type: "http"}, + }}, }, }, { Input: `{}`, Parser: loadJSON(creator), - Output: &blackhole.Config{}, + Output: &freedom.Config{ + Firewall: []*freedom.FirewallConfig{{ + Action: freedom.RuleAction_Block, + Delay: &freedom.Range{}, + LogLevel: log.Severity_Unknown.Enum(), + }}, + }, }, }) } @@ -46,11 +58,16 @@ func TestCustomResponseJSON(t *testing.T) { } }`, Parser: loadJSON(creator), - Output: &blackhole.Config{ - Response: &blackhole.Response{ - Type: "custom", - CustomResponseData: []byte("custom response"), - }, + Output: &freedom.Config{ + Firewall: []*freedom.FirewallConfig{{ + Action: freedom.RuleAction_Block, + Delay: &freedom.Range{}, + LogLevel: log.Severity_Unknown.Enum(), + Reply: &freedom.Reply{ + Type: "custom", + CustomResponseData: []byte("custom response"), + }, + }}, }, }, }) diff --git a/infra/conf/freedom.go b/infra/conf/freedom.go index d825e032b..5384c7d9a 100644 --- a/infra/conf/freedom.go +++ b/infra/conf/freedom.go @@ -18,16 +18,17 @@ import ( ) type FreedomConfig struct { - TargetStrategy string `json:"targetStrategy"` - DomainStrategy string `json:"domainStrategy"` - Redirect string `json:"redirect"` - UserLevel uint32 `json:"userLevel"` - Fragment *Fragment `json:"fragment"` - Noise *Noise `json:"noise"` - Noises []*Noise `json:"noises"` - ProxyProtocol uint32 `json:"proxyProtocol"` - IPsBlocked *StringList `json:"ipsBlocked"` - FinalRules []*FreedomFinalRuleConfig `json:"finalRules"` + TargetStrategy string `json:"targetStrategy"` + DomainStrategy string `json:"domainStrategy"` + Redirect string `json:"redirect"` + UserLevel uint32 `json:"userLevel"` + Fragment *Fragment `json:"fragment"` + Noise *Noise `json:"noise"` + Noises []*Noise `json:"noises"` + ProxyProtocol uint32 `json:"proxyProtocol"` + IPsBlocked *StringList `json:"ipsBlocked"` + Firewall []*FreedomFirewallConfig `json:"firewall"` + FinalRules []*FreedomFirewallConfig `json:"finalRules"` } type Fragment struct { @@ -44,21 +45,45 @@ type Noise struct { ApplyTo string `json:"applyTo"` } -type FreedomFinalRuleConfig struct { - Action string `json:"action"` - Network *NetworkList `json:"network"` - Port *PortList `json:"port"` - IP *StringList `json:"ip"` - Delay *Int32Range `json:"delay"` - LogLevel string `json:"logLevel"` - BlockDelay *Int32Range `json:"blockDelay"` +type FreedomFirewallConfig struct { + Action string `json:"action"` + Network *NetworkList `json:"network"` + Port *PortList `json:"port"` + IP *StringList `json:"ip"` + Delay *Int32Range `json:"delay"` + LogLevel string `json:"logLevel"` + Reply *FreedomReplyConfig `json:"reply"` + BlockDelay *Int32Range `json:"blockDelay"` +} + +type FreedomReplyConfig struct { + Type string `json:"type"` + CustomResponseData string `json:"customResponseData"` +} + +func (c *FreedomReplyConfig) Build() (*freedom.Reply, error) { + replyType := strings.ToLower(c.Type) + switch replyType { + case "none", "": + return &freedom.Reply{Type: "none"}, nil + case "http": + return &freedom.Reply{Type: "http"}, nil + case "custom": + data, err := base64.StdEncoding.DecodeString(c.CustomResponseData) + if err != nil { + return nil, errors.New("failed to decode custom reply data: " + err.Error()) + } + return &freedom.Reply{Type: "custom", CustomResponseData: data}, nil + default: + return nil, errors.New("unknown firewall reply: " + replyType) + } } // Build implements Buildable func (c *FreedomConfig) Build() (proto.Message, error) { if c.IPsBlocked != nil { // todo: remove legacy - errors.LogWarning(context.Background(), `The feature "ipsBlocked" has been removed and migrated to "finalRules". Please update your config(s) according to release note and documentation.`) + errors.LogWarning(context.Background(), `The feature "ipsBlocked" has been removed and migrated to "firewall". Please update your config(s) according to release note and documentation.`) } config := new(freedom.Config) @@ -184,15 +209,22 @@ func (c *FreedomConfig) Build() (proto.Message, error) { } if c.ProxyProtocol > 0 && c.ProxyProtocol <= 2 { - config.ProxyProtocol = c.ProxyProtocol + errors.PrintDeprecatedFeatureWarning(`"proxyProtocol" in Freedom`, `"proxy-protocol" in "streamSettings.finalmask.tcp"`) } - for _, r := range c.FinalRules { + firewall := c.Firewall + if c.FinalRules != nil { + errors.PrintDeprecatedFeatureWarning("finalRules", "firewall") + if firewall == nil { + firewall = c.FinalRules + } + } + for _, r := range firewall { rule, err := r.Build() if err != nil { return nil, err } - config.FinalRules = append(config.FinalRules, rule) + config.Firewall = append(config.Firewall, rule) } return config, nil @@ -254,8 +286,8 @@ func ParseNoise(noise *Noise) (*freedom.Noise, error) { return NConfig, nil } -func (c *FreedomFinalRuleConfig) Build() (*freedom.FinalRuleConfig, error) { - rule := &freedom.FinalRuleConfig{} +func (c *FreedomFirewallConfig) Build() (*freedom.FirewallConfig, error) { + rule := &freedom.FirewallConfig{} switch strings.ToLower(c.Action) { case "allow": @@ -283,13 +315,13 @@ func (c *FreedomFinalRuleConfig) Build() (*freedom.FinalRuleConfig, error) { } if c.BlockDelay != nil { - errors.PrintDeprecatedFeatureWarning("finalRules.blockDelay", "finalRules.delay") + errors.PrintDeprecatedFeatureWarning("firewall.blockDelay", "firewall.delay") c.Delay = c.BlockDelay } if rule.Action != freedom.RuleAction_Block { - if c.Delay != nil || c.LogLevel != "" { - return nil, errors.New("delay and logLevel are only supported for block finalRules") + if c.Delay != nil || c.LogLevel != "" || c.Reply != nil { + return nil, errors.New("delay, logLevel and reply are only supported for firewall action block") } return rule, nil } @@ -301,6 +333,14 @@ func (c *FreedomFinalRuleConfig) Build() (*freedom.FinalRuleConfig, error) { } } + if c.Reply != nil { + reply, err := c.Reply.Build() + if err != nil { + return nil, err + } + rule.Reply = reply + } + switch strings.ToLower(c.LogLevel) { case "", "info": rule.LogLevel = log.Severity_Info.Enum() @@ -313,7 +353,7 @@ func (c *FreedomFinalRuleConfig) Build() (*freedom.FinalRuleConfig, error) { case "error": rule.LogLevel = log.Severity_Error.Enum() default: - return nil, errors.New("unknown finalRules.logLevel: ", c.LogLevel) + return nil, errors.New("unknown firewall.logLevel: ", c.LogLevel) } return rule, nil diff --git a/infra/conf/freedom_test.go b/infra/conf/freedom_test.go index 1d50fee7b..af29e9eeb 100644 --- a/infra/conf/freedom_test.go +++ b/infra/conf/freedom_test.go @@ -42,13 +42,17 @@ func TestFreedomConfig(t *testing.T) { }, { Input: `{ - "finalRules": [{ + "firewall": [{ "action": "block", "network": "tcp,udp", "port": "53,443", "ip": ["10.0.0.0/8", "2001:db8::/32"], "delay": "30-60", - "logLevel": "debug" + "logLevel": "debug", + "reply": { + "type": "custom", + "customResponseData": "Y3VzdG9tIHJlc3BvbnNl" + } }, { "action": "allow", "network": ["udp"] @@ -56,7 +60,7 @@ func TestFreedomConfig(t *testing.T) { }`, Parser: loadJSON(creator), Output: &freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{ + Firewall: []*freedom.FirewallConfig{ { Action: freedom.RuleAction_Block, Networks: []net.Network{net.Network_TCP, net.Network_UDP}, @@ -90,6 +94,10 @@ func TestFreedomConfig(t *testing.T) { }, Delay: &freedom.Range{Min: 30, Max: 60}, LogLevel: log.Severity_Debug.Enum(), + Reply: &freedom.Reply{ + Type: "custom", + CustomResponseData: []byte("custom response"), + }, }, { Action: freedom.RuleAction_Allow, diff --git a/infra/conf/transport_finalmask.go b/infra/conf/transport_finalmask.go index 29d3fe838..1873159d2 100644 --- a/infra/conf/transport_finalmask.go +++ b/infra/conf/transport_finalmask.go @@ -18,6 +18,7 @@ import ( "github.com/xtls/xray-core/common/geodata" xlua "github.com/xtls/xray-core/common/lua" "github.com/xtls/xray-core/common/net" + "github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/finalmask/filter" "github.com/xtls/xray-core/transport/internet/finalmask/fragment" @@ -26,6 +27,7 @@ import ( "github.com/xtls/xray-core/transport/internet/finalmask/mkcp/header" "github.com/xtls/xray-core/transport/internet/finalmask/mkcp/original" "github.com/xtls/xray-core/transport/internet/finalmask/noise" + "github.com/xtls/xray-core/transport/internet/finalmask/proxyprotocol" "github.com/xtls/xray-core/transport/internet/finalmask/realm" "github.com/xtls/xray-core/transport/internet/finalmask/salamander" "github.com/xtls/xray-core/transport/internet/finalmask/sudoku" @@ -76,11 +78,12 @@ var ( customVarNamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) tcpmaskLoader = NewJSONConfigLoader(ConfigCreatorCache{ - "filter": func() interface{} { return new(Filter) }, - "header-custom": func() interface{} { return new(HeaderCustomTCP) }, - "fragment": func() interface{} { return new(FragmentMask) }, - "sudoku": func() interface{} { return new(Sudoku) }, - "xmc": func() interface{} { return new(XMC) }, + "filter": func() interface{} { return new(Filter) }, + "header-custom": func() interface{} { return new(HeaderCustomTCP) }, + "proxy-protocol": func() interface{} { return new(ProxyProtocol) }, + "fragment": func() interface{} { return new(FragmentMask) }, + "sudoku": func() interface{} { return new(Sudoku) }, + "xmc": func() interface{} { return new(XMC) }, }, "type", "settings") udpmaskLoader = NewJSONConfigLoader(ConfigCreatorCache{ @@ -97,6 +100,32 @@ var ( }, "type", "settings") ) +type ProxyProtocol struct { + Version uint32 `json:"version"` +} + +func (c *ProxyProtocol) Build() (proto.Message, error) { + version := c.Version + if version == 0 { + version = 2 + } + if version != 1 && version != 2 { + return nil, errors.New("PROXY protocol version must be 1 or 2") + } + return &proxyprotocol.Config{Version: version}, nil +} + +func addProxyProtocolMask(config *internet.StreamConfig, version uint32) { + mask := serial.ToTypedMessage(&proxyprotocol.Config{Version: version}) + for _, existing := range config.Tcpmasks { + if existing.Type == mask.Type { + return + } + } + // Put the header directly on the socket, before the other masks. + config.Tcpmasks = append(config.Tcpmasks, mask) +} + type Filter struct { BlockedSourceIPs []string `json:"blockedSourceIPs"` AllowedSourceIPs []string `json:"allowedSourceIPs"` diff --git a/infra/conf/xray.go b/infra/conf/xray.go index 2c94ce55c..3a88eaca7 100644 --- a/infra/conf/xray.go +++ b/infra/conf/xray.go @@ -407,7 +407,16 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) { return nil, errors.New("the masque transport can only be used by the masque outbound") } - if fc, ok := ts.(*freedom.Config); ok { + if _, ok := rawConfig.(*BlackholeConfig); ok { + // The legacy blackhole outbound never used its transport settings. + senderSettings.StreamSettings = nil + } else if fc, ok := ts.(*freedom.Config); ok { + if legacy := rawConfig.(*FreedomConfig); legacy.ProxyProtocol > 0 && legacy.ProxyProtocol <= 2 { + if senderSettings.StreamSettings == nil { + senderSettings.StreamSettings = &internet.StreamConfig{} + } + addProxyProtocolMask(senderSettings.StreamSettings, legacy.ProxyProtocol) + } if senderSettings.StreamSettings != nil && senderSettings.StreamSettings.SocketSettings != nil && senderSettings.StreamSettings.SocketSettings.AddressPortStrategy != internet.AddressPortStrategy_None { diff --git a/main/distro/all/all.go b/main/distro/all/all.go index 840d0e146..712f3eb77 100644 --- a/main/distro/all/all.go +++ b/main/distro/all/all.go @@ -35,7 +35,6 @@ import ( _ "github.com/xtls/xray-core/app/observatory" // Inbound and outbound proxies. - _ "github.com/xtls/xray-core/proxy/blackhole" _ "github.com/xtls/xray-core/proxy/dns" _ "github.com/xtls/xray-core/proxy/dokodemo" _ "github.com/xtls/xray-core/proxy/freedom" diff --git a/proxy/blackhole/blackhole.go b/proxy/blackhole/blackhole.go deleted file mode 100644 index ee0ee7b08..000000000 --- a/proxy/blackhole/blackhole.go +++ /dev/null @@ -1,88 +0,0 @@ -// Package blackhole is an outbound handler that blocks all connections. -package blackhole - -import ( - "bytes" - "context" - "net/http" - "time" - - "github.com/xtls/xray-core/common" - "github.com/xtls/xray-core/common/buf" - "github.com/xtls/xray-core/common/dice" - "github.com/xtls/xray-core/common/errors" - "github.com/xtls/xray-core/common/net" - "github.com/xtls/xray-core/common/session" - "github.com/xtls/xray-core/common/signal" - "github.com/xtls/xray-core/transport" - "github.com/xtls/xray-core/transport/internet" -) - -// Handler is an outbound connection that silently swallow the entire payload. -type Handler struct { - response []byte -} - -var http403response = http.Response{ - StatusCode: 403, - ProtoMajor: 1, - ProtoMinor: 1, - Header: http.Header{ - "Connection": {"close"}, - "Cache-Control": {"max-age=3600, public"}, - }, -} - -// New creates a new blackhole handler. -func New(ctx context.Context, config *Config) (*Handler, error) { - response := []byte{} - if config.Response != nil { - switch config.Response.Type { - case "", "none": - case "http": - var data bytes.Buffer - common.Must(http403response.Write(&data)) - response = data.Bytes() - case "custom": - response = config.Response.CustomResponseData - default: - return nil, errors.New("unknown blackhole response: " + config.Response.Type) - } - } - return &Handler{ - response: response, - }, nil -} - -// Process implements OutboundHandler.Dispatch(). -func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { - outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds)-1] - ob.Name = "blackhole" - - if len(h.response) > 0 { - mbc := buf.MultiBufferContainer{} - common.Must2(mbc.Write(h.response)) - link.Writer.WriteMultiBuffer(mbc.MultiBuffer) - // Sleep a little here to make sure the response is sent to client. - time.Sleep(time.Second) - } - defer common.Interrupt(link.Writer) - defer common.Interrupt(link.Reader) - // wait to drain all the possible incoming UDP data - if ob.Target.Network == net.Network_UDP { - ctx, cancel := context.WithCancel(ctx) - timer := signal.CancelAfterInactivity(ctx, func() { - cancel() - }, time.Duration(30+dice.Roll(61))*time.Second) - go buf.Copy(link.Reader, buf.Discard, buf.UpdateActivity(timer)) - <-ctx.Done() - } - return nil -} - -func init() { - common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { - return New(ctx, config.(*Config)) - })) -} diff --git a/proxy/blackhole/blackhole_test.go b/proxy/blackhole/blackhole_test.go deleted file mode 100644 index ac1822757..000000000 --- a/proxy/blackhole/blackhole_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package blackhole_test - -import ( - "bufio" - "bytes" - "context" - "crypto/rand" - "net/http" - "testing" - - "github.com/xtls/xray-core/common" - "github.com/xtls/xray-core/common/buf" - "github.com/xtls/xray-core/common/session" - "github.com/xtls/xray-core/proxy/blackhole" - "github.com/xtls/xray-core/transport" - "github.com/xtls/xray-core/transport/pipe" -) - -func TestBlackholeHTTPResponse(t *testing.T) { - ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{}}) - handler, err := blackhole.New(ctx, &blackhole.Config{ - Response: &blackhole.Response{Type: "http"}, - }) - common.Must(err) - - reader, writer := pipe.New(pipe.WithoutSizeLimit()) - - dataCh := make(chan buf.MultiBuffer, 1) - go func() { - mb := common.Must2(reader.ReadMultiBuffer()) - dataCh <- mb - }() - link := transport.Link{ - Reader: reader, - Writer: writer, - } - common.Must(handler.Process(ctx, &link, nil)) - mb := <-dataCh - data := make([]byte, mb.Len()) - mb.Copy(data) - resp := common.Must2(http.ReadResponse(bufio.NewReader(bytes.NewBuffer(data)), nil)) - if resp.StatusCode != 403 { - t.Errorf("expected 403 response, got %d", resp.StatusCode) - } -} - -func TestBlackholeCustomResponse(t *testing.T) { - ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{}}) - // slightly bigger than a buffer - expected := make([]byte, buf.Size+1000) - if _, err := rand.Read(expected); err != nil { - t.Fatal(err) - } - handler, err := blackhole.New(ctx, &blackhole.Config{ - Response: &blackhole.Response{ - Type: "custom", - CustomResponseData: expected, - }, - }) - common.Must(err) - - reader, writer := pipe.New(pipe.WithoutSizeLimit()) - var actual buf.MultiBuffer - var rerr error - go func() { - actual, rerr = reader.ReadMultiBuffer() - }() - - link := transport.Link{Reader: reader, Writer: writer} - common.Must(handler.Process(ctx, &link, nil)) - common.Must(rerr) - - if actual.String() != string(expected) { - t.Errorf("custom response mismatch") - } -} diff --git a/proxy/blackhole/config.pb.go b/proxy/blackhole/config.pb.go deleted file mode 100644 index 74f6d1e02..000000000 --- a/proxy/blackhole/config.pb.go +++ /dev/null @@ -1,180 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.36.12 -// protoc (unknown) -// source: proxy/blackhole/config.proto - -package blackhole - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" - unsafe "unsafe" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -type Response struct { - state protoimpl.MessageState `protogen:"open.v1"` - Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` - CustomResponseData []byte `protobuf:"bytes,2,opt,name=custom_response_data,json=customResponseData,proto3" json:"custom_response_data,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *Response) Reset() { - *x = Response{} - mi := &file_proxy_blackhole_config_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *Response) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Response) ProtoMessage() {} - -func (x *Response) ProtoReflect() protoreflect.Message { - mi := &file_proxy_blackhole_config_proto_msgTypes[0] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use Response.ProtoReflect.Descriptor instead. -func (*Response) Descriptor() ([]byte, []int) { - return file_proxy_blackhole_config_proto_rawDescGZIP(), []int{0} -} - -func (x *Response) GetType() string { - if x != nil { - return x.Type - } - return "" -} - -func (x *Response) GetCustomResponseData() []byte { - if x != nil { - return x.CustomResponseData - } - return nil -} - -type Config struct { - state protoimpl.MessageState `protogen:"open.v1"` - Response *Response `protobuf:"bytes,1,opt,name=response,proto3" json:"response,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *Config) Reset() { - *x = Config{} - mi := &file_proxy_blackhole_config_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *Config) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Config) ProtoMessage() {} - -func (x *Config) ProtoReflect() protoreflect.Message { - mi := &file_proxy_blackhole_config_proto_msgTypes[1] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use Config.ProtoReflect.Descriptor instead. -func (*Config) Descriptor() ([]byte, []int) { - return file_proxy_blackhole_config_proto_rawDescGZIP(), []int{1} -} - -func (x *Config) GetResponse() *Response { - if x != nil { - return x.Response - } - return nil -} - -var File_proxy_blackhole_config_proto protoreflect.FileDescriptor - -const file_proxy_blackhole_config_proto_rawDesc = "" + - "\n" + - "\x1cproxy/blackhole/config.proto\x12\x14xray.proxy.blackhole\"P\n" + - "\bResponse\x12\x12\n" + - "\x04type\x18\x01 \x01(\tR\x04type\x120\n" + - "\x14custom_response_data\x18\x02 \x01(\fR\x12customResponseData\"D\n" + - "\x06Config\x12:\n" + - "\bresponse\x18\x01 \x01(\v2\x1e.xray.proxy.blackhole.ResponseR\bresponseB^\n" + - "\x18com.xray.proxy.blackholeP\x01Z)github.com/xtls/xray-core/proxy/blackhole\xaa\x02\x14Xray.Proxy.Blackholeb\x06proto3" - -var ( - file_proxy_blackhole_config_proto_rawDescOnce sync.Once - file_proxy_blackhole_config_proto_rawDescData []byte -) - -func file_proxy_blackhole_config_proto_rawDescGZIP() []byte { - file_proxy_blackhole_config_proto_rawDescOnce.Do(func() { - file_proxy_blackhole_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_blackhole_config_proto_rawDesc), len(file_proxy_blackhole_config_proto_rawDesc))) - }) - return file_proxy_blackhole_config_proto_rawDescData -} - -var file_proxy_blackhole_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2) -var file_proxy_blackhole_config_proto_goTypes = []any{ - (*Response)(nil), // 0: xray.proxy.blackhole.Response - (*Config)(nil), // 1: xray.proxy.blackhole.Config -} -var file_proxy_blackhole_config_proto_depIdxs = []int32{ - 0, // 0: xray.proxy.blackhole.Config.response:type_name -> xray.proxy.blackhole.Response - 1, // [1:1] is the sub-list for method output_type - 1, // [1:1] is the sub-list for method input_type - 1, // [1:1] is the sub-list for extension type_name - 1, // [1:1] is the sub-list for extension extendee - 0, // [0:1] is the sub-list for field type_name -} - -func init() { file_proxy_blackhole_config_proto_init() } -func file_proxy_blackhole_config_proto_init() { - if File_proxy_blackhole_config_proto != nil { - return - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_blackhole_config_proto_rawDesc), len(file_proxy_blackhole_config_proto_rawDesc)), - NumEnums: 0, - NumMessages: 2, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_proxy_blackhole_config_proto_goTypes, - DependencyIndexes: file_proxy_blackhole_config_proto_depIdxs, - MessageInfos: file_proxy_blackhole_config_proto_msgTypes, - }.Build() - File_proxy_blackhole_config_proto = out.File - file_proxy_blackhole_config_proto_goTypes = nil - file_proxy_blackhole_config_proto_depIdxs = nil -} diff --git a/proxy/blackhole/config.proto b/proxy/blackhole/config.proto deleted file mode 100644 index 93b4d8e7b..000000000 --- a/proxy/blackhole/config.proto +++ /dev/null @@ -1,16 +0,0 @@ -syntax = "proto3"; - -package xray.proxy.blackhole; -option csharp_namespace = "Xray.Proxy.Blackhole"; -option go_package = "github.com/xtls/xray-core/proxy/blackhole"; -option java_package = "com.xray.proxy.blackhole"; -option java_multiple_files = true; - -message Response { - string type = 1; - bytes custom_response_data = 2; -} - -message Config { - Response response = 1; -} diff --git a/proxy/blackhole/config_test.go b/proxy/blackhole/config_test.go deleted file mode 100644 index f54cb0154..000000000 --- a/proxy/blackhole/config_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package blackhole_test - -import ( - "context" - "testing" - - "github.com/xtls/xray-core/common" - "github.com/xtls/xray-core/proxy/blackhole" -) - -func TestHTTPResponse(t *testing.T) { - handler, err := blackhole.New(context.Background(), &blackhole.Config{ - Response: &blackhole.Response{Type: "http"}, - }) - common.Must(err) - if handler == nil { - t.Error("expected HTTP response handler") - } -} diff --git a/proxy/freedom/config.pb.go b/proxy/freedom/config.pb.go index 4bc9c1849..ced63563e 100644 --- a/proxy/freedom/config.pb.go +++ b/proxy/freedom/config.pb.go @@ -352,32 +352,28 @@ func (x *Range) GetMax() uint64 { return 0 } -type FinalRuleConfig struct { - state protoimpl.MessageState `protogen:"open.v1"` - Action RuleAction `protobuf:"varint,1,opt,name=action,proto3,enum=xray.proxy.freedom.RuleAction" json:"action,omitempty"` - Networks []net.Network `protobuf:"varint,2,rep,packed,name=networks,proto3,enum=xray.common.net.Network" json:"networks,omitempty"` - PortList *net.PortList `protobuf:"bytes,3,opt,name=port_list,json=portList,proto3" json:"port_list,omitempty"` - Ip []*geodata.IPRule `protobuf:"bytes,4,rep,name=ip,proto3" json:"ip,omitempty"` - Delay *Range `protobuf:"bytes,5,opt,name=delay,proto3" json:"delay,omitempty"` - LogLevel *log.Severity `protobuf:"varint,6,opt,name=log_level,json=logLevel,proto3,enum=xray.common.log.Severity,oneof" json:"log_level,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache +type Reply struct { + state protoimpl.MessageState `protogen:"open.v1"` + Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` + CustomResponseData []byte `protobuf:"bytes,2,opt,name=custom_response_data,json=customResponseData,proto3" json:"custom_response_data,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } -func (x *FinalRuleConfig) Reset() { - *x = FinalRuleConfig{} +func (x *Reply) Reset() { + *x = Reply{} mi := &file_proxy_freedom_config_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *FinalRuleConfig) String() string { +func (x *Reply) String() string { return protoimpl.X.MessageStringOf(x) } -func (*FinalRuleConfig) ProtoMessage() {} +func (*Reply) ProtoMessage() {} -func (x *FinalRuleConfig) ProtoReflect() protoreflect.Message { +func (x *Reply) ProtoReflect() protoreflect.Message { mi := &file_proxy_freedom_config_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) @@ -389,69 +385,132 @@ func (x *FinalRuleConfig) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use FinalRuleConfig.ProtoReflect.Descriptor instead. -func (*FinalRuleConfig) Descriptor() ([]byte, []int) { +// Deprecated: Use Reply.ProtoReflect.Descriptor instead. +func (*Reply) Descriptor() ([]byte, []int) { return file_proxy_freedom_config_proto_rawDescGZIP(), []int{4} } -func (x *FinalRuleConfig) GetAction() RuleAction { +func (x *Reply) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *Reply) GetCustomResponseData() []byte { + if x != nil { + return x.CustomResponseData + } + return nil +} + +type FirewallConfig struct { + state protoimpl.MessageState `protogen:"open.v1"` + Action RuleAction `protobuf:"varint,1,opt,name=action,proto3,enum=xray.proxy.freedom.RuleAction" json:"action,omitempty"` + Networks []net.Network `protobuf:"varint,2,rep,packed,name=networks,proto3,enum=xray.common.net.Network" json:"networks,omitempty"` + PortList *net.PortList `protobuf:"bytes,3,opt,name=port_list,json=portList,proto3" json:"port_list,omitempty"` + Ip []*geodata.IPRule `protobuf:"bytes,4,rep,name=ip,proto3" json:"ip,omitempty"` + Delay *Range `protobuf:"bytes,5,opt,name=delay,proto3" json:"delay,omitempty"` + LogLevel *log.Severity `protobuf:"varint,6,opt,name=log_level,json=logLevel,proto3,enum=xray.common.log.Severity,oneof" json:"log_level,omitempty"` + Reply *Reply `protobuf:"bytes,7,opt,name=reply,proto3" json:"reply,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FirewallConfig) Reset() { + *x = FirewallConfig{} + mi := &file_proxy_freedom_config_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FirewallConfig) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FirewallConfig) ProtoMessage() {} + +func (x *FirewallConfig) ProtoReflect() protoreflect.Message { + mi := &file_proxy_freedom_config_proto_msgTypes[5] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FirewallConfig.ProtoReflect.Descriptor instead. +func (*FirewallConfig) Descriptor() ([]byte, []int) { + return file_proxy_freedom_config_proto_rawDescGZIP(), []int{5} +} + +func (x *FirewallConfig) GetAction() RuleAction { if x != nil { return x.Action } return RuleAction_Allow } -func (x *FinalRuleConfig) GetNetworks() []net.Network { +func (x *FirewallConfig) GetNetworks() []net.Network { if x != nil { return x.Networks } return nil } -func (x *FinalRuleConfig) GetPortList() *net.PortList { +func (x *FirewallConfig) GetPortList() *net.PortList { if x != nil { return x.PortList } return nil } -func (x *FinalRuleConfig) GetIp() []*geodata.IPRule { +func (x *FirewallConfig) GetIp() []*geodata.IPRule { if x != nil { return x.Ip } return nil } -func (x *FinalRuleConfig) GetDelay() *Range { +func (x *FirewallConfig) GetDelay() *Range { if x != nil { return x.Delay } return nil } -func (x *FinalRuleConfig) GetLogLevel() log.Severity { +func (x *FirewallConfig) GetLogLevel() log.Severity { if x != nil && x.LogLevel != nil { return *x.LogLevel } return log.Severity(0) } +func (x *FirewallConfig) GetReply() *Reply { + if x != nil { + return x.Reply + } + return nil +} + type Config struct { state protoimpl.MessageState `protogen:"open.v1"` DomainStrategy internet.DomainStrategy `protobuf:"varint,1,opt,name=domain_strategy,json=domainStrategy,proto3,enum=xray.transport.internet.DomainStrategy" json:"domain_strategy,omitempty"` DestinationOverride *DestinationOverride `protobuf:"bytes,3,opt,name=destination_override,json=destinationOverride,proto3" json:"destination_override,omitempty"` UserLevel uint32 `protobuf:"varint,4,opt,name=user_level,json=userLevel,proto3" json:"user_level,omitempty"` Fragment *Fragment `protobuf:"bytes,5,opt,name=fragment,proto3" json:"fragment,omitempty"` - ProxyProtocol uint32 `protobuf:"varint,6,opt,name=proxy_protocol,json=proxyProtocol,proto3" json:"proxy_protocol,omitempty"` Noises []*Noise `protobuf:"bytes,7,rep,name=noises,proto3" json:"noises,omitempty"` - FinalRules []*FinalRuleConfig `protobuf:"bytes,8,rep,name=final_rules,json=finalRules,proto3" json:"final_rules,omitempty"` + Firewall []*FirewallConfig `protobuf:"bytes,8,rep,name=firewall,proto3" json:"firewall,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Config) Reset() { *x = Config{} - mi := &file_proxy_freedom_config_proto_msgTypes[5] + mi := &file_proxy_freedom_config_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -463,7 +522,7 @@ func (x *Config) String() string { func (*Config) ProtoMessage() {} func (x *Config) ProtoReflect() protoreflect.Message { - mi := &file_proxy_freedom_config_proto_msgTypes[5] + mi := &file_proxy_freedom_config_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -476,7 +535,7 @@ func (x *Config) ProtoReflect() protoreflect.Message { // Deprecated: Use Config.ProtoReflect.Descriptor instead. func (*Config) Descriptor() ([]byte, []int) { - return file_proxy_freedom_config_proto_rawDescGZIP(), []int{5} + return file_proxy_freedom_config_proto_rawDescGZIP(), []int{6} } func (x *Config) GetDomainStrategy() internet.DomainStrategy { @@ -507,13 +566,6 @@ func (x *Config) GetFragment() *Fragment { return nil } -func (x *Config) GetProxyProtocol() uint32 { - if x != nil { - return x.ProxyProtocol - } - return 0 -} - func (x *Config) GetNoises() []*Noise { if x != nil { return x.Noises @@ -521,9 +573,9 @@ func (x *Config) GetNoises() []*Noise { return nil } -func (x *Config) GetFinalRules() []*FinalRuleConfig { +func (x *Config) GetFirewall() []*FirewallConfig { if x != nil { - return x.FinalRules + return x.Firewall } return nil } @@ -558,26 +610,28 @@ const file_proxy_freedom_config_proto_rawDesc = "" + "\bapply_to\x18\x06 \x01(\tR\aapplyTo\"+\n" + "\x05Range\x12\x10\n" + "\x03min\x18\x01 \x01(\x04R\x03min\x12\x10\n" + - "\x03max\x18\x02 \x01(\x04R\x03max\"\xe0\x02\n" + - "\x0fFinalRuleConfig\x126\n" + + "\x03max\x18\x02 \x01(\x04R\x03max\"M\n" + + "\x05Reply\x12\x12\n" + + "\x04type\x18\x01 \x01(\tR\x04type\x120\n" + + "\x14custom_response_data\x18\x02 \x01(\fR\x12customResponseData\"\x90\x03\n" + + "\x0eFirewallConfig\x126\n" + "\x06action\x18\x01 \x01(\x0e2\x1e.xray.proxy.freedom.RuleActionR\x06action\x124\n" + "\bnetworks\x18\x02 \x03(\x0e2\x18.xray.common.net.NetworkR\bnetworks\x126\n" + "\tport_list\x18\x03 \x01(\v2\x19.xray.common.net.PortListR\bportList\x12+\n" + "\x02ip\x18\x04 \x03(\v2\x1b.xray.common.geodata.IPRuleR\x02ip\x12/\n" + "\x05delay\x18\x05 \x01(\v2\x19.xray.proxy.freedom.RangeR\x05delay\x12;\n" + - "\tlog_level\x18\x06 \x01(\x0e2\x19.xray.common.log.SeverityH\x00R\blogLevel\x88\x01\x01B\f\n" + + "\tlog_level\x18\x06 \x01(\x0e2\x19.xray.common.log.SeverityH\x00R\blogLevel\x88\x01\x01\x12/\n" + + "\x05reply\x18\a \x01(\v2\x19.xray.proxy.freedom.ReplyR\x05replyB\f\n" + "\n" + - "_log_level\"\xaf\x03\n" + + "_log_level\"\x88\x03\n" + "\x06Config\x12P\n" + "\x0fdomain_strategy\x18\x01 \x01(\x0e2'.xray.transport.internet.DomainStrategyR\x0edomainStrategy\x12Z\n" + "\x14destination_override\x18\x03 \x01(\v2'.xray.proxy.freedom.DestinationOverrideR\x13destinationOverride\x12\x1d\n" + "\n" + "user_level\x18\x04 \x01(\rR\tuserLevel\x128\n" + - "\bfragment\x18\x05 \x01(\v2\x1c.xray.proxy.freedom.FragmentR\bfragment\x12%\n" + - "\x0eproxy_protocol\x18\x06 \x01(\rR\rproxyProtocol\x121\n" + - "\x06noises\x18\a \x03(\v2\x19.xray.proxy.freedom.NoiseR\x06noises\x12D\n" + - "\vfinal_rules\x18\b \x03(\v2#.xray.proxy.freedom.FinalRuleConfigR\n" + - "finalRules*\"\n" + + "\bfragment\x18\x05 \x01(\v2\x1c.xray.proxy.freedom.FragmentR\bfragment\x121\n" + + "\x06noises\x18\a \x03(\v2\x19.xray.proxy.freedom.NoiseR\x06noises\x12>\n" + + "\bfirewall\x18\b \x03(\v2\".xray.proxy.freedom.FirewallConfigR\bfirewallJ\x04\b\x06\x10\a*\"\n" + "\n" + "RuleAction\x12\t\n" + "\x05Allow\x10\x00\x12\t\n" + @@ -597,40 +651,42 @@ func file_proxy_freedom_config_proto_rawDescGZIP() []byte { } var file_proxy_freedom_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_proxy_freedom_config_proto_msgTypes = make([]protoimpl.MessageInfo, 6) +var file_proxy_freedom_config_proto_msgTypes = make([]protoimpl.MessageInfo, 7) var file_proxy_freedom_config_proto_goTypes = []any{ (RuleAction)(0), // 0: xray.proxy.freedom.RuleAction (*DestinationOverride)(nil), // 1: xray.proxy.freedom.DestinationOverride (*Fragment)(nil), // 2: xray.proxy.freedom.Fragment (*Noise)(nil), // 3: xray.proxy.freedom.Noise (*Range)(nil), // 4: xray.proxy.freedom.Range - (*FinalRuleConfig)(nil), // 5: xray.proxy.freedom.FinalRuleConfig - (*Config)(nil), // 6: xray.proxy.freedom.Config - (*protocol.ServerEndpoint)(nil), // 7: xray.common.protocol.ServerEndpoint - (net.Network)(0), // 8: xray.common.net.Network - (*net.PortList)(nil), // 9: xray.common.net.PortList - (*geodata.IPRule)(nil), // 10: xray.common.geodata.IPRule - (log.Severity)(0), // 11: xray.common.log.Severity - (internet.DomainStrategy)(0), // 12: xray.transport.internet.DomainStrategy + (*Reply)(nil), // 5: xray.proxy.freedom.Reply + (*FirewallConfig)(nil), // 6: xray.proxy.freedom.FirewallConfig + (*Config)(nil), // 7: xray.proxy.freedom.Config + (*protocol.ServerEndpoint)(nil), // 8: xray.common.protocol.ServerEndpoint + (net.Network)(0), // 9: xray.common.net.Network + (*net.PortList)(nil), // 10: xray.common.net.PortList + (*geodata.IPRule)(nil), // 11: xray.common.geodata.IPRule + (log.Severity)(0), // 12: xray.common.log.Severity + (internet.DomainStrategy)(0), // 13: xray.transport.internet.DomainStrategy } var file_proxy_freedom_config_proto_depIdxs = []int32{ - 7, // 0: xray.proxy.freedom.DestinationOverride.server:type_name -> xray.common.protocol.ServerEndpoint - 0, // 1: xray.proxy.freedom.FinalRuleConfig.action:type_name -> xray.proxy.freedom.RuleAction - 8, // 2: xray.proxy.freedom.FinalRuleConfig.networks:type_name -> xray.common.net.Network - 9, // 3: xray.proxy.freedom.FinalRuleConfig.port_list:type_name -> xray.common.net.PortList - 10, // 4: xray.proxy.freedom.FinalRuleConfig.ip:type_name -> xray.common.geodata.IPRule - 4, // 5: xray.proxy.freedom.FinalRuleConfig.delay:type_name -> xray.proxy.freedom.Range - 11, // 6: xray.proxy.freedom.FinalRuleConfig.log_level:type_name -> xray.common.log.Severity - 12, // 7: xray.proxy.freedom.Config.domain_strategy:type_name -> xray.transport.internet.DomainStrategy - 1, // 8: xray.proxy.freedom.Config.destination_override:type_name -> xray.proxy.freedom.DestinationOverride - 2, // 9: xray.proxy.freedom.Config.fragment:type_name -> xray.proxy.freedom.Fragment - 3, // 10: xray.proxy.freedom.Config.noises:type_name -> xray.proxy.freedom.Noise - 5, // 11: xray.proxy.freedom.Config.final_rules:type_name -> xray.proxy.freedom.FinalRuleConfig - 12, // [12:12] is the sub-list for method output_type - 12, // [12:12] is the sub-list for method input_type - 12, // [12:12] is the sub-list for extension type_name - 12, // [12:12] is the sub-list for extension extendee - 0, // [0:12] is the sub-list for field type_name + 8, // 0: xray.proxy.freedom.DestinationOverride.server:type_name -> xray.common.protocol.ServerEndpoint + 0, // 1: xray.proxy.freedom.FirewallConfig.action:type_name -> xray.proxy.freedom.RuleAction + 9, // 2: xray.proxy.freedom.FirewallConfig.networks:type_name -> xray.common.net.Network + 10, // 3: xray.proxy.freedom.FirewallConfig.port_list:type_name -> xray.common.net.PortList + 11, // 4: xray.proxy.freedom.FirewallConfig.ip:type_name -> xray.common.geodata.IPRule + 4, // 5: xray.proxy.freedom.FirewallConfig.delay:type_name -> xray.proxy.freedom.Range + 12, // 6: xray.proxy.freedom.FirewallConfig.log_level:type_name -> xray.common.log.Severity + 5, // 7: xray.proxy.freedom.FirewallConfig.reply:type_name -> xray.proxy.freedom.Reply + 13, // 8: xray.proxy.freedom.Config.domain_strategy:type_name -> xray.transport.internet.DomainStrategy + 1, // 9: xray.proxy.freedom.Config.destination_override:type_name -> xray.proxy.freedom.DestinationOverride + 2, // 10: xray.proxy.freedom.Config.fragment:type_name -> xray.proxy.freedom.Fragment + 3, // 11: xray.proxy.freedom.Config.noises:type_name -> xray.proxy.freedom.Noise + 6, // 12: xray.proxy.freedom.Config.firewall:type_name -> xray.proxy.freedom.FirewallConfig + 13, // [13:13] is the sub-list for method output_type + 13, // [13:13] is the sub-list for method input_type + 13, // [13:13] is the sub-list for extension type_name + 13, // [13:13] is the sub-list for extension extendee + 0, // [0:13] is the sub-list for field type_name } func init() { file_proxy_freedom_config_proto_init() } @@ -638,14 +694,14 @@ func file_proxy_freedom_config_proto_init() { if File_proxy_freedom_config_proto != nil { return } - file_proxy_freedom_config_proto_msgTypes[4].OneofWrappers = []any{} + file_proxy_freedom_config_proto_msgTypes[5].OneofWrappers = []any{} type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_freedom_config_proto_rawDesc), len(file_proxy_freedom_config_proto_rawDesc)), NumEnums: 1, - NumMessages: 6, + NumMessages: 7, NumExtensions: 0, NumServices: 0, }, diff --git a/proxy/freedom/config.proto b/proxy/freedom/config.proto index 9a218877d..2a6dd33d5 100644 --- a/proxy/freedom/config.proto +++ b/proxy/freedom/config.proto @@ -47,21 +47,27 @@ enum RuleAction { Block = 1; } -message FinalRuleConfig { +message Reply { + string type = 1; + bytes custom_response_data = 2; +} + +message FirewallConfig { RuleAction action = 1; repeated xray.common.net.Network networks = 2; xray.common.net.PortList port_list = 3; repeated xray.common.geodata.IPRule ip = 4; Range delay = 5; optional xray.common.log.Severity log_level = 6; + Reply reply = 7; } message Config { + reserved 6; xray.transport.internet.DomainStrategy domain_strategy = 1; DestinationOverride destination_override = 3; uint32 user_level = 4; Fragment fragment = 5; - uint32 proxy_protocol = 6; repeated Noise noises = 7; - repeated FinalRuleConfig final_rules = 8; + repeated FirewallConfig firewall = 8; } diff --git a/proxy/freedom/freedom.go b/proxy/freedom/freedom.go index 6215647a2..5a19d050b 100644 --- a/proxy/freedom/freedom.go +++ b/proxy/freedom/freedom.go @@ -1,14 +1,15 @@ package freedom import ( + "bytes" "context" "crypto/rand" "io" + "net/http" "strings" "sync/atomic" "time" - "github.com/pires/go-proxyproto" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/crypto" @@ -35,10 +36,20 @@ import ( var ( useSplice atomic.Bool allNetworks [8]bool - defaultBlockPrivateRule *FinalRule - defaultBlockAllRule *FinalRule + defaultBlockPrivateRule *Firewall + defaultBlockAllRule *Firewall ) +var http403response = http.Response{ + StatusCode: 403, + ProtoMajor: 1, + ProtoMinor: 1, + Header: http.Header{ + "Connection": {"close"}, + "Cache-Control": {"max-age=3600, public"}, + }, +} + func reloadEnvSettings() error { const defaultFlagValue = "NOT_DEFINED_AT_ALL" value := platform.NewEnvFlag(platform.UseFreedomSplice).GetValue(func() string { return defaultFlagValue }) @@ -72,45 +83,60 @@ func init() { allNetworks[i] = true } - defaultBlockPrivateRule = &FinalRule{ + defaultBlockPrivateRule = &Firewall{ action: RuleAction_Block, network: allNetworks, ip: geodata.GetPrivateIPMatcher(), logLevel: log.Severity_Warning.Enum(), } - defaultBlockAllRule = &FinalRule{ + defaultBlockAllRule = &Firewall{ action: RuleAction_Block, network: allNetworks, logLevel: log.Severity_Warning.Enum(), } } -type FinalRule struct { +type Firewall struct { action RuleAction network [8]bool port net.MemoryPortList ip geodata.IPMatcher delay *Range logLevel *log.Severity + reply []byte } // Handler handles Freedom connections. type Handler struct { policyManager policy.Manager config *Config - finalRules []*FinalRule + firewall []*Firewall resolveStrategy internet.DomainStrategy usesDialerProxy bool } -func buildFinalRule(config *FinalRuleConfig) (*FinalRule, error) { - rule := &FinalRule{ +func buildRule(config *FirewallConfig) (*Firewall, error) { + rule := &Firewall{ action: config.GetAction(), delay: config.GetDelay(), logLevel: config.LogLevel, } + if config.Reply != nil { + switch config.Reply.Type { + case "", "none": + case "http": + var data bytes.Buffer + common.Must(http403response.Write(&data)) + rule.reply = data.Bytes() + case "custom": + rule.reply = config.Reply.CustomResponseData + default: + return nil, errors.New("unknown firewall reply: " + config.Reply.Type) + } + } + if len(config.Networks) == 0 { rule.network = allNetworks } else { @@ -134,25 +160,25 @@ func buildFinalRule(config *FinalRuleConfig) (*FinalRule, error) { return rule, nil } -func (r *FinalRule) matchNetwork(network net.Network) bool { +func (r *Firewall) matchNetwork(network net.Network) bool { return r.network[int(network)] } -func (r *FinalRule) matchPort(port net.Port) bool { +func (r *Firewall) matchPort(port net.Port) bool { if len(r.port) == 0 { return true } return r.port.Contains(port) } -func (r *FinalRule) matchIP(addr net.Address) bool { +func (r *Firewall) matchIP(addr net.Address) bool { if r.ip == nil { return true } return addr != nil && addr.Family().IsIP() && r.ip.Match(addr.IP()) } -func (r *FinalRule) Apply(network net.Network, address net.Address, port net.Port) bool { +func (r *Firewall) Apply(network net.Network, address net.Address, port net.Port) bool { if !r.matchNetwork(network) { return false } @@ -162,7 +188,7 @@ func (r *FinalRule) Apply(network net.Network, address net.Address, port net.Por return r.matchIP(address) } -func getDefaultFinalRule(inbound *session.Inbound) *FinalRule { +func getDefaultRule(inbound *session.Inbound) *Firewall { if inbound == nil { return nil } @@ -179,8 +205,8 @@ func getDefaultFinalRule(inbound *session.Inbound) *FinalRule { return nil } -func (h *Handler) matchFinalRule(network net.Network, address net.Address, port net.Port, defaultRule *FinalRule) *FinalRule { - for _, rule := range h.finalRules { +func (h *Handler) matchRule(network net.Network, address net.Address, port net.Port, defaultRule *Firewall) *Firewall { + for _, rule := range h.firewall { if rule.Apply(network, address, port) { return rule } @@ -195,19 +221,19 @@ func (h *Handler) matchFinalRule(network net.Network, address net.Address, port func (h *Handler) Init(config *Config, pm policy.Manager) error { h.config = config h.policyManager = pm - if h.usesDialerProxy { // freedom is not the final outbound, final rules do not apply - if len(config.FinalRules) > 0 { - errors.LogWarning(context.Background(), `The "finalRules" setting is ignored when "sockopt.dialerProxy" is set, since freedom is not the final outbound.`) + if h.usesDialerProxy { // freedom is not the final outbound, firewall does not apply + if len(config.Firewall) > 0 { + errors.LogWarning(context.Background(), `The "firewall" setting is ignored when "sockopt.dialerProxy" is set, since freedom is not the final outbound.`) } return nil } - h.finalRules = make([]*FinalRule, 0, len(config.FinalRules)) - for _, rc := range config.FinalRules { - rule, err := buildFinalRule(rc) + h.firewall = make([]*Firewall, 0, len(config.Firewall)) + for _, rc := range config.Firewall { + rule, err := buildRule(rc) if err != nil { - return errors.New("failed to build final rule").Base(err) + return errors.New("failed to build firewall rule").Base(err) } - h.finalRules = append(h.finalRules, rule) + h.firewall = append(h.firewall, rule) } return nil } @@ -217,7 +243,7 @@ func (h *Handler) policy() policy.Session { return p } -func (r *FinalRule) blockDuration() time.Duration { +func (r *Firewall) blockDuration() time.Duration { min := uint64(30) max := uint64(90) if r.delay != nil { @@ -231,7 +257,7 @@ func (r *FinalRule) blockDuration() time.Duration { return time.Duration(min+uint64(dice.Roll(int(span+1)))) * time.Second } -func (r *FinalRule) log(ctx context.Context, msg ...interface{}) { +func (r *Firewall) log(ctx context.Context, msg ...interface{}) { level := log.Severity_Info if r.logLevel != nil { level = *r.logLevel @@ -248,10 +274,17 @@ func (r *FinalRule) log(ctx context.Context, msg ...interface{}) { } } -func (h *Handler) blackhole(ctx context.Context, input buf.Reader, output buf.Writer, rule *FinalRule, dest *net.Destination) error { +func (h *Handler) blackhole(ctx context.Context, input buf.Reader, output buf.Writer, rule *Firewall, dest *net.Destination) error { delay := rule.blockDuration() - rule.log(ctx, "target blocked by a finalrule: ", *dest, ", blackholing connection for ", delay) + rule.log(ctx, "target blocked by a firewall rule: ", *dest, ", blackholing connection for ", delay) defer common.Close(output) + if len(rule.reply) > 0 { + mbc := buf.MultiBufferContainer{} + common.Must2(mbc.Write(rule.reply)) + output.WriteMultiBuffer(mbc.MultiBuffer) + // Sleep a little here to make sure the reply is sent to client. + time.Sleep(time.Second) + } done := make(chan struct{}) go func() { // a DispatchLink inbound's reader ignores Interrupt, so don't wait for this copy _ = buf.Copy(input, buf.Discard) @@ -285,10 +318,16 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte } ob.Name = "freedom" ob.CanSpliceCopy = 1 + if !h.usesDialerProxy && len(h.firewall) > 0 { + rule := h.firewall[0] + if rule.action == RuleAction_Block && rule.network == allNetworks && len(rule.port) == 0 && rule.ip == nil { + return h.blackhole(ctx, link.Reader, link.Writer, rule, &ob.Target) + } + } inbound := session.InboundFromContext(ctx) - var defaultRule *FinalRule - if !h.usesDialerProxy { // freedom is not the final outbound, final rules do not apply (and the domain is not resolved) - defaultRule = getDefaultFinalRule(inbound) + var defaultRule *Firewall + if !h.usesDialerProxy { // freedom is not the final outbound, firewall does not apply (and the domain is not resolved) + defaultRule = getDefaultRule(inbound) } destination := ob.Target @@ -316,10 +355,10 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte var conn stat.Connection var blockedDest *net.Destination - var blockedRule *FinalRule + var blockedRule *Firewall err := retry.ExponentialBackoff(5, 100).On(func() error { if destination.Address.Family().IsDomain() { - if defaultRule != nil || len(h.finalRules) > 0 { + if defaultRule != nil || len(h.firewall) > 0 { if strategy := h.resolveStrategy; strategy.HasStrategy() { ips, err := internet.LookupForIP(destination.Address.Domain(), strategy, outGateway) if err != nil { // non-force may still dial with system DNS @@ -330,7 +369,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte } for _, ip := range ips { if addr := net.IPAddress(ip); addr != nil { - if rule := h.matchFinalRule(destination.Network, addr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block { + if rule := h.matchRule(destination.Network, addr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block { blockedDest = &destination blockedDest.Address = addr blockedRule = rule @@ -345,7 +384,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte } for _, addr := range addrs { if ipAddr := net.IPAddress(addr.IP); ipAddr != nil { - if rule := h.matchFinalRule(destination.Network, ipAddr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block { + if rule := h.matchRule(destination.Network, ipAddr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block { blockedDest = &destination blockedDest.Address = ipAddr blockedRule = rule @@ -356,7 +395,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte } } } else { - if rule := h.matchFinalRule(destination.Network, destination.Address, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block { + if rule := h.matchRule(destination.Network, destination.Address, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block { blockedDest = &destination blockedRule = rule return nil @@ -377,25 +416,15 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte if blockedDest != nil { return h.blackhole(ctx, input, output, blockedRule, blockedDest) } - if destination.Address.Family().IsDomain() && (defaultRule != nil || len(h.finalRules) > 0) { + if destination.Address.Family().IsDomain() && (defaultRule != nil || len(h.firewall) > 0) { // pre-check may fail or dialer may select another IP remoteDest := net.DestinationFromAddr(conn.RemoteAddr()) - if rule := h.matchFinalRule(remoteDest.Network, remoteDest.Address, remoteDest.Port, defaultRule); rule != nil && rule.action == RuleAction_Block { + if rule := h.matchRule(remoteDest.Network, remoteDest.Address, remoteDest.Port, defaultRule); rule != nil && rule.action == RuleAction_Block { conn.Close() return h.blackhole(ctx, input, output, rule, &remoteDest) } } - if h.config.ProxyProtocol > 0 && h.config.ProxyProtocol <= 2 { - version := byte(h.config.ProxyProtocol) - srcAddr := inbound.Source.RawNetAddr() - dstAddr := conn.RemoteAddr() - header := proxyproto.HeaderProxyFromAddrs(version, srcAddr, dstAddr) - if _, err = header.WriteTo(conn); err != nil { - conn.Close() - return errors.New("failed to set PROXY protocol v", version).Base(err) - } - } defer conn.Close() errors.LogInfo(ctx, "connection opened to ", destination, ", local endpoint ", conn.LocalAddr(), ", remote endpoint ", conn.RemoteAddr()) @@ -484,7 +513,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte return nil } -func NewPacketReader(conn net.Conn, h *Handler, defaultRule *FinalRule, UDPOverride net.Destination, DialDest net.Destination) buf.Reader { +func NewPacketReader(conn net.Conn, h *Handler, defaultRule *Firewall, UDPOverride net.Destination, DialDest net.Destination) buf.Reader { iConn := conn statConn, ok := iConn.(*stat.CounterConnection) if ok { @@ -517,7 +546,7 @@ type PacketReader struct { *net.PacketConnWrapper stats.Counter Handler *Handler - DefaultRule *FinalRule + DefaultRule *Firewall IsOverridden bool InitUnchangedAddr net.Address InitChangedAddr net.Address @@ -534,7 +563,7 @@ func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) { } udpAddr := d.(*net.UDPAddr) sourceAddr := net.IPAddress(udpAddr.IP) - if rule := r.Handler.matchFinalRule(net.Network_UDP, sourceAddr, net.Port(udpAddr.Port), r.DefaultRule); rule != nil && rule.action == RuleAction_Block { + if rule := r.Handler.matchRule(net.Network_UDP, sourceAddr, net.Port(udpAddr.Port), r.DefaultRule); rule != nil && rule.action == RuleAction_Block { continue } b.Resize(0, int32(n)) @@ -559,7 +588,7 @@ func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) { } // DialDest means the dial target used in the dialer when creating conn -func NewPacketWriter(conn net.Conn, h *Handler, defaultRule *FinalRule, UDPOverride net.Destination, DialDest net.Destination, outGateway net.Address) buf.Writer { +func NewPacketWriter(conn net.Conn, h *Handler, defaultRule *Firewall, UDPOverride net.Destination, DialDest net.Destination, outGateway net.Address) buf.Writer { iConn := conn statConn, ok := iConn.(*stat.CounterConnection) if ok { @@ -593,7 +622,7 @@ type PacketWriter struct { *net.PacketConnWrapper stats.Counter *Handler - DefaultRule *FinalRule + DefaultRule *Firewall UDPOverride net.Destination // Dest of udp packets might be a domain, we will resolve them to IP @@ -652,7 +681,7 @@ func (w *PacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error { } } } - if rule := w.matchFinalRule(net.Network_UDP, b.UDP.Address, b.UDP.Port, w.DefaultRule); rule != nil && rule.action == RuleAction_Block { + if rule := w.matchRule(net.Network_UDP, b.UDP.Address, b.UDP.Port, w.DefaultRule); rule != nil && rule.action == RuleAction_Block { b.Release() continue } diff --git a/proxy/freedom/freedom_test.go b/proxy/freedom/freedom_test.go new file mode 100644 index 000000000..a7940a76a --- /dev/null +++ b/proxy/freedom/freedom_test.go @@ -0,0 +1,87 @@ +package freedom + +import ( + "bufio" + "bytes" + "context" + "net/http" + "testing" + + "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/net" + "github.com/xtls/xray-core/common/session" + "github.com/xtls/xray-core/transport" +) + +func TestUnconditionalBlockFastPath(t *testing.T) { + for _, network := range []net.Network{net.Network_TCP, net.Network_UDP} { + t.Run(network.String(), func(t *testing.T) { + const reply = "blocked" + h := new(Handler) + if err := h.Init(&Config{Firewall: []*FirewallConfig{{ + Action: RuleAction_Block, + Delay: &Range{}, + Reply: &Reply{Type: "custom", CustomResponseData: []byte(reply)}, + }}}, nil); err != nil { + t.Fatal(err) + } + ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{ + Target: net.Destination{Network: network, Address: net.DomainAddress("blocked.invalid"), Port: 443}, + }}) + var output bytes.Buffer + link := &transport.Link{ + Reader: buf.NewReader(bytes.NewReader(nil)), + Writer: &buf.BufferToBytesWriter{Writer: &output}, + } + // An unconditional block must finish without touching the dialer or resolving the domain. + if err := h.Process(ctx, link, nil); err != nil { + t.Fatal(err) + } + if output.String() != reply { + t.Fatalf("reply = %q, want %q", output.String(), reply) + } + }) + } +} + +func TestFirewallReply(t *testing.T) { + custom := bytes.Repeat([]byte("custom response"), buf.Size) + for _, test := range []struct { + name string + reply *Reply + want []byte + }{ + {name: "default"}, + {name: "none", reply: &Reply{Type: "none"}}, + {name: "http", reply: &Reply{Type: "http"}}, + {name: "custom", reply: &Reply{Type: "custom", CustomResponseData: custom}, want: custom}, + } { + t.Run(test.name, func(t *testing.T) { + rule, err := buildRule(&FirewallConfig{ + Action: RuleAction_Block, + Delay: &Range{}, + Reply: test.reply, + }) + if err != nil { + t.Fatal(err) + } + var output bytes.Buffer + dest := net.TCPDestination(net.LocalHostIP, 80) + if err := new(Handler).blackhole(context.Background(), buf.NewReader(bytes.NewReader(nil)), &buf.BufferToBytesWriter{Writer: &output}, rule, &dest); err != nil { + t.Fatal(err) + } + if test.name == "http" { + response, err := http.ReadResponse(bufio.NewReader(&output), nil) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusForbidden { + t.Fatalf("HTTP status = %d, want 403", response.StatusCode) + } + } else if !bytes.Equal(output.Bytes(), test.want) { + t.Fatalf("reply has %d bytes, want %d", output.Len(), len(test.want)) + } + }) + } +} diff --git a/proxy/tun/tun_linux_dns_route_test.go b/proxy/tun/tun_linux_dns_route_test.go index 120ef7e10..179d4896e 100644 --- a/proxy/tun/tun_linux_dns_route_test.go +++ b/proxy/tun/tun_linux_dns_route_test.go @@ -17,7 +17,6 @@ import ( "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/core" - "github.com/xtls/xray-core/proxy/blackhole" proxydns "github.com/xtls/xray-core/proxy/dns" "github.com/xtls/xray-core/proxy/freedom" ) @@ -73,7 +72,7 @@ func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.Na Outbound: []*core.OutboundHandlerConfig{ {Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})}, {Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})}, - {Tag: "block", ProxySettings: serial.ToTypedMessage(&blackhole.Config{})}, + {Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})}, }, }) if err != nil { diff --git a/testing/scenarios/command_test.go b/testing/scenarios/command_test.go index 8f82bb2b4..e14344f75 100644 --- a/testing/scenarios/command_test.go +++ b/testing/scenarios/command_test.go @@ -71,7 +71,7 @@ func TestCommanderListenConfigurationItem(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { Tag: "default-outbound", - ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}), }, }, } @@ -166,7 +166,7 @@ func TestCommanderRemoveHandler(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { Tag: "default-outbound", - ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}), }, }, } @@ -262,7 +262,7 @@ func TestCommanderListHandlers(t *testing.T) { { Tag: "default-outbound", SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{}), - ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}), }, }, } @@ -390,7 +390,7 @@ func TestCommanderAddRemoveUser(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -579,7 +579,7 @@ func TestCommanderStats(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, diff --git a/testing/scenarios/dns_test.go b/testing/scenarios/dns_test.go index a38f1b200..ee5b49e80 100644 --- a/testing/scenarios/dns_test.go +++ b/testing/scenarios/dns_test.go @@ -13,7 +13,6 @@ import ( "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/core" - "github.com/xtls/xray-core/proxy/blackhole" "github.com/xtls/xray-core/proxy/freedom" "github.com/xtls/xray-core/proxy/socks" "github.com/xtls/xray-core/testing/servers/tcp" @@ -78,7 +77,7 @@ func TestResolveIP(t *testing.T) { }, Outbound: []*core.OutboundHandlerConfig{ { - ProxySettings: serial.ToTypedMessage(&blackhole.Config{}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}), }, { Tag: "direct", diff --git a/testing/scenarios/dokodemo_test.go b/testing/scenarios/dokodemo_test.go index e160ab508..225044330 100644 --- a/testing/scenarios/dokodemo_test.go +++ b/testing/scenarios/dokodemo_test.go @@ -60,7 +60,7 @@ func TestDokodemoTCP(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -163,7 +163,7 @@ func TestDokodemoUDP(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, diff --git a/testing/scenarios/feature_test.go b/testing/scenarios/feature_test.go index fa1ff3564..692d27f49 100644 --- a/testing/scenarios/feature_test.go +++ b/testing/scenarios/feature_test.go @@ -21,7 +21,6 @@ import ( "github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/uuid" core "github.com/xtls/xray-core/core" - "github.com/xtls/xray-core/proxy/blackhole" "github.com/xtls/xray-core/proxy/dokodemo" "github.com/xtls/xray-core/proxy/freedom" v2http "github.com/xtls/xray-core/proxy/http" @@ -62,7 +61,7 @@ func TestPassiveConnection(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -123,7 +122,7 @@ func TestDialerProxy(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -152,7 +151,7 @@ func TestDialerProxy(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -254,7 +253,7 @@ func TestDialerProxyOverKCP(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -283,7 +282,7 @@ func TestDialerProxyOverKCP(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{ StreamSettings: &internet.StreamConfig{ @@ -402,11 +401,11 @@ func TestBlackhole(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { Tag: "direct", - ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}), }, { Tag: "blocked", - ProxySettings: serial.ToTypedMessage(&blackhole.Config{}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}), }, }, App: []*serial.TypedMessage{ @@ -517,7 +516,7 @@ func TestUDPConnection(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -582,7 +581,7 @@ func TestDomainSniffing(t *testing.T) { }, { Tag: "direct", - ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}), }, }, App: []*serial.TypedMessage{ @@ -669,7 +668,7 @@ func TestDialXray(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, diff --git a/testing/scenarios/http_test.go b/testing/scenarios/http_test.go index 28d0ea4e8..8e91392da 100644 --- a/testing/scenarios/http_test.go +++ b/testing/scenarios/http_test.go @@ -50,7 +50,7 @@ func TestHttpConformance(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -113,7 +113,7 @@ func TestHttpError(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -163,7 +163,7 @@ func TestHTTPConnectMethod(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -245,7 +245,7 @@ func TestHttpPost(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -317,7 +317,7 @@ func TestHttpBasicAuth(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -405,7 +405,7 @@ func TestHTTPOutboundServerFirst(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, diff --git a/testing/scenarios/masque_test.go b/testing/scenarios/masque_test.go index 876ff0d2e..5d92cf4f7 100644 --- a/testing/scenarios/masque_test.go +++ b/testing/scenarios/masque_test.go @@ -499,7 +499,7 @@ func masqueServerConfig(serverPort net.Port, certificate *tls.Certificate, h2 bo Port: uint32(dest.Port), }, }, - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), } } diff --git a/testing/scenarios/metrics_test.go b/testing/scenarios/metrics_test.go index d75384770..fed9c5d05 100644 --- a/testing/scenarios/metrics_test.go +++ b/testing/scenarios/metrics_test.go @@ -63,7 +63,7 @@ func TestMetrics(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { Tag: "default-outbound", - ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}), }, }, } diff --git a/testing/scenarios/policy_test.go b/testing/scenarios/policy_test.go index 588d07e5c..fea442831 100644 --- a/testing/scenarios/policy_test.go +++ b/testing/scenarios/policy_test.go @@ -85,7 +85,7 @@ func TestVMessClosing(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -193,7 +193,7 @@ func TestZeroBuffer(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, diff --git a/testing/scenarios/reverse_test.go b/testing/scenarios/reverse_test.go index 155386944..26ced6250 100644 --- a/testing/scenarios/reverse_test.go +++ b/testing/scenarios/reverse_test.go @@ -17,7 +17,6 @@ import ( "github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/uuid" core "github.com/xtls/xray-core/core" - "github.com/xtls/xray-core/proxy/blackhole" "github.com/xtls/xray-core/proxy/dokodemo" "github.com/xtls/xray-core/proxy/freedom" "github.com/xtls/xray-core/proxy/vmess" @@ -100,7 +99,7 @@ func TestReverseProxy(t *testing.T) { }, Outbound: []*core.OutboundHandlerConfig{ { - ProxySettings: serial.ToTypedMessage(&blackhole.Config{}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}), }, }, } @@ -151,7 +150,7 @@ func TestReverseProxy(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { Tag: "freedom", - ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}), }, { Tag: "reverse", @@ -275,7 +274,7 @@ func TestReverseProxyLongRunning(t *testing.T) { }, Outbound: []*core.OutboundHandlerConfig{ { - ProxySettings: serial.ToTypedMessage(&blackhole.Config{}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}), }, }, } @@ -340,7 +339,7 @@ func TestReverseProxyLongRunning(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { Tag: "freedom", - ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}), }, { Tag: "reverse", diff --git a/testing/scenarios/shadowsocks_2022_test.go b/testing/scenarios/shadowsocks_2022_test.go index f456c5a3c..99c48f170 100644 --- a/testing/scenarios/shadowsocks_2022_test.go +++ b/testing/scenarios/shadowsocks_2022_test.go @@ -91,7 +91,7 @@ func testShadowsocks2022Tcp(t *testing.T, method string, password string) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -176,7 +176,7 @@ func testShadowsocks2022Udp(t *testing.T, method string, password string) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, diff --git a/testing/scenarios/shadowsocks_test.go b/testing/scenarios/shadowsocks_test.go index 2f4536993..ec46f02b1 100644 --- a/testing/scenarios/shadowsocks_test.go +++ b/testing/scenarios/shadowsocks_test.go @@ -53,7 +53,7 @@ func TestShadowsocksChaCha20Poly1305TCP(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -141,7 +141,7 @@ func TestShadowsocksAES256GCMTCP(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -236,7 +236,7 @@ func TestShadowsocksAES128GCMUDP(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -330,7 +330,7 @@ func TestShadowsocksAES128GCMUDPMux(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, diff --git a/testing/scenarios/socks_test.go b/testing/scenarios/socks_test.go index e4682b80e..13794de07 100644 --- a/testing/scenarios/socks_test.go +++ b/testing/scenarios/socks_test.go @@ -11,7 +11,6 @@ import ( "github.com/xtls/xray-core/common/protocol" "github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/core" - "github.com/xtls/xray-core/proxy/blackhole" "github.com/xtls/xray-core/proxy/dokodemo" "github.com/xtls/xray-core/proxy/freedom" "github.com/xtls/xray-core/proxy/http" @@ -51,7 +50,7 @@ func TestSocksBridgeTCP(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -128,7 +127,7 @@ func TestSocksWithHttpRequest(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -217,7 +216,7 @@ func TestSocksBridageUDP(t *testing.T) { }, Outbound: []*core.OutboundHandlerConfig{ { - ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}), }, }, } @@ -331,11 +330,11 @@ func TestSocksBridageUDPWithRouting(t *testing.T) { }, Outbound: []*core.OutboundHandlerConfig{ { - ProxySettings: serial.ToTypedMessage(&blackhole.Config{}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}), }, { Tag: "out", - ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), + ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}), }, }, } @@ -435,7 +434,7 @@ func TestSocksConformanceMod(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, diff --git a/testing/scenarios/tls_test.go b/testing/scenarios/tls_test.go index c76ce4f60..f08144b7d 100644 --- a/testing/scenarios/tls_test.go +++ b/testing/scenarios/tls_test.go @@ -69,7 +69,7 @@ func TestSimpleTLSConnection(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -182,7 +182,7 @@ func TestAutoIssuingCertificate(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -287,7 +287,7 @@ func TestTLSOverKCP(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -387,7 +387,7 @@ func TestTLSOverWebSocket(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -503,7 +503,7 @@ func TestGRPC(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -619,7 +619,7 @@ func TestGRPCMultiMode(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -728,7 +728,7 @@ func TestSimpleTLSConnectionPinned(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -827,7 +827,7 @@ func TestSimpleTLSConnectionPinnedWrongCert(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -925,7 +925,7 @@ func TestUTLSConnectionPinned(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -1025,7 +1025,7 @@ func TestUTLSConnectionPinnedWrongCert(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, diff --git a/testing/scenarios/transport_test.go b/testing/scenarios/transport_test.go index a0bd43f5b..584c51ccd 100644 --- a/testing/scenarios/transport_test.go +++ b/testing/scenarios/transport_test.go @@ -63,7 +63,7 @@ func TestHTTPConnectionHeader(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, diff --git a/testing/scenarios/vless_test.go b/testing/scenarios/vless_test.go index a624b0844..963dae8b4 100644 --- a/testing/scenarios/vless_test.go +++ b/testing/scenarios/vless_test.go @@ -70,7 +70,7 @@ func TestVless(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -175,7 +175,7 @@ func TestVlessTls(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -298,7 +298,7 @@ func TestVlessXtlsVision(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -430,7 +430,7 @@ func TestVlessXtlsVisionReality(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -569,7 +569,7 @@ func TestVlessRealityFingerprints(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -661,7 +661,7 @@ func TestVlessRealityFingerprints(t *testing.T) { wg.Wait() } -// A blocked connection must close after finalRules.delay even while the client keeps it open and sends nothing. +// A blocked connection must close after firewall.delay even while the client keeps it open and sends nothing. func TestVlessBlockDelay(t *testing.T) { tcpServer := tcp.Server{ MsgProcessor: xor, @@ -695,7 +695,7 @@ func TestVlessBlockDelay(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{ + Firewall: []*freedom.FirewallConfig{ { Action: freedom.RuleAction_Block, Delay: &freedom.Range{Min: delay, Max: delay}, @@ -734,7 +734,7 @@ func TestVlessBlockDelay(t *testing.T) { t.Fatalf("connection is still open after %v", elapsed) } if elapsed < blockDuration { - t.Fatalf("connection is closed after %v, before finalRules.delay", elapsed) + t.Fatalf("connection is closed after %v, before firewall.delay", elapsed) } }) } diff --git a/testing/scenarios/vmess_test.go b/testing/scenarios/vmess_test.go index b1d73b20c..35e416f4a 100644 --- a/testing/scenarios/vmess_test.go +++ b/testing/scenarios/vmess_test.go @@ -62,7 +62,7 @@ func TestVMessGCM(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -162,7 +162,7 @@ func TestVMessGCMReadv(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -265,7 +265,7 @@ func TestVMessGCMUDP(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -362,7 +362,7 @@ func TestVMessChacha20(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -463,7 +463,7 @@ func TestVMessKCP(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -568,7 +568,7 @@ func TestVMessKCPLarge(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -674,7 +674,7 @@ func TestVMessGCMMux(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -787,7 +787,7 @@ func TestVMessGCMMuxUDP(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -910,7 +910,7 @@ func TestVMessGCMLengthAuth(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, @@ -1012,7 +1012,7 @@ func TestVMessGCMLengthAuthPlusNoTerminationSignal(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), }, }, diff --git a/testing/scenarios/wireguard_test.go b/testing/scenarios/wireguard_test.go index a3014c48e..663d02f76 100644 --- a/testing/scenarios/wireguard_test.go +++ b/testing/scenarios/wireguard_test.go @@ -61,7 +61,7 @@ func TestWireguard(t *testing.T) { Port: uint32(dest.Port), }, }, - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, }), } } diff --git a/transport/internet/finalmask/finalmask.go b/transport/internet/finalmask/finalmask.go index a64d4183a..617d7fa2e 100644 --- a/transport/internet/finalmask/finalmask.go +++ b/transport/internet/finalmask/finalmask.go @@ -9,9 +9,11 @@ import ( "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" + "github.com/xtls/xray-core/common/session" ) type Dialer struct { + Source net.Addr DialTCP func(net.Destination) (net.Conn, error) DialUDP func(net.Destination) (net.Conn, error) } @@ -85,6 +87,9 @@ func (fm *FinalMask) DialTCP(ctx context.Context, dest net.Destination) (net.Con return &net.PacketConnWrapper{PacketConn: conn, Dest: addr}, err }, } + if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() { + dialer.Source = inbound.Source.RawNetAddr() + } for i := range fm.tcpMasks { var newConn net.Conn newConn, err = fm.tcpMasks[i].WrapConnClient(conn, &dest, dialer) diff --git a/transport/internet/finalmask/proxyprotocol/config.go b/transport/internet/finalmask/proxyprotocol/config.go new file mode 100644 index 000000000..924de4d97 --- /dev/null +++ b/transport/internet/finalmask/proxyprotocol/config.go @@ -0,0 +1,31 @@ +package proxyprotocol + +import ( + "github.com/pires/go-proxyproto" + "github.com/xtls/xray-core/common/errors" + "github.com/xtls/xray-core/common/net" + "github.com/xtls/xray-core/transport/internet/finalmask" +) + +func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *finalmask.Dialer) (net.Conn, error) { + version := c.Version + if version == 0 { + version = 2 + } + if version != 1 && version != 2 { + return nil, errors.New("PROXY protocol version must be 1 or 2") + } + source := conn.LocalAddr() + if dialer != nil && dialer.Source != nil { + source = dialer.Source + } + header := proxyproto.HeaderProxyFromAddrs(byte(version), source, conn.RemoteAddr()) + if _, err := header.WriteTo(conn); err != nil { + return nil, errors.New("failed to write PROXY protocol header").Base(err) + } + return conn, nil +} + +func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) { + return proxyproto.NewConn(conn, proxyproto.WithPolicy(proxyproto.REQUIRE)), nil +} diff --git a/transport/internet/finalmask/proxyprotocol/config.pb.go b/transport/internet/finalmask/proxyprotocol/config.pb.go new file mode 100644 index 000000000..c765d3b9f --- /dev/null +++ b/transport/internet/finalmask/proxyprotocol/config.pb.go @@ -0,0 +1,123 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.12 +// protoc (unknown) +// source: transport/internet/finalmask/proxyprotocol/config.proto + +package proxyprotocol + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type Config struct { + state protoimpl.MessageState `protogen:"open.v1"` + Version uint32 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Config) Reset() { + *x = Config{} + mi := &file_transport_internet_finalmask_proxyprotocol_config_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Config) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Config) ProtoMessage() {} + +func (x *Config) ProtoReflect() protoreflect.Message { + mi := &file_transport_internet_finalmask_proxyprotocol_config_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Config.ProtoReflect.Descriptor instead. +func (*Config) Descriptor() ([]byte, []int) { + return file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescGZIP(), []int{0} +} + +func (x *Config) GetVersion() uint32 { + if x != nil { + return x.Version + } + return 0 +} + +var File_transport_internet_finalmask_proxyprotocol_config_proto protoreflect.FileDescriptor + +const file_transport_internet_finalmask_proxyprotocol_config_proto_rawDesc = "" + + "\n" + + "7transport/internet/finalmask/proxyprotocol/config.proto\x12/xray.transport.internet.finalmask.proxyprotocol\"\"\n" + + "\x06Config\x12\x18\n" + + "\aversion\x18\x01 \x01(\rR\aversionB\xaf\x01\n" + + "3com.xray.transport.internet.finalmask.proxyprotocolP\x01ZDgithub.com/xtls/xray-core/transport/internet/finalmask/proxyprotocol\xaa\x02/Xray.Transport.Internet.Finalmask.ProxyProtocolb\x06proto3" + +var ( + file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescOnce sync.Once + file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescData []byte +) + +func file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescGZIP() []byte { + file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescOnce.Do(func() { + file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_transport_internet_finalmask_proxyprotocol_config_proto_rawDesc), len(file_transport_internet_finalmask_proxyprotocol_config_proto_rawDesc))) + }) + return file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescData +} + +var file_transport_internet_finalmask_proxyprotocol_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_transport_internet_finalmask_proxyprotocol_config_proto_goTypes = []any{ + (*Config)(nil), // 0: xray.transport.internet.finalmask.proxyprotocol.Config +} +var file_transport_internet_finalmask_proxyprotocol_config_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_transport_internet_finalmask_proxyprotocol_config_proto_init() } +func file_transport_internet_finalmask_proxyprotocol_config_proto_init() { + if File_transport_internet_finalmask_proxyprotocol_config_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_transport_internet_finalmask_proxyprotocol_config_proto_rawDesc), len(file_transport_internet_finalmask_proxyprotocol_config_proto_rawDesc)), + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_transport_internet_finalmask_proxyprotocol_config_proto_goTypes, + DependencyIndexes: file_transport_internet_finalmask_proxyprotocol_config_proto_depIdxs, + MessageInfos: file_transport_internet_finalmask_proxyprotocol_config_proto_msgTypes, + }.Build() + File_transport_internet_finalmask_proxyprotocol_config_proto = out.File + file_transport_internet_finalmask_proxyprotocol_config_proto_goTypes = nil + file_transport_internet_finalmask_proxyprotocol_config_proto_depIdxs = nil +} diff --git a/transport/internet/finalmask/proxyprotocol/config.proto b/transport/internet/finalmask/proxyprotocol/config.proto new file mode 100644 index 000000000..1b1030179 --- /dev/null +++ b/transport/internet/finalmask/proxyprotocol/config.proto @@ -0,0 +1,11 @@ +syntax = "proto3"; + +package xray.transport.internet.finalmask.proxyprotocol; +option csharp_namespace = "Xray.Transport.Internet.Finalmask.ProxyProtocol"; +option go_package = "github.com/xtls/xray-core/transport/internet/finalmask/proxyprotocol"; +option java_package = "com.xray.transport.internet.finalmask.proxyprotocol"; +option java_multiple_files = true; + +message Config { + uint32 version = 1; +} diff --git a/transport/internet/finalmask/proxyprotocol/config_test.go b/transport/internet/finalmask/proxyprotocol/config_test.go new file mode 100644 index 000000000..636de844f --- /dev/null +++ b/transport/internet/finalmask/proxyprotocol/config_test.go @@ -0,0 +1,93 @@ +package proxyprotocol + +import ( + "context" + "fmt" + "io" + "testing" + "time" + + "github.com/pires/go-proxyproto" + "github.com/xtls/xray-core/common/net" + "github.com/xtls/xray-core/common/session" + "github.com/xtls/xray-core/transport/internet/finalmask" +) + +func TestClientHeader(t *testing.T) { + for _, version := range []uint32{0, 1, 2} { + for _, sourceIP := range []string{"", "198.51.100.7", "2001:db8::7"} { + t.Run(fmt.Sprintf("version=%d/source=%s", version, sourceIP), func(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + ctx := context.Background() + if sourceIP != "" { + ctx = session.ContextWithInbound(ctx, &session.Inbound{ + Source: net.TCPDestination(net.ParseAddress(sourceIP), 12345), + }) + } + fm := finalmask.NewFinalMask([]finalmask.TCPMask{&Config{Version: version}}, nil, + func(ctx context.Context, dest net.Destination) (net.Conn, error) { + return net.Dial("tcp", dest.NetAddr()) + }, func(ctx context.Context, addr net.Addr) (net.Listener, error) { + return listener, nil + }, nil, nil) + maskedListener, err := fm.Listen(context.Background(), listener.Addr()) + if err != nil { + t.Fatal(err) + } + client, err := fm.DialTCP(ctx, net.DestinationFromAddr(listener.Addr())) + if err != nil { + t.Fatal(err) + } + defer client.Close() + server, err := maskedListener.Accept() + if err != nil { + t.Fatal(err) + } + defer server.Close() + deadline := time.Now().Add(5 * time.Second) + if err := client.SetDeadline(deadline); err != nil { + t.Fatal(err) + } + if err := server.SetDeadline(deadline); err != nil { + t.Fatal(err) + } + proxyConn, ok := server.(*proxyproto.Conn) + if !ok { + t.Fatalf("server connection type = %T, want *proxyproto.Conn", server) + } + header := proxyConn.ProxyHeader() + wantVersion := byte(version) + if wantVersion == 0 { + wantVersion = 2 + } + if header == nil || header.Version != wantVersion || header.Command != proxyproto.PROXY { + t.Fatalf("unexpected PROXY header: %v", header) + } + wantSource := client.LocalAddr() + if sourceIP != "" { + wantSource = &net.TCPAddr{IP: net.ParseIP(sourceIP), Port: 12345} + } + if server.RemoteAddr().String() != wantSource.String() || server.LocalAddr().String() != listener.Addr().String() { + t.Fatalf("addresses = %v -> %v, want %v -> %v", server.RemoteAddr(), server.LocalAddr(), wantSource, listener.Addr()) + } + for _, pair := range [][2]net.Conn{{client, server}, {client, server}, {server, client}} { + const payload = "application payload" + if _, err := io.WriteString(pair[0], payload); err != nil { + t.Fatal(err) + } + data := make([]byte, len(payload)) + if _, err := io.ReadFull(pair[1], data); err != nil { + t.Fatal(err) + } + if string(data) != payload { + t.Fatalf("payload = %q", data) + } + } + }) + } + } +} diff --git a/transport/internet/finalmask/sudoku/sudoku_test.go b/transport/internet/finalmask/sudoku/sudoku_test.go index 2c03a21f0..a2460f3e1 100644 --- a/transport/internet/finalmask/sudoku/sudoku_test.go +++ b/transport/internet/finalmask/sudoku/sudoku_test.go @@ -279,7 +279,7 @@ func runVLESSRealityCase(t *testing.T, bin string, mode trafficMode, payloadSize }, Outbound: []*core.OutboundHandlerConfig{ {ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, })}, }, }) @@ -398,7 +398,7 @@ func runHysteria2Case(t *testing.T, bin string, mode trafficMode, payloadSize in }, Outbound: []*core.OutboundHandlerConfig{ {ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, })}, }, }) @@ -514,7 +514,7 @@ func runVLesseEncCase(t *testing.T, bin string, mode trafficMode, payloadSize in }, Outbound: []*core.OutboundHandlerConfig{ {ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, })}, }, }) @@ -614,7 +614,7 @@ func runVLESSXHTTPCase(t *testing.T, bin string, mode trafficMode, payloadSize i }, Outbound: []*core.OutboundHandlerConfig{ {ProxySettings: serial.ToTypedMessage(&freedom.Config{ - FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, + Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}, })}, }, })