Compare commits

..
Author SHA1 Message Date
Meo597 3e2b8ef1ad readme is open 2026-11-19 17:20:41 +08:00
Meo597 153eb771ac PR template 2026-11-19 03:36:49 +08:00
Meo597 2a351fe2aa contributing 2026-11-19 02:46:20 +08:00
Meo597 b1ef448a88 README: Add project listing criteria
Place the submission link and listing rules in one collapsible block above Contributing.
2026-11-19 01:58:54 +08:00
Meo597 02decee3d2 README: Remove inactive downstream projects 2026-11-19 01:48:18 +08:00
Meo597 9af8bb7f05 README: Polish Telegram and installation links 2026-11-19 00:49:16 +08:00
MeowandGitHub 939ca80bed README: Fix star history chart 2026-11-16 19:57:26 +08:00
95 changed files with 1062 additions and 2046 deletions
+5
View File
@@ -0,0 +1,5 @@
<!--
Read CONTRIBUTING.md before opening a pull request.
Human-led pull requests can use a normal description.
For agent-led pull requests, disclose each AI tool and model, then paste the complete conversation directly in a collapsed <details> block in this PR body. External transcript links are not accepted.
-->
+29
View File
@@ -0,0 +1,29 @@
# Contributing to Xray-core
We review pull requests that address a concrete problem or an agreed proposal. Please keep each change focused and provide evidence that maintainers can check.
## Bug fixes
A bug-fix pull request must link an existing issue filed using the issue template. Summarize the code change and verification in the pull request, and add a regression test when practical. A speculative fix without a demonstrated problem is not ready for a pull request. Report security vulnerabilities through [the security policy](SECURITY.md) rather than a public issue.
## Features
Propose the use case and intended design in an issue before implementing it. Wait for a maintainer to accept the proposal. Explain how the change fits the existing architecture and any compatibility impact.
## Refactors
Propose the scope in an issue and wait for maintainer acceptance before implementing it. Show which complexity the change removes and why the resulting design is easier to understand. Prefer a reduction in code and moving parts, but line count alone is not the review criterion. Preserve observable behavior and test both old-to-new and new-to-old client/server connections when protocol or network behavior is affected.
## AI involvement and author responsibility
AI assistance does not require a conversation record when the author selects or verifies the problem, directs the approach, reviews every changed line, verifies the result, and personally responds to review feedback. The author must be able to explain every changed line and maintain the change. A pull request meeting these conditions is considered human-led, regardless of whether AI wrote the code or who pushed the commits. Such pull requests may ignore the agent-led requirements below.
If an AI agent independently selected the task or made key implementation decisions without ongoing human direction, the pull request is agent-led even if a person submits it manually. Disclose each tool and model and paste the complete prompt-and-response record for every session used for the pull request, including retries and changes after review feedback, inside a collapsed `<details>` block in the pull request description. External links, summaries, and selected excerpts are insufficient. A transcript does not replace the author's review, verification, or responsibility for responding to maintainers.
In agent-led pull requests, commits containing AI-generated changes must credit the specific LLM as their author or co-author.
We do not oppose the use of AI, but agent-led pull requests must have a human author who responds to maintainer feedback for several weeks after submission. Dishonest declarations, fabricated verification, intentionally incomplete records, or abandoning an agent-led pull request are prohibited and may result in being blocked from contributing to Xray-core.
## Review
Maintainers may ask for missing evidence before reviewing code or close a pull request that is outside the agreed scope. The contributor is responsible for understanding, testing, and explaining the change, regardless of the tools used to produce it.
+24 -37
View File
@@ -41,10 +41,10 @@
## Telegram
[Project X](https://t.me/projectXray)
[Project X Channel](https://t.me/projectXtls)
[Project X](https://t.me/projectXray) (中文 / English)
[Project VLESS](https://t.me/projectVless) (Русский)
[Project XHTTP](https://t.me/projectXhttp) (Persian)
@@ -53,7 +53,6 @@
- Linux Script
- [XTLS/Xray-install](https://github.com/XTLS/Xray-install) (**Official**)
- [tempest](https://github.com/team-cloudchaser/tempest) (supports [`systemd`](https://systemd.io) and [OpenRC](https://github.com/OpenRC/openrc); Linux-only)
- Docker
- [ghcr.io/xtls/xray-core](https://ghcr.io/xtls/xray-core) (**Official**)
- [teddysun/xray](https://hub.docker.com/r/teddysun/xray)
@@ -69,12 +68,10 @@
- [TX-UI](https://github.com/AghayeCoder/tx-ui)
- [CELERITY](https://github.com/ClickDevTech/CELERITY-panel)
- One Click
- [Xray-REALITY](https://github.com/zxcvos/Xray-script), [xray-reality](https://github.com/sajjaddg/xray-reality), [reality-ezpz](https://github.com/aleskxyz/reality-ezpz)
- [Xray_bash_onekey](https://github.com/hello-yunshu/Xray_bash_onekey), [XTool](https://github.com/LordPenguin666/XTool), [VPainLess](https://github.com/vpainless/vpainless)
- [v2ray-agent](https://github.com/mack-a/v2ray-agent), [Xray_onekey](https://github.com/wulabing/Xray_onekey), [ProxySU](https://github.com/proxysu/ProxySU)
- [xray-reality](https://github.com/sajjaddg/xray-reality), [Xray_bash_onekey](https://github.com/hello-yunshu/Xray_bash_onekey)
- [v2ray-agent](https://github.com/mack-a/v2ray-agent), [Xray_onekey](https://github.com/wulabing/Xray_onekey)
- Magisk
- [Magic_V2Ray](https://github.com/vincentng295/Magic_V2Ray)
- [Xray_For_Magisk](https://github.com/E7KMbb/Xray_For_Magisk)
- Homebrew
- `brew install xray`
@@ -86,14 +83,7 @@
- [All-in-One-fallbacks-Nginx](https://github.com/XTLS/Xray-examples/tree/main/All-in-One-fallbacks-Nginx)
- Xray-examples
- [XTLS/Xray-examples](https://github.com/XTLS/Xray-examples)
- [chika0801/Xray-examples](https://github.com/chika0801/Xray-examples)
- [lxhao61/integrated-examples](https://github.com/lxhao61/integrated-examples)
- Tutorial
- [XTLS Vision](https://github.com/chika0801/Xray-install)
- [REALITY (English)](https://cscot.pages.dev/2023/03/02/Xray-REALITY-tutorial/)
- [XTLS-Iran-Reality (English)](https://github.com/SasukeFreestyle/XTLS-Iran-Reality)
- [Xray REALITY with 'steal oneself' (English)](https://computerscot.github.io/vless-xtls-utls-reality-steal-oneself.html)
- [Xray with WireGuard inbound (English)](https://g800.pages.dev/wireguard)
## GUI Clients
@@ -106,43 +96,31 @@
- [fancyss](https://github.com/hq450/fancyss)
- Windows
- [v2rayN](https://github.com/2dust/v2rayN)
- [Furious](https://github.com/LorenEteval/Furious)
- [Invisible Man - Xray](https://github.com/InvisibleManVPN/InvisibleMan-XRayClient)
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
- [GenyConnect](https://github.com/genyleap/GenyConnect)
- [OneXray](https://github.com/OneXray/OneXray)
- [XrayUI-dev](https://github.com/PhoenixNil/XrayUI-dev)
- Android
- [v2rayNG](https://github.com/2dust/v2rayNG)
- [X-flutter](https://github.com/XTLS/X-flutter)
- [SaeedDev94/Xray](https://github.com/SaeedDev94/Xray)
- [SimpleXray](https://github.com/lhear/SimpleXray)
- [XrayFA](https://github.com/Q7DF1/XrayFA)
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
- [OneXray](https://github.com/OneXray/OneXray)
- [AsteriskNG](https://github.com/Asterisk4Magisk/AsteriskNG)
- iOS & macOS arm64 & tvOS
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ RU](https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973) | [Happ tvOS](https://apps.apple.com/us/app/happ-proxy-utility-for-tv/id6748297274)
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ tvOS](https://apps.apple.com/us/app/happ-proxy-utility-for-tv/id6748297274)
- [Streisand](https://apps.apple.com/app/streisand/id6450534064)
- [OneXray](https://github.com/OneXray/OneXray)
- [INCY](https://apps.apple.com/en/app/incy/id6756943388)
- macOS arm64 & x64
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ RU](https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973)
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215)
- [V2rayU](https://github.com/yanue/V2rayU)
- [V2RayXS](https://github.com/tzmax/V2RayXS)
- [Furious](https://github.com/LorenEteval/Furious)
- [OneXray](https://github.com/OneXray/OneXray)
- [GoXRay](https://github.com/goxray/desktop)
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
- [v2rayN](https://github.com/2dust/v2rayN)
- [GenyConnect](https://github.com/genyleap/GenyConnect)
- [INCY](https://apps.apple.com/en/app/incy/id6756943388)
- Linux
- [v2rayA](https://github.com/v2rayA/v2rayA)
- [Furious](https://github.com/LorenEteval/Furious)
- [GorzRay](https://github.com/ketetefid/GorzRay)
- [GoXRay](https://github.com/goxray/desktop)
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
- [v2rayN](https://github.com/2dust/v2rayN)
- [GenyConnect](https://github.com/genyleap/GenyConnect)
- [OneXray](https://github.com/OneXray/OneXray)
@@ -163,24 +141,29 @@
- Xray Wrapper
- [XTLS/libXray](https://github.com/XTLS/libXray)
- [xtls-sdk](https://github.com/remnawave/xtls-sdk)
- [xtlsapi](https://github.com/hiddify/xtlsapi)
- [AndroidLibXrayLite](https://github.com/2dust/AndroidLibXrayLite)
- [flutter_vless](https://github.com/XIIIFOX/flutter_vless)
- [Xray-core-python](https://github.com/LorenEteval/Xray-core-python)
- [xray-api](https://github.com/XVGuardian/xray-api)
- [XrayR](https://github.com/XrayR-project/XrayR)
- [XrayR-release](https://github.com/XrayR-project/XrayR-release)
- [XrayR-V2Board](https://github.com/missuo/XrayR-V2Board)
- Cores
- [Amnezia VPN](https://github.com/amnezia-vpn)
- [mihomo](https://github.com/MetaCubeX/mihomo)
- [sing-box](https://github.com/SagerNet/sing-box)
<details>
<summary>Project listing criteria</summary>
To submit a project to the [README](https://github.com/XTLS/Xray-core#readme), open a [pull request](https://github.com/XTLS/Xray-core/pulls). Projects are listed under these rules:
- Projects must be based on Xray-core, have been maintained for at least one month, and have at least 30 stars.
- Projects with no activity for three months will be removed.
- **Closed-source iOS clients must be submitted by their developers.**
</details>
## Contributing
[Code of Conduct](https://github.com/XTLS/Xray-core/blob/main/CODE_OF_CONDUCT.md)
For code contributions, please read [CONTRIBUTING.md](CONTRIBUTING.md) and [Code of Conduct](https://github.com/XTLS/Xray-core/blob/main/CODE_OF_CONDUCT.md) before opening a pull request.
[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/XTLS/Xray-core)
[Ask DeepWiki](https://deepwiki.com/XTLS/Xray-core) might be helpful.
## Credits
@@ -263,4 +246,8 @@ GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 go build -o xray -trimpa
## Stargazers over time
[![Stargazers over time](https://starchart.cc/XTLS/Xray-core.svg)](https://starchart.cc/XTLS/Xray-core)
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xtls/xray-core&type=date&legend=top-left" />
</picture>
+5 -8
View File
@@ -124,17 +124,14 @@ func (c *CacheController) writeAndShrink(expiredKeys []string) {
if rec == nil {
continue
}
a, aaaa := rec.A, rec.AAAA
if a != nil && a.Expire.Before(now) {
a = nil
if rec.A != nil && rec.A.Expire.Before(now) {
rec.A = nil
}
if aaaa != nil && aaaa.Expire.Before(now) {
aaaa = nil
if rec.AAAA != nil && rec.AAAA.Expire.Before(now) {
rec.AAAA = nil
}
if a == nil && aaaa == nil {
if rec.A == nil && rec.AAAA == nil {
delete(c.ips, domain)
} else if a != rec.A || aaaa != rec.AAAA {
c.ips[domain] = &record{A: a, AAAA: aaaa}
}
}
+8 -8
View File
@@ -148,7 +148,7 @@ func TestUDPServerSubnet(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -210,7 +210,7 @@ func TestUDPServer(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -350,7 +350,7 @@ func TestPrioritizedDomain(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -421,7 +421,7 @@ func TestUDPServerIPv6(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -490,7 +490,7 @@ func TestStaticHostDomain(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -577,7 +577,7 @@ func TestIPMatch(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -696,7 +696,7 @@ func TestLocalDomain(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -953,7 +953,7 @@ func TestMultiMatchPrioritizedDomain(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
-4
View File
@@ -68,10 +68,6 @@ func NewServer(ctx context.Context, dest net.Destination, dispatcher routing.Dis
return NewTCPNameServer(u, dispatcher, disableCache, serveStale, serveExpiredTTL, clientIP)
case strings.EqualFold(u.Scheme, "tcp+local"): // DNS-over-TCP Local mode
return NewTCPLocalNameServer(u, disableCache, serveStale, serveExpiredTTL, clientIP)
case strings.EqualFold(u.Scheme, "udp"): // UDP DNS Remote mode
return NewUDPNameServer(u, dispatcher, false, disableCache, serveStale, serveExpiredTTL, clientIP)
case strings.EqualFold(u.Scheme, "udp+local"): // UDP DNS Local mode
return NewUDPNameServer(u, dispatcher, true, disableCache, serveStale, serveExpiredTTL, clientIP)
case strings.EqualFold(u.String(), "fakedns"):
var fd dns.FakeDNSEngine
err = core.RequireFeatures(ctx, func(fdns dns.FakeDNSEngine) {
-45
View File
@@ -2,15 +2,12 @@ package dns
import (
"context"
"io"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/xtls/xray-core/common"
"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/protocol/dns"
@@ -18,8 +15,6 @@ import (
"github.com/xtls/xray-core/common/task"
dns_feature "github.com/xtls/xray-core/features/dns"
"github.com/xtls/xray-core/features/routing"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/internet"
"github.com/xtls/xray-core/transport/internet/udp"
"golang.org/x/net/dns/dnsmessage"
)
@@ -64,46 +59,6 @@ func NewClassicNameServer(address net.Destination, dispatcher routing.Dispatcher
return s
}
// NewUDPNameServer creates a UDP DNS client from a URL.
func NewUDPNameServer(url *url.URL, dispatcher routing.Dispatcher, local bool, disableCache bool, serveStale bool, serveExpiredTTL uint32, clientIP net.IP) (*ClassicNameServer, error) {
if url.Hostname() == "" {
return nil, errors.New("missing UDP nameserver host")
}
port := net.Port(53)
if url.Port() != "" {
var err error
if port, err = net.PortFromString(url.Port()); err != nil {
return nil, err
}
}
if local {
dispatcher = &localUDPDispatcher{dispatcher}
}
s := NewClassicNameServer(net.UDPDestination(net.ParseAddress(url.Hostname()), port), dispatcher, disableCache, serveStale, serveExpiredTTL, clientIP)
if local {
s.cacheController.name = "UDPL//" + s.address.NetAddr()
}
return s, nil
}
type localUDPDispatcher struct {
routing.Dispatcher
}
func (*localUDPDispatcher) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
conn, err := internet.DialSystem(ctx, dest, nil)
if err != nil {
return nil, err
}
return &transport.Link{
Reader: &struct {
buf.Reader
io.Closer
}{buf.NewPacketReader(conn), conn},
Writer: buf.NewWriter(conn),
}, nil
}
// Name implements Server.
func (s *ClassicNameServer) Name() string {
return s.cacheController.name
+7 -1
View File
@@ -273,7 +273,8 @@ type udpWorker struct {
checker *task.Periodic
activeConn map[connID]*udpConn
ctx context.Context
ctx context.Context
cone bool
}
func (w *udpWorker) getConnection(id connID) (*udpConn, bool) {
@@ -315,6 +316,9 @@ func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest
src: source,
}
if originalDest.IsValid() {
if !w.cone {
id.dest = originalDest
}
b.UDP = &originalDest
}
conn, existing := w.getConnection(id)
@@ -414,6 +418,8 @@ func (w *udpWorker) Start() error {
return err
}
w.cone = w.ctx.Value("cone").(bool)
w.checker = &task.Periodic{
Interval: time.Minute,
Execute: w.clean,
+3 -3
View File
@@ -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{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{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{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{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{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
}
if h, err := NewHandler(ctx, cfg); err == nil {
if err := ohm.AddHandler(ctx, h); err == nil {
+3 -2
View File
@@ -24,6 +24,7 @@ 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"
)
@@ -396,9 +397,9 @@ end`)
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
},
Outbound: []*core.OutboundHandlerConfig{
{Tag: "default", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
{Tag: "default", ProxySettings: serial.ToTypedMessage(&blackhole.Config{})},
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
})},
},
})
+1 -1
View File
@@ -23,7 +23,7 @@ func RegisterLua(L *lua.LState) {
return 0
}
xlua.PushWithDirectMethods(L, matcher, map[string]xlua.DirectMethod{
"Match": newLuaDomainMatch(xlua.NewReadOnlySlicePusher[uint32](L)),
"Match": newLuaDomainMatch(xlua.NewSlicePusher[uint32](L)),
"MatchAny": luaDomainMatchAny,
})
return 1
+1 -3
View File
@@ -104,9 +104,7 @@ for _, value in ipairs({matcher, domain}) do
assert(not pcall(function() return value ^ {} end))
end
assert(domain:matchAny("example.com"))
local indices = domain:Match("example.com")
assert(#indices == 1)
assert(not pcall(function() indices[1] = 7 end))
assert(#domain:Match("example.com") == 1)
assert(domain:match("example.com")[1] == 0)
assert(not pcall(function() matcher:AnyMatch() end))
assert(not pcall(function() matcher:AnyMatch(matched, true) end))
+3 -3
View File
@@ -8,10 +8,10 @@ import (
luar "layeh.com/gopher-luar"
)
// newSlicePusher captures luar's slice metatable during state initialization.
// NewSlicePusher captures luar's slice metatable during state initialization.
// The returned function wraps slices without reflection or metatable lookup,
// and pushes nil for nil slices. Use it with this state or its coroutines.
func newSlicePusher[T any](L *glua.LState) func(*glua.LState, []T) {
func NewSlicePusher[T any](L *glua.LState) func(*glua.LState, []T) {
metatable := luar.MT(L, []T(nil)).LTable
return func(L *glua.LState, values []T) {
if values == nil {
@@ -38,7 +38,7 @@ func NewReadOnlySlicePusher[T any](L *glua.LState) func(*glua.LState, []T) {
})
setSliceReadOnly[[]T](L, readOnly)
}
return newSlicePusher[T](L)
return NewSlicePusher[T](L)
}
func setSliceReadOnly[S ~[]E, E any](L *glua.LState, readOnly *glua.LFunction) {
+43 -21
View File
@@ -9,20 +9,53 @@ import (
luar "layeh.com/gopher-luar"
)
func TestReadOnlySlicePusher(t *testing.T) {
func TestSlicePusher(t *testing.T) {
L := glua.NewState()
defer L.Close()
push := NewReadOnlySlicePusher[int](L)
push := NewSlicePusher[int](L)
values := []int{3, 5}
L.SetGlobal("getValues", L.NewFunction(func(L *glua.LState) int {
push(L, values)
return 1
}))
if err := L.DoString(`
local co = coroutine.create(function() return getValues() end)
local values = getValues()
assert(#values == 2 and values[1] == 3 and values[2] == 5)
values[2] = 7
local co = coroutine.create(function()
local values = getValues()
assert(#values == 2 and values[1] == 3 and values[2] == 7)
return true
end)
local ok, result = coroutine.resume(co)
assert(ok, result)
values = result
assert(ok and result == true)
`); err != nil {
t.Fatal(err)
}
if values[1] != 7 {
t.Fatal("slice storage was copied")
}
push(L, nil)
if L.Get(-1) != glua.LNil {
t.Fatal("nil slice must push Lua nil")
}
L.Pop(1)
push(L, []int{})
L.SetGlobal("empty", L.Get(-1))
L.Pop(1)
if err := L.DoString(`assert(type(empty) == "userdata" and #empty == 0)`); err != nil {
t.Fatal(err)
}
}
func TestReadOnlySlicePusher(t *testing.T) {
L := glua.NewState()
defer L.Close()
values := []int{3, 5}
NewReadOnlySlicePusher[int](L)(L, values)
L.SetGlobal("values", L.Get(-1))
L.Pop(1)
if err := L.DoString(`
assert(#values == 2 and values[1] == 3 and values[2] == 5)
assert(not pcall(function() values[1] = 7 end))
assert(not pcall(function() return values + 7 end))
@@ -36,17 +69,6 @@ assert(sum == 8)
if &got[0] != &values[0] || values[0] != 3 || values[1] != 5 {
t.Fatal("read-only binding copied or modified the slice")
}
push(L, nil)
if L.Get(-1) != glua.LNil {
t.Fatal("nil slice must push Lua nil")
}
L.Pop(1)
push(L, []int{})
L.SetGlobal("empty", L.Get(-1))
L.Pop(1)
if err := L.DoString(`assert(type(empty) == "userdata" and #empty == 0)`); err != nil {
t.Fatal(err)
}
}
func TestReadOnlyIPSlicePusher(t *testing.T) {
@@ -208,23 +230,23 @@ assert(not pcall(function() return nested + nested end))
}
}
func TestReadOnlySlicePusherMetatablePerState(t *testing.T) {
func TestSlicePusherMetatablePerState(t *testing.T) {
first := glua.NewState()
defer first.Close()
second := glua.NewState()
defer second.Close()
NewReadOnlySlicePusher[int](first)(first, []int{1})
NewReadOnlySlicePusher[int](second)(second, []int{1})
NewSlicePusher[int](first)(first, []int{1})
NewSlicePusher[int](second)(second, []int{1})
if first.Get(-1).(*glua.LUserData).Metatable == second.Get(-1).(*glua.LUserData).Metatable {
t.Fatal("independent states share a slice metatable")
}
}
func BenchmarkReadOnlySlicePusher(b *testing.B) {
func BenchmarkSlicePusher(b *testing.B) {
L := glua.NewState()
defer L.Close()
ips := []net.IP{net.ParseIP("127.0.0.1")}
pushIPs := NewReadOnlySlicePusher[net.IP](L)
pushIPs := NewSlicePusher[net.IP](L)
for _, benchmark := range []struct {
name string
push func(*glua.LState, []net.IP)
+4 -2
View File
@@ -671,7 +671,7 @@ string.__tostring = nil
L.SetGlobal("testNativeError", L.Get(-1))
L.Pop(1)
L.SetGlobal("testGoStruct", luar.New(L, &struct{ Value string }{"readable field"}))
NewReadOnlySlicePusher[net.IP](L)(L, []net.IP{net.ParseIP("192.0.2.1")})
NewSlicePusher[net.IP](L)(L, []net.IP{net.ParseIP("192.0.2.1")})
L.SetGlobal("testIPs", L.Get(-1))
L.Pop(1)
userdata := L.NewUserData()
@@ -865,7 +865,9 @@ assert(not ok and a == "{<address> <address>}")
PushUserData(L, struct{ Pointer *int }{&target})
L.SetGlobal("testObject", L.Get(-1))
L.Pop(1)
L.SetGlobal("testValues", luar.New(L, []int{1}))
NewSlicePusher[int](L)(L, []int{1})
L.SetGlobal("testValues", L.Get(-1))
L.Pop(1)
L.SetGlobal("testPanic", L.NewFunction(func(L *glua.LState) int {
panic(struct{ First, Second *int }{&target, &target})
}))
+11 -12
View File
@@ -8,7 +8,6 @@ import (
"fmt"
"net"
"os"
"slices"
"strconv"
"strings"
@@ -32,7 +31,7 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
switch network {
case "tcp":
if net.ParseIP(srcIP).To4() != nil {
procFiles = []string{"/proc/net/tcp", "/proc/net/tcp6"}
procFiles = []string{"/proc/net/tcp"}
} else {
procFiles = []string{"/proc/net/tcp6"}
}
@@ -46,18 +45,14 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
panic("Unsupported network type for process lookup.")
}
targetHexAddrs := []string{formatProcNetAddress(net.ParseIP(srcIP).To16(), Port(srcPort))}
if ipv4 := net.ParseIP(srcIP).To4(); ipv4 != nil {
// the one above is then the IPv4-mapped IPv6 address that an IPv6 socket has it as, in the IPv6 file
targetHexAddrs = append(targetHexAddrs, formatProcNetAddress(ipv4, Port(srcPort)))
}
targetHexAddr := formatProcNetAddress(net.ParseIP(srcIP), Port(srcPort))
portFallback := ""
if network == "udp" {
portFallback = fmt.Sprintf(":%04X", srcPort)
}
inode, err := findInodeInFiles(procFiles, targetHexAddrs, portFallback)
inode, err := findInodeInFiles(procFiles, targetHexAddr, portFallback)
if err != nil {
return 0, "", "", errors.New("could not search in ", strings.Join(procFiles, " and ")).Base(err)
}
@@ -89,9 +84,13 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
return pid, procName, absPath, nil
}
// formatProcNetAddress formats the 4 or 16 bytes of addr as they are: an IPv4-mapped IPv6 address stays one
func formatProcNetAddress(addr net.IP, port Port) string {
ipBytes := []byte(addr)
var ipBytes []byte
if ipv4 := addr.To4(); ipv4 != nil {
ipBytes = ipv4
} else {
ipBytes = addr.To16()
}
var formatted strings.Builder
formatted.Grow(len(ipBytes)*2 + 5)
@@ -102,7 +101,7 @@ func formatProcNetAddress(addr net.IP, port Port) string {
return formatted.String()
}
func findInodeInFiles(filePaths []string, targetHexAddrs []string, portFallback string) (string, error) {
func findInodeInFiles(filePaths []string, targetHexAddr, portFallback string) (string, error) {
onlyMatchedPort := ""
for i, filePath := range filePaths {
@@ -123,7 +122,7 @@ func findInodeInFiles(filePaths []string, targetHexAddrs []string, portFallback
}
localAddress := fields[1]
if slices.Contains(targetHexAddrs, localAddress) {
if localAddress == targetHexAddr {
return fields[9], nil
}
if portFallback != "" && strings.HasSuffix(localAddress, portFallback) {
-50
View File
@@ -1,50 +0,0 @@
//go:build linux && !android
package net
import (
"errors"
stdnet "net"
"net/netip"
"os"
"syscall"
"testing"
)
func TestFindProcessIPv4Mapped(t *testing.T) {
listener, err := stdnet.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
peer, err := stdnet.ListenPacket("udp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer peer.Close()
// an IPv6 socket that connects to an IPv4 address, as the sockets of Java and .NET are
for _, c := range []struct{ local, remote stdnet.Addr }{
{&stdnet.TCPAddr{IP: stdnet.IPv6zero}, listener.Addr()},
{&stdnet.UDPAddr{IP: stdnet.IPv6zero}, peer.LocalAddr()},
} {
network := c.remote.Network()
conn, err := (&stdnet.Dialer{LocalAddr: c.local}).Dial(network, c.remote.String())
if errors.Is(err, syscall.EAFNOSUPPORT) {
t.Skip("no IPv6 sockets here")
}
if err != nil {
t.Fatal(err)
}
defer conn.Close()
local := netip.MustParseAddrPort(conn.LocalAddr().String())
remote := netip.MustParseAddrPort(c.remote.String())
pid, _, _, err := FindProcess(network, "127.0.0.1", local.Port(), "127.0.0.1", remote.Port())
if err != nil {
t.Errorf("%s: %v", network, err)
} else if pid != os.Getpid() {
t.Errorf("%s: found PID %d, want %d", network, pid, os.Getpid())
}
}
}
+1
View File
@@ -16,6 +16,7 @@ const (
UseReadV = "xray.buf.readv"
UseFreedomSplice = "xray.buf.splice"
UseVmessPadding = "xray.vmess.padding"
UseCone = "xray.cone.disabled"
UseStrictJSON = "xray.json.strict"
BufferSize = "xray.ray.buffer.size"
+3
View File
@@ -63,6 +63,9 @@ func init() {
}
func GetGlobalID(ctx context.Context) (globalID [8]byte) {
if cone := ctx.Value("cone"); cone == nil || !cone.(bool) { // cone is nil only in some unit tests
return
}
if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.Network == net.Network_UDP &&
(inbound.Name == "dokodemo-door" || inbound.Name == "socks" || inbound.Name == "shadowsocks" || inbound.Name == "tun") {
h := blake3.New(8, ensureBaseKey())
+3 -3
View File
@@ -53,7 +53,7 @@ func TestXrayDial(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -105,7 +105,7 @@ func TestXrayDialUDPConn(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -174,7 +174,7 @@ func TestXrayDialUDP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
+2
View File
@@ -192,6 +192,8 @@ func initInstanceWithConfig(config *Config, server *Instance) (bool, error) {
if err := platform.ReloadEnvSettings(); err != nil {
return true, errors.New("failed to reload environment settings").Base(err)
}
server.ctx = context.WithValue(server.ctx, "cone",
platform.NewEnvFlag(platform.UseCone).GetValue(func() string { return "" }) != "true")
for _, appSettings := range config.App {
settings, err := appSettings.GetInstance()
+1 -1
View File
@@ -45,7 +45,7 @@ require (
github.com/huin/goupnp v1.2.0 // indirect
github.com/jackpal/go-nat-pmp v1.0.2 // indirect
github.com/juju/ratelimit v1.0.2 // indirect
github.com/klauspost/compress v1.20.4 // indirect
github.com/klauspost/compress v1.20.1 // indirect
github.com/koron/go-ssdp v0.0.4 // indirect
github.com/libp2p/go-netroute v0.2.1 // indirect
github.com/molecule-man/go-brrr v1.2.0 // indirect
-2
View File
@@ -33,8 +33,6 @@ github.com/juju/ratelimit v1.0.2 h1:sRxmtRiajbvrcLQT7S+JbqU0ntsb9W2yhSdNN8tWfaI=
github.com/juju/ratelimit v1.0.2/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk=
github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ=
github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/koron/go-ssdp v0.0.4 h1:1IDwrghSKYM7yLf7XCzbByg2sJ/JcNOZRXS2jczTwz0=
+6 -12
View File
@@ -5,8 +5,7 @@ import (
"strings"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/proxy/freedom"
"github.com/xtls/xray-core/proxy/blackhole"
"google.golang.org/protobuf/proto"
)
@@ -20,29 +19,24 @@ type BlackholeConfig struct {
}
func (v *BlackholeConfig) Build() (proto.Message, error) {
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(),
}
config := new(blackhole.Config)
if v.Response != nil {
responseName := strings.ToLower(v.Response.Type)
switch responseName {
case "none", "":
rule.Reply = &freedom.Reply{Type: "none"}
config.Response = &blackhole.Response{Type: "none"}
case "http":
rule.Reply = &freedom.Reply{Type: "http"}
config.Response = &blackhole.Response{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())
}
rule.Reply = &freedom.Reply{Type: "custom", CustomResponseData: data}
config.Response = &blackhole.Response{Type: "custom", CustomResponseData: data}
default:
return nil, errors.New("unknown blackhole response: " + responseName)
}
}
return &freedom.Config{Firewall: []*freedom.FirewallConfig{rule}}, nil
return config, nil
}
+9 -26
View File
@@ -3,9 +3,8 @@ 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/freedom"
"github.com/xtls/xray-core/proxy/blackhole"
)
func TestHTTPResponseJSON(t *testing.T) {
@@ -21,25 +20,14 @@ func TestHTTPResponseJSON(t *testing.T) {
}
}`,
Parser: loadJSON(creator),
Output: &freedom.Config{
Firewall: []*freedom.FirewallConfig{{
Action: freedom.RuleAction_Block,
Delay: &freedom.Range{},
LogLevel: log.Severity_Unknown.Enum(),
Reply: &freedom.Reply{Type: "http"},
}},
Output: &blackhole.Config{
Response: &blackhole.Response{Type: "http"},
},
},
{
Input: `{}`,
Parser: loadJSON(creator),
Output: &freedom.Config{
Firewall: []*freedom.FirewallConfig{{
Action: freedom.RuleAction_Block,
Delay: &freedom.Range{},
LogLevel: log.Severity_Unknown.Enum(),
}},
},
Output: &blackhole.Config{},
},
})
}
@@ -58,16 +46,11 @@ func TestCustomResponseJSON(t *testing.T) {
}
}`,
Parser: loadJSON(creator),
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"),
},
}},
Output: &blackhole.Config{
Response: &blackhole.Response{
Type: "custom",
CustomResponseData: []byte("custom response"),
},
},
},
})
+28 -68
View File
@@ -18,17 +18,16 @@ 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"`
Firewall []*FreedomFirewallConfig `json:"firewall"`
FinalRules []*FreedomFirewallConfig `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"`
FinalRules []*FreedomFinalRuleConfig `json:"finalRules"`
}
type Fragment struct {
@@ -45,45 +44,21 @@ type Noise struct {
ApplyTo string `json:"applyTo"`
}
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)
}
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"`
}
// 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 "firewall". Please update your config(s) according to release note and documentation.`)
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.`)
}
config := new(freedom.Config)
@@ -209,22 +184,15 @@ func (c *FreedomConfig) Build() (proto.Message, error) {
}
if c.ProxyProtocol > 0 && c.ProxyProtocol <= 2 {
errors.PrintDeprecatedFeatureWarning(`"proxyProtocol" in Freedom`, `"proxy-protocol" in "streamSettings.finalmask.tcp"`)
config.ProxyProtocol = c.ProxyProtocol
}
firewall := c.Firewall
if c.FinalRules != nil {
errors.PrintDeprecatedFeatureWarning("finalRules", "firewall")
if firewall == nil {
firewall = c.FinalRules
}
}
for _, r := range firewall {
for _, r := range c.FinalRules {
rule, err := r.Build()
if err != nil {
return nil, err
}
config.Firewall = append(config.Firewall, rule)
config.FinalRules = append(config.FinalRules, rule)
}
return config, nil
@@ -286,8 +254,8 @@ func ParseNoise(noise *Noise) (*freedom.Noise, error) {
return NConfig, nil
}
func (c *FreedomFirewallConfig) Build() (*freedom.FirewallConfig, error) {
rule := &freedom.FirewallConfig{}
func (c *FreedomFinalRuleConfig) Build() (*freedom.FinalRuleConfig, error) {
rule := &freedom.FinalRuleConfig{}
switch strings.ToLower(c.Action) {
case "allow":
@@ -315,13 +283,13 @@ func (c *FreedomFirewallConfig) Build() (*freedom.FirewallConfig, error) {
}
if c.BlockDelay != nil {
errors.PrintDeprecatedFeatureWarning("firewall.blockDelay", "firewall.delay")
errors.PrintDeprecatedFeatureWarning("finalRules.blockDelay", "finalRules.delay")
c.Delay = c.BlockDelay
}
if rule.Action != freedom.RuleAction_Block {
if c.Delay != nil || c.LogLevel != "" || c.Reply != nil {
return nil, errors.New("delay, logLevel and reply are only supported for firewall action block")
if c.Delay != nil || c.LogLevel != "" {
return nil, errors.New("delay and logLevel are only supported for block finalRules")
}
return rule, nil
}
@@ -333,14 +301,6 @@ func (c *FreedomFirewallConfig) Build() (*freedom.FirewallConfig, 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()
@@ -353,7 +313,7 @@ func (c *FreedomFirewallConfig) Build() (*freedom.FirewallConfig, error) {
case "error":
rule.LogLevel = log.Severity_Error.Enum()
default:
return nil, errors.New("unknown firewall.logLevel: ", c.LogLevel)
return nil, errors.New("unknown finalRules.logLevel: ", c.LogLevel)
}
return rule, nil
+3 -11
View File
@@ -42,17 +42,13 @@ func TestFreedomConfig(t *testing.T) {
},
{
Input: `{
"firewall": [{
"finalRules": [{
"action": "block",
"network": "tcp,udp",
"port": "53,443",
"ip": ["10.0.0.0/8", "2001:db8::/32"],
"delay": "30-60",
"logLevel": "debug",
"reply": {
"type": "custom",
"customResponseData": "Y3VzdG9tIHJlc3BvbnNl"
}
"logLevel": "debug"
}, {
"action": "allow",
"network": ["udp"]
@@ -60,7 +56,7 @@ func TestFreedomConfig(t *testing.T) {
}`,
Parser: loadJSON(creator),
Output: &freedom.Config{
Firewall: []*freedom.FirewallConfig{
FinalRules: []*freedom.FinalRuleConfig{
{
Action: freedom.RuleAction_Block,
Networks: []net.Network{net.Network_TCP, net.Network_UDP},
@@ -94,10 +90,6 @@ 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,
+7 -51
View File
@@ -18,7 +18,6 @@ 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"
@@ -27,7 +26,6 @@ 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"
@@ -78,12 +76,11 @@ 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) },
"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) },
"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) },
}, "type", "settings")
udpmaskLoader = NewJSONConfigLoader(ConfigCreatorCache{
@@ -100,32 +97,6 @@ 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"`
@@ -965,20 +936,12 @@ type XMC struct {
Profiles []XMCProfile `json:"profiles"`
Password string `json:"password"`
Paddings []XMCPaddingTurn `json:"paddings,omitempty"`
// A configured list is the complete padding schedule and replaces the
// built-in preset entirely, including the preset's Play-state join tail.
// NoPadding disables padding. An explicit empty "paddings" array means the
// same; an absent one keeps the built-in preset.
NoPadding bool `json:"noPadding,omitempty"`
}
type XMCPaddingTurn struct {
Length string `json:"length"`
Direction string `json:"direction"`
// Delay is an optional millisecond value or inclusive min-max range: the
// pause that leads into this turn, written on the turn that follows the gap
// it reproduces. The sending side samples the range, the peer spends its
// minimum, and nothing pauses after the last turn.
// Delay is an optional millisecond value or inclusive min-max range.
Delay string `json:"delay,omitempty"`
}
@@ -1025,14 +988,7 @@ func (c *XMC) Build() (proto.Message, error) {
if len(c.Password) > xmc.MaxLegacyPasswordLength {
return nil, fmt.Errorf("minecraft password is longer than %d bytes", xmc.MaxLegacyPasswordLength)
}
// An explicit empty array is different from an absent field: json leaves
// Paddings nil when it is absent, so the user can turn padding off without
// a second switch.
noPadding := c.NoPadding || (c.Paddings != nil && len(c.Paddings) == 0)
if noPadding && len(c.Paddings) > 0 {
return nil, fmt.Errorf("minecraft padding: noPadding and paddings are exclusive")
}
config := &xmc.Config{Password: c.Password, Hostname: c.Hostname, NoPadding: noPadding}
config := &xmc.Config{Password: c.Password, Hostname: c.Hostname}
for i, turn := range c.Paddings {
minimum, maximum, err := ParseRangeString(turn.Length)
if err != nil {
@@ -112,42 +112,3 @@ func TestXMCBuildRejectsLongPassword(t *testing.T) {
t.Fatalf("expected a password length error, got %v", err)
}
}
func TestXMCBuildDisablesPadding(t *testing.T) {
profile := XMCProfile{
Username: "TestUser", UUID: "00112233-4455-6677-8899-aabbccddeeff",
TexturesValue: "textures-value", TexturesSignature: "textures-signature",
}
for name, settings := range map[string]string{
"explicit_empty_array": `{"paddings": []}`,
"no_padding_switch": `{"noPadding": true}`,
} {
t.Run(name, func(t *testing.T) {
var config XMC
if err := json.Unmarshal([]byte(settings), &config); err != nil {
t.Fatal(err)
}
config.Password = "test-password"
config.Profiles = []XMCProfile{profile}
built, err := config.Build()
if err != nil {
t.Fatalf("build XMC config: %v", err)
}
builtConfig := built.(*xmc.Config)
if !builtConfig.NoPadding || len(builtConfig.Paddings) != 0 {
t.Fatalf("padding was not disabled: %+v", builtConfig)
}
})
}
var config XMC
if err := json.Unmarshal([]byte(`{"noPadding": true, "paddings": [{"length": "3", "direction": "c2s"}]}`), &config); err != nil {
t.Fatal(err)
}
config.Password = "test-password"
config.Profiles = []XMCProfile{profile}
if _, err := config.Build(); err == nil || !strings.Contains(err.Error(), "exclusive") {
t.Fatalf("expected an exclusive padding error, got %v", err)
}
}
+1 -10
View File
@@ -407,16 +407,7 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
return nil, errors.New("the masque transport can only be used by the masque outbound")
}
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 fc, ok := ts.(*freedom.Config); ok {
if senderSettings.StreamSettings != nil &&
senderSettings.StreamSettings.SocketSettings != nil &&
senderSettings.StreamSettings.SocketSettings.AddressPortStrategy != internet.AddressPortStrategy_None {
+1
View File
@@ -35,6 +35,7 @@ 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"
+88
View File
@@ -0,0 +1,88 @@
// 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))
}))
}
+76
View File
@@ -0,0 +1,76 @@
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")
}
}
+180
View File
@@ -0,0 +1,180 @@
// 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
}
+16
View File
@@ -0,0 +1,16 @@
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;
}
+19
View File
@@ -0,0 +1,19 @@
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")
}
}
+68 -124
View File
@@ -352,59 +352,7 @@ func (x *Range) GetMax() uint64 {
return 0
}
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 *Reply) Reset() {
*x = Reply{}
mi := &file_proxy_freedom_config_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Reply) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Reply) ProtoMessage() {}
func (x *Reply) ProtoReflect() protoreflect.Message {
mi := &file_proxy_freedom_config_proto_msgTypes[4]
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 Reply.ProtoReflect.Descriptor instead.
func (*Reply) Descriptor() ([]byte, []int) {
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{4}
}
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 {
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"`
@@ -412,26 +360,25 @@ type FirewallConfig struct {
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]
func (x *FinalRuleConfig) Reset() {
*x = FinalRuleConfig{}
mi := &file_proxy_freedom_config_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *FirewallConfig) String() string {
func (x *FinalRuleConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*FirewallConfig) ProtoMessage() {}
func (*FinalRuleConfig) ProtoMessage() {}
func (x *FirewallConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_freedom_config_proto_msgTypes[5]
func (x *FinalRuleConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_freedom_config_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -442,75 +389,69 @@ func (x *FirewallConfig) ProtoReflect() protoreflect.Message {
return mi.MessageOf(x)
}
// Deprecated: Use FirewallConfig.ProtoReflect.Descriptor instead.
func (*FirewallConfig) Descriptor() ([]byte, []int) {
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{5}
// Deprecated: Use FinalRuleConfig.ProtoReflect.Descriptor instead.
func (*FinalRuleConfig) Descriptor() ([]byte, []int) {
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{4}
}
func (x *FirewallConfig) GetAction() RuleAction {
func (x *FinalRuleConfig) GetAction() RuleAction {
if x != nil {
return x.Action
}
return RuleAction_Allow
}
func (x *FirewallConfig) GetNetworks() []net.Network {
func (x *FinalRuleConfig) GetNetworks() []net.Network {
if x != nil {
return x.Networks
}
return nil
}
func (x *FirewallConfig) GetPortList() *net.PortList {
func (x *FinalRuleConfig) GetPortList() *net.PortList {
if x != nil {
return x.PortList
}
return nil
}
func (x *FirewallConfig) GetIp() []*geodata.IPRule {
func (x *FinalRuleConfig) GetIp() []*geodata.IPRule {
if x != nil {
return x.Ip
}
return nil
}
func (x *FirewallConfig) GetDelay() *Range {
func (x *FinalRuleConfig) GetDelay() *Range {
if x != nil {
return x.Delay
}
return nil
}
func (x *FirewallConfig) GetLogLevel() log.Severity {
func (x *FinalRuleConfig) 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"`
Firewall []*FirewallConfig `protobuf:"bytes,8,rep,name=firewall,proto3" json:"firewall,omitempty"`
FinalRules []*FinalRuleConfig `protobuf:"bytes,8,rep,name=final_rules,json=finalRules,proto3" json:"final_rules,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_proxy_freedom_config_proto_msgTypes[6]
mi := &file_proxy_freedom_config_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -522,7 +463,7 @@ func (x *Config) String() string {
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_proxy_freedom_config_proto_msgTypes[6]
mi := &file_proxy_freedom_config_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -535,7 +476,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{6}
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{5}
}
func (x *Config) GetDomainStrategy() internet.DomainStrategy {
@@ -566,6 +507,13 @@ 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
@@ -573,9 +521,9 @@ func (x *Config) GetNoises() []*Noise {
return nil
}
func (x *Config) GetFirewall() []*FirewallConfig {
func (x *Config) GetFinalRules() []*FinalRuleConfig {
if x != nil {
return x.Firewall
return x.FinalRules
}
return nil
}
@@ -610,28 +558,26 @@ 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\"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" +
"\x03max\x18\x02 \x01(\x04R\x03max\"\xe0\x02\n" +
"\x0fFinalRuleConfig\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\x01\x12/\n" +
"\x05reply\x18\a \x01(\v2\x19.xray.proxy.freedom.ReplyR\x05replyB\f\n" +
"\tlog_level\x18\x06 \x01(\x0e2\x19.xray.common.log.SeverityH\x00R\blogLevel\x88\x01\x01B\f\n" +
"\n" +
"_log_level\"\x88\x03\n" +
"_log_level\"\xaf\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\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" +
"\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" +
"\n" +
"RuleAction\x12\t\n" +
"\x05Allow\x10\x00\x12\t\n" +
@@ -651,42 +597,40 @@ 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, 7)
var file_proxy_freedom_config_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
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
(*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
(*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
}
var file_proxy_freedom_config_proto_depIdxs = []int32{
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
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
}
func init() { file_proxy_freedom_config_proto_init() }
@@ -694,14 +638,14 @@ func file_proxy_freedom_config_proto_init() {
if File_proxy_freedom_config_proto != nil {
return
}
file_proxy_freedom_config_proto_msgTypes[5].OneofWrappers = []any{}
file_proxy_freedom_config_proto_msgTypes[4].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: 7,
NumMessages: 6,
NumExtensions: 0,
NumServices: 0,
},
+3 -9
View File
@@ -47,27 +47,21 @@ enum RuleAction {
Block = 1;
}
message Reply {
string type = 1;
bytes custom_response_data = 2;
}
message FirewallConfig {
message FinalRuleConfig {
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 FirewallConfig firewall = 8;
repeated FinalRuleConfig final_rules = 8;
}
+54 -83
View File
@@ -1,15 +1,14 @@
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"
@@ -36,20 +35,10 @@ import (
var (
useSplice atomic.Bool
allNetworks [8]bool
defaultBlockPrivateRule *Firewall
defaultBlockAllRule *Firewall
defaultBlockPrivateRule *FinalRule
defaultBlockAllRule *FinalRule
)
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 })
@@ -83,60 +72,45 @@ func init() {
allNetworks[i] = true
}
defaultBlockPrivateRule = &Firewall{
defaultBlockPrivateRule = &FinalRule{
action: RuleAction_Block,
network: allNetworks,
ip: geodata.GetPrivateIPMatcher(),
logLevel: log.Severity_Warning.Enum(),
}
defaultBlockAllRule = &Firewall{
defaultBlockAllRule = &FinalRule{
action: RuleAction_Block,
network: allNetworks,
logLevel: log.Severity_Warning.Enum(),
}
}
type Firewall struct {
type FinalRule 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
firewall []*Firewall
finalRules []*FinalRule
resolveStrategy internet.DomainStrategy
usesDialerProxy bool
}
func buildRule(config *FirewallConfig) (*Firewall, error) {
rule := &Firewall{
func buildFinalRule(config *FinalRuleConfig) (*FinalRule, error) {
rule := &FinalRule{
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 {
@@ -160,25 +134,25 @@ func buildRule(config *FirewallConfig) (*Firewall, error) {
return rule, nil
}
func (r *Firewall) matchNetwork(network net.Network) bool {
func (r *FinalRule) matchNetwork(network net.Network) bool {
return r.network[int(network)]
}
func (r *Firewall) matchPort(port net.Port) bool {
func (r *FinalRule) matchPort(port net.Port) bool {
if len(r.port) == 0 {
return true
}
return r.port.Contains(port)
}
func (r *Firewall) matchIP(addr net.Address) bool {
func (r *FinalRule) matchIP(addr net.Address) bool {
if r.ip == nil {
return true
}
return addr != nil && addr.Family().IsIP() && r.ip.Match(addr.IP())
}
func (r *Firewall) Apply(network net.Network, address net.Address, port net.Port) bool {
func (r *FinalRule) Apply(network net.Network, address net.Address, port net.Port) bool {
if !r.matchNetwork(network) {
return false
}
@@ -188,7 +162,7 @@ func (r *Firewall) Apply(network net.Network, address net.Address, port net.Port
return r.matchIP(address)
}
func getDefaultRule(inbound *session.Inbound) *Firewall {
func getDefaultFinalRule(inbound *session.Inbound) *FinalRule {
if inbound == nil {
return nil
}
@@ -205,8 +179,8 @@ func getDefaultRule(inbound *session.Inbound) *Firewall {
return nil
}
func (h *Handler) matchRule(network net.Network, address net.Address, port net.Port, defaultRule *Firewall) *Firewall {
for _, rule := range h.firewall {
func (h *Handler) matchFinalRule(network net.Network, address net.Address, port net.Port, defaultRule *FinalRule) *FinalRule {
for _, rule := range h.finalRules {
if rule.Apply(network, address, port) {
return rule
}
@@ -221,19 +195,19 @@ func (h *Handler) matchRule(network net.Network, address net.Address, port net.P
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, 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.`)
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.`)
}
return nil
}
h.firewall = make([]*Firewall, 0, len(config.Firewall))
for _, rc := range config.Firewall {
rule, err := buildRule(rc)
h.finalRules = make([]*FinalRule, 0, len(config.FinalRules))
for _, rc := range config.FinalRules {
rule, err := buildFinalRule(rc)
if err != nil {
return errors.New("failed to build firewall rule").Base(err)
return errors.New("failed to build final rule").Base(err)
}
h.firewall = append(h.firewall, rule)
h.finalRules = append(h.finalRules, rule)
}
return nil
}
@@ -243,7 +217,7 @@ func (h *Handler) policy() policy.Session {
return p
}
func (r *Firewall) blockDuration() time.Duration {
func (r *FinalRule) blockDuration() time.Duration {
min := uint64(30)
max := uint64(90)
if r.delay != nil {
@@ -257,7 +231,7 @@ func (r *Firewall) blockDuration() time.Duration {
return time.Duration(min+uint64(dice.Roll(int(span+1)))) * time.Second
}
func (r *Firewall) log(ctx context.Context, msg ...interface{}) {
func (r *FinalRule) log(ctx context.Context, msg ...interface{}) {
level := log.Severity_Info
if r.logLevel != nil {
level = *r.logLevel
@@ -274,17 +248,10 @@ func (r *Firewall) log(ctx context.Context, msg ...interface{}) {
}
}
func (h *Handler) blackhole(ctx context.Context, input buf.Reader, output buf.Writer, rule *Firewall, dest *net.Destination) error {
func (h *Handler) blackhole(ctx context.Context, input buf.Reader, output buf.Writer, rule *FinalRule, dest *net.Destination) error {
delay := rule.blockDuration()
rule.log(ctx, "target blocked by a firewall rule: ", *dest, ", blackholing connection for ", delay)
rule.log(ctx, "target blocked by a finalrule: ", *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)
@@ -318,16 +285,10 @@ 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 *Firewall
if !h.usesDialerProxy { // freedom is not the final outbound, firewall does not apply (and the domain is not resolved)
defaultRule = getDefaultRule(inbound)
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)
}
destination := ob.Target
@@ -355,10 +316,10 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
var conn stat.Connection
var blockedDest *net.Destination
var blockedRule *Firewall
var blockedRule *FinalRule
err := retry.ExponentialBackoff(5, 100).On(func() error {
if destination.Address.Family().IsDomain() {
if defaultRule != nil || len(h.firewall) > 0 {
if defaultRule != nil || len(h.finalRules) > 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
@@ -369,7 +330,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.matchRule(destination.Network, addr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
if rule := h.matchFinalRule(destination.Network, addr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
blockedDest = &destination
blockedDest.Address = addr
blockedRule = rule
@@ -384,7 +345,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.matchRule(destination.Network, ipAddr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
if rule := h.matchFinalRule(destination.Network, ipAddr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
blockedDest = &destination
blockedDest.Address = ipAddr
blockedRule = rule
@@ -395,7 +356,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
}
}
} else {
if rule := h.matchRule(destination.Network, destination.Address, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
if rule := h.matchFinalRule(destination.Network, destination.Address, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
blockedDest = &destination
blockedRule = rule
return nil
@@ -416,15 +377,25 @@ 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.firewall) > 0) {
if destination.Address.Family().IsDomain() && (defaultRule != nil || len(h.finalRules) > 0) {
// pre-check may fail or dialer may select another IP
remoteDest := net.DestinationFromAddr(conn.RemoteAddr())
if rule := h.matchRule(remoteDest.Network, remoteDest.Address, remoteDest.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
if rule := h.matchFinalRule(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())
@@ -513,7 +484,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
return nil
}
func NewPacketReader(conn net.Conn, h *Handler, defaultRule *Firewall, UDPOverride net.Destination, DialDest net.Destination) buf.Reader {
func NewPacketReader(conn net.Conn, h *Handler, defaultRule *FinalRule, UDPOverride net.Destination, DialDest net.Destination) buf.Reader {
iConn := conn
statConn, ok := iConn.(*stat.CounterConnection)
if ok {
@@ -546,7 +517,7 @@ type PacketReader struct {
*net.PacketConnWrapper
stats.Counter
Handler *Handler
DefaultRule *Firewall
DefaultRule *FinalRule
IsOverridden bool
InitUnchangedAddr net.Address
InitChangedAddr net.Address
@@ -563,7 +534,7 @@ func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
}
udpAddr := d.(*net.UDPAddr)
sourceAddr := net.IPAddress(udpAddr.IP)
if rule := r.Handler.matchRule(net.Network_UDP, sourceAddr, net.Port(udpAddr.Port), r.DefaultRule); rule != nil && rule.action == RuleAction_Block {
if rule := r.Handler.matchFinalRule(net.Network_UDP, sourceAddr, net.Port(udpAddr.Port), r.DefaultRule); rule != nil && rule.action == RuleAction_Block {
continue
}
b.Resize(0, int32(n))
@@ -588,7 +559,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 *Firewall, UDPOverride net.Destination, DialDest net.Destination, outGateway net.Address) buf.Writer {
func NewPacketWriter(conn net.Conn, h *Handler, defaultRule *FinalRule, UDPOverride net.Destination, DialDest net.Destination, outGateway net.Address) buf.Writer {
iConn := conn
statConn, ok := iConn.(*stat.CounterConnection)
if ok {
@@ -622,7 +593,7 @@ type PacketWriter struct {
*net.PacketConnWrapper
stats.Counter
*Handler
DefaultRule *Firewall
DefaultRule *FinalRule
UDPOverride net.Destination
// Dest of udp packets might be a domain, we will resolve them to IP
@@ -681,7 +652,7 @@ func (w *PacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
}
}
}
if rule := w.matchRule(net.Network_UDP, b.UDP.Address, b.UDP.Port, w.DefaultRule); rule != nil && rule.action == RuleAction_Block {
if rule := w.matchFinalRule(net.Network_UDP, b.UDP.Address, b.UDP.Port, w.DefaultRule); rule != nil && rule.action == RuleAction_Block {
b.Release()
continue
}
-87
View File
@@ -1,87 +0,0 @@
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))
}
})
}
}
-1
View File
@@ -150,7 +150,6 @@ Start:
To: request.URL,
Status: log.AccessAccepted,
Reason: "",
Email: inbound.User.Email,
})
if strings.EqualFold(request.Method, "CONNECT") {
+3 -1
View File
@@ -25,6 +25,7 @@ type Server struct {
config *ServerConfig
validator *Validator
policyManager policy.Manager
cone bool
}
// NewServer create a new Shadowsocks server.
@@ -46,6 +47,7 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
config: config,
validator: validator,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
}
return s, nil
@@ -183,7 +185,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
data.UDP = &destination
if dest == nil {
if !s.cone || dest == nil {
dest = &destination
}
+3 -3
View File
@@ -29,6 +29,7 @@ import (
type Server struct {
config *ServerConfig
policyManager policy.Manager
cone bool
httpServer *http.Server
}
@@ -38,6 +39,7 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
s := &Server{
config: config,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
}
httpConfig := &http.ServerConfig{
UserLevel: config.UserLevel,
@@ -147,7 +149,6 @@ func (s *Server) processTCP(ctx context.Context, conn stat.Connection, dispatche
To: dest,
Status: log.AccessAccepted,
Reason: "",
Email: inbound.User.Email,
})
}
if inbound.CanSpliceCopy == 2 {
@@ -269,13 +270,12 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
To: destination,
Status: log.AccessAccepted,
Reason: "",
Email: inbound.User.Email,
})
}
payload.UDP = &destination
if dest == nil {
if !s.cone || dest == nil {
dest = &destination
}
+3 -1
View File
@@ -38,6 +38,7 @@ type Server struct {
policyManager policy.Manager
validator *Validator
fallbacks map[string]map[string]map[string]*Fallback // or nil
cone bool
}
// NewServer creates a new trojan inbound handler.
@@ -58,6 +59,7 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
server := &Server{
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
validator: validator,
cone: ctx.Value("cone").(bool),
}
if config.Fallbacks != nil {
@@ -300,7 +302,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, sessionPolicy policy.Sess
}
errors.LogInfo(ctx, "tunnelling request to ", destination)
if dest == nil {
if !s.cone || dest == nil {
dest = &destination
}
+1 -9
View File
@@ -25,10 +25,7 @@ import (
// Handler is managing object that tie together tun interface, ip stack and dispatch connections to the routing
type Handler struct {
// ctx is detached from the instance's; cancel ends it, and with it every dispatch started from it,
// when the handler closes, since nothing else would
ctx context.Context
cancel context.CancelFunc
config *Config
stack Stack
tun Tun
@@ -99,7 +96,7 @@ func (t *Handler) Init(ctx context.Context, pm policy.Manager, dispatcher routin
t.sniffingRequest = content.SniffingRequest
}
t.ctx, t.cancel = context.WithCancel(core.ToBackgroundDetachedContext(ctx))
t.ctx = core.ToBackgroundDetachedContext(ctx)
t.policyManager = pm
t.dispatcher = dispatcher
@@ -268,11 +265,6 @@ func (t *Handler) HandleConnection(conn net.Conn, destination net.Destination) {
// Close implements common.Closable.
func (t *Handler) Close() error {
// cancel first so every dispatch in flight unwinds, then close the stack (resets TCP, ends UDP flows)
// and the tun
if t.cancel != nil {
t.cancel()
}
return errors.Combine(common.CloseIfExists(t.stack), common.CloseIfExists(t.tun))
}
-34
View File
@@ -179,37 +179,3 @@ func TestHandlerCountsTunConnectionTraffic(t *testing.T) {
t.Fatalf("connection write mismatch: got %q, want %q", got, "downlink")
}
}
// a dispatcher that only returns when its context ends
type blockingDispatcher struct {
testDispatcher
entered chan struct{}
}
func (d *blockingDispatcher) DispatchLink(ctx context.Context, dest xnet.Destination, link *transport.Link) error {
close(d.entered)
<-ctx.Done()
return ctx.Err()
}
// Closing the handler must end a dispatch that is not reading its connection: the handler's context
// is detached from the instance's, so Close is what cancels it
func TestHandlerCloseCancelsDispatches(t *testing.T) {
dispatcher := &blockingDispatcher{entered: make(chan struct{})}
handler := &Handler{config: &Config{}, dispatcher: dispatcher}
handler.ctx, handler.cancel = context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
handler.HandleConnection(newTestConn(nil), xnet.TCPDestination(xnet.LocalHostIP, 443))
close(done)
}()
<-dispatcher.entered
if err := handler.Close(); err != nil {
t.Fatal(err)
}
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("dispatch still running after Close")
}
}
-5
View File
@@ -148,11 +148,6 @@ func (s *stack) Close() error {
for _, u := range sockets {
u.queue.close()
}
// the UDP flows the other side opened are in neither conns nor sockets; end them too, or their
// dispatches and what they hold survive the instance
if s.udp != nil {
s.udp.closeAll()
}
return nil
}
+2 -1
View File
@@ -17,6 +17,7 @@ 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"
)
@@ -72,7 +73,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(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
{Tag: "block", ProxySettings: serial.ToTypedMessage(&blackhole.Config{})},
},
})
if err != nil {
-23
View File
@@ -16,8 +16,6 @@ type udpConnectionHandler struct {
sync.RWMutex
udpConns map[net.Destination]*udpConn
// closed is set by closeAll; a packet that arrives after it opens no flow
closed bool
handleConnection func(conn net.Conn, dest net.Destination)
writePacket func(data []byte, src net.Destination, dst net.Destination) error
@@ -53,10 +51,6 @@ func (u *udpConnectionHandler) HandlePacket(src net.Destination, dst net.Destina
u.Lock()
defer u.Unlock()
if u.closed {
data.Release()
return
}
conn, found = u.udpConns[src]
if !found {
conn = &udpConn{handler: u, queue: newPacketQueue(udpQueueLimit), src: src, dst: dst}
@@ -72,23 +66,6 @@ func (u *udpConnectionHandler) HandlePacket(src net.Destination, dst net.Destina
}
}
// closeAll ends every UDP flow and takes no new ones: the readers get EOF, so the dispatch of each flow
// returns and lets go of its outbound. Called when the stack closes; without it an inbound's UDP flows,
// and whatever carries them, outlive the instance.
func (u *udpConnectionHandler) closeAll() {
u.Lock()
u.closed = true
conns := make([]*udpConn, 0, len(u.udpConns))
for _, c := range u.udpConns {
conns = append(conns, c)
}
u.udpConns = make(map[net.Destination]*udpConn)
u.Unlock()
for _, c := range conns {
c.queue.close()
}
}
func (u *udpConnectionHandler) connectionFinished(conn *udpConn) {
u.Lock()
// Close runs twice per flow; a newer conn may already own this src.
-36
View File
@@ -89,39 +89,3 @@ func TestPacketQueueDropsDrainedStorage(t *testing.T) {
t.Fatalf("drained queue still holds %d slots", cap(q.items))
}
}
// A closing stack must end its UDP flows: the dispatch reading a flow gets EOF and returns, instead of
// waiting on the queue forever and keeping its outbound alive past the instance; a packet that arrives
// afterwards opens no flow.
func TestUDPHandlerCloseAllEndsFlows(t *testing.T) {
done := make(chan struct{}, 2)
handler := newUdpConnectionHandler(func(conn net.Conn, dest net.Destination) {
b := make([]byte, 2048)
for {
if _, err := conn.Read(b); err != nil {
done <- struct{}{}
return
}
}
}, func(data []byte, src net.Destination, dst net.Destination) error { return nil })
dst := net.UDPDestination(net.IPAddress([]byte{10, 6, 0, 2}), 53)
for _, port := range []net.Port{40000, 40001} {
src := net.UDPDestination(net.IPAddress([]byte{10, 255, 0, 2}), port)
handler.HandlePacket(src, dst, buf.FromBytes([]byte("query")))
}
handler.closeAll()
for i := 0; i < 2; i++ {
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatalf("flow %d still running after closeAll", i)
}
}
handler.HandlePacket(net.UDPDestination(net.IPAddress([]byte{10, 255, 0, 2}), 40002), dst, buf.FromBytes([]byte("late")))
handler.RLock()
n := len(handler.udpConns)
handler.RUnlock()
if n != 0 {
t.Fatalf("%d flows in the table after closeAll", n)
}
}
+3 -1
View File
@@ -50,6 +50,7 @@ func init() {
type Handler struct {
server *protocol.ServerSpec
policyManager policy.Manager
cone bool
encryption *encryption.ClientInstance
reverse *Reverse
@@ -77,6 +78,7 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
handler := &Handler{
server: server,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
}
a := handler.server.User.Account.(*vless.MemoryAccount)
@@ -298,7 +300,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
clientReader := link.Reader // .(*pipe.Reader)
clientWriter := link.Writer // .(*pipe.Writer)
trafficState := proxy.NewTrafficState(account.ID.Bytes())
if request.Command == protocol.RequestCommandUDP && (requestAddons.Flow == vless.XRV || (request.Port != 53 && request.Port != 443)) {
if request.Command == protocol.RequestCommandUDP && (requestAddons.Flow == vless.XRV || (h.cone && request.Port != 53 && request.Port != 443)) {
request.Command = protocol.RequestCommandMux
request.Address = net.DomainAddress("v1.mux.cool")
request.Port = net.Port(666)
+78 -19
View File
@@ -14,6 +14,8 @@ import (
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/common/signal"
"github.com/xtls/xray-core/common/task"
"github.com/xtls/xray-core/common/uuid"
"github.com/xtls/xray-core/core"
feature_inbound "github.com/xtls/xray-core/features/inbound"
@@ -21,7 +23,6 @@ import (
"github.com/xtls/xray-core/features/routing"
"github.com/xtls/xray-core/proxy/vmess"
"github.com/xtls/xray-core/proxy/vmess/encoding"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/internet/stat"
)
@@ -184,6 +185,44 @@ func (h *Handler) RemoveUser(ctx context.Context, email string) error {
return nil
}
func transferResponse(timer signal.ActivityUpdater, session *encoding.ServerSession, request *protocol.RequestHeader, response *protocol.ResponseHeader, input buf.Reader, output *buf.BufferedWriter) error {
session.EncodeResponseHeader(response, output)
bodyWriter, err := session.EncodeResponseBody(request, output)
if err != nil {
return errors.New("failed to start decoding response").Base(err)
}
{
// Optimize for small response packet
data, err := input.ReadMultiBuffer()
if err != nil {
return err
}
if err := bodyWriter.WriteMultiBuffer(data); err != nil {
return err
}
}
if err := output.SetBuffered(false); err != nil {
return err
}
if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil {
return err
}
account := request.User.Account.(*vmess.MemoryAccount)
if request.Option.Has(protocol.RequestOptionChunkStream) && !account.NoTerminationSignal {
if err := bodyWriter.WriteMultiBuffer(buf.MultiBuffer{}); err != nil {
return err
}
}
return nil
}
// Process implements proxy.Inbound.Process().
func (h *Handler) Process(ctx context.Context, network net.Network, connection stat.Connection, dispatcher routing.Dispatcher) error {
sessionPolicy := h.policyManager.ForLevel(0)
@@ -234,29 +273,49 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
inbound.CanSpliceCopy = 3
inbound.User = request.User
bodyReader, err := svrSession.DecodeRequestBody(request, reader)
sessionPolicy = h.policyManager.ForLevel(request.User.Level)
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
link, err := dispatcher.Dispatch(ctx, request.Destination())
if err != nil {
return errors.New("failed to start decoding").Base(err)
return errors.New("failed to dispatch request to ", request.Destination()).Base(err)
}
writer := buf.NewBufferedWriter(buf.NewWriter(connection))
response := &protocol.ResponseHeader{
Command: h.generateCommand(ctx, request),
}
svrSession.EncodeResponseHeader(response, writer)
bodyWriter, err := svrSession.EncodeResponseBody(request, writer)
if err != nil {
return errors.New("failed to start decoding response").Base(err)
}
writer.SetFlushNext()
requestDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
if err := dispatcher.DispatchLink(ctx, request.Destination(), &transport.Link{
Reader: bodyReader,
Writer: bodyWriter,
},
); err != nil {
return errors.New("failed to dispatch request").Base(err)
bodyReader, err := svrSession.DecodeRequestBody(request, reader)
if err != nil {
return errors.New("failed to start decoding").Base(err)
}
if err := buf.Copy(bodyReader, link.Writer, buf.UpdateActivity(timer)); err != nil {
return errors.New("failed to transfer request").Base(err)
}
return nil
}
responseDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
writer := buf.NewBufferedWriter(buf.NewWriter(connection))
defer writer.Flush()
response := &protocol.ResponseHeader{
Command: h.generateCommand(ctx, request),
}
return transferResponse(timer, svrSession, request, response, link.Reader, writer)
}
requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
common.Interrupt(link.Reader)
common.Interrupt(link.Writer)
return errors.New("connection ends").Base(err)
}
return nil
}
+3 -1
View File
@@ -32,6 +32,7 @@ import (
type Handler struct {
server *protocol.ServerSpec
policyManager policy.Manager
cone bool
}
// New creates a new VMess outbound handler.
@@ -48,6 +49,7 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
handler := &Handler{
server: server,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
}
return handler, nil
@@ -141,7 +143,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
}
}, sessionPolicy.Timeouts.ConnectionIdle)
if request.Command == protocol.RequestCommandUDP && request.Port != 53 && request.Port != 443 {
if request.Command == protocol.RequestCommandUDP && h.cone && request.Port != 53 && request.Port != 443 {
request.Command = protocol.RequestCommandMux
request.Address = net.DomainAddress("v1.mux.cool")
request.Port = net.Port(666)
+5 -5
View File
@@ -71,7 +71,7 @@ func TestCommanderListenConfigurationItem(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "default-outbound",
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
},
},
}
@@ -166,7 +166,7 @@ func TestCommanderRemoveHandler(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "default-outbound",
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{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{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
},
},
}
@@ -390,7 +390,7 @@ func TestCommanderAddRemoveUser(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -579,7 +579,7 @@ func TestCommanderStats(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
+2 -1
View File
@@ -13,6 +13,7 @@ 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"
@@ -77,7 +78,7 @@ func TestResolveIP(t *testing.T) {
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
},
{
Tag: "direct",
+2 -2
View File
@@ -60,7 +60,7 @@ func TestDokodemoTCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -163,7 +163,7 @@ func TestDokodemoUDP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
+11 -10
View File
@@ -21,6 +21,7 @@ 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"
@@ -61,7 +62,7 @@ func TestPassiveConnection(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -122,7 +123,7 @@ func TestDialerProxy(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -151,7 +152,7 @@ func TestDialerProxy(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -253,7 +254,7 @@ func TestDialerProxyOverKCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -282,7 +283,7 @@ func TestDialerProxyOverKCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
@@ -401,11 +402,11 @@ func TestBlackhole(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "direct",
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
},
{
Tag: "blocked",
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
},
},
App: []*serial.TypedMessage{
@@ -516,7 +517,7 @@ func TestUDPConnection(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -581,7 +582,7 @@ func TestDomainSniffing(t *testing.T) {
},
{
Tag: "direct",
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
},
},
App: []*serial.TypedMessage{
@@ -668,7 +669,7 @@ func TestDialXray(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
+6 -6
View File
@@ -50,7 +50,7 @@ func TestHttpConformance(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -113,7 +113,7 @@ func TestHttpError(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -163,7 +163,7 @@ func TestHTTPConnectMethod(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -245,7 +245,7 @@ func TestHttpPost(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -317,7 +317,7 @@ func TestHttpBasicAuth(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -405,7 +405,7 @@ func TestHTTPOutboundServerFirst(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
+1 -1
View File
@@ -499,7 +499,7 @@ func masqueServerConfig(serverPort net.Port, certificate *tls.Certificate, h2 bo
Port: uint32(dest.Port),
},
},
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
}
}
+1 -1
View File
@@ -63,7 +63,7 @@ func TestMetrics(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "default-outbound",
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
},
},
}
+2 -2
View File
@@ -85,7 +85,7 @@ func TestVMessClosing(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -193,7 +193,7 @@ func TestZeroBuffer(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
+5 -4
View File
@@ -17,6 +17,7 @@ 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"
@@ -99,7 +100,7 @@ func TestReverseProxy(t *testing.T) {
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
},
},
}
@@ -150,7 +151,7 @@ func TestReverseProxy(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "freedom",
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
},
{
Tag: "reverse",
@@ -274,7 +275,7 @@ func TestReverseProxyLongRunning(t *testing.T) {
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
},
},
}
@@ -339,7 +340,7 @@ func TestReverseProxyLongRunning(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "freedom",
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
},
{
Tag: "reverse",
+2 -2
View File
@@ -91,7 +91,7 @@ func testShadowsocks2022Tcp(t *testing.T, method string, password string) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{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{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
+4 -4
View File
@@ -53,7 +53,7 @@ func TestShadowsocksChaCha20Poly1305TCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -141,7 +141,7 @@ func TestShadowsocksAES256GCMTCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -236,7 +236,7 @@ func TestShadowsocksAES128GCMUDP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -330,7 +330,7 @@ func TestShadowsocksAES128GCMUDPMux(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
+7 -6
View File
@@ -11,6 +11,7 @@ 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"
@@ -50,7 +51,7 @@ func TestSocksBridgeTCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -127,7 +128,7 @@ func TestSocksWithHttpRequest(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -216,7 +217,7 @@ func TestSocksBridageUDP(t *testing.T) {
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
},
},
}
@@ -330,11 +331,11 @@ func TestSocksBridageUDPWithRouting(t *testing.T) {
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
},
{
Tag: "out",
ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
},
},
}
@@ -434,7 +435,7 @@ func TestSocksConformanceMod(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
+10 -10
View File
@@ -69,7 +69,7 @@ func TestSimpleTLSConnection(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -182,7 +182,7 @@ func TestAutoIssuingCertificate(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -287,7 +287,7 @@ func TestTLSOverKCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -387,7 +387,7 @@ func TestTLSOverWebSocket(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -503,7 +503,7 @@ func TestGRPC(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -619,7 +619,7 @@ func TestGRPCMultiMode(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -728,7 +728,7 @@ func TestSimpleTLSConnectionPinned(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -827,7 +827,7 @@ func TestSimpleTLSConnectionPinnedWrongCert(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -925,7 +925,7 @@ func TestUTLSConnectionPinned(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -1025,7 +1025,7 @@ func TestUTLSConnectionPinnedWrongCert(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
+1 -1
View File
@@ -63,7 +63,7 @@ func TestHTTPConnectionHeader(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
+8 -8
View File
@@ -70,7 +70,7 @@ func TestVless(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -175,7 +175,7 @@ func TestVlessTls(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -298,7 +298,7 @@ func TestVlessXtlsVision(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -430,7 +430,7 @@ func TestVlessXtlsVisionReality(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -569,7 +569,7 @@ func TestVlessRealityFingerprints(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -661,7 +661,7 @@ func TestVlessRealityFingerprints(t *testing.T) {
wg.Wait()
}
// A blocked connection must close after firewall.delay even while the client keeps it open and sends nothing.
// A blocked connection must close after finalRules.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{
Firewall: []*freedom.FirewallConfig{
FinalRules: []*freedom.FinalRuleConfig{
{
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 firewall.delay", elapsed)
t.Fatalf("connection is closed after %v, before finalRules.delay", elapsed)
}
})
}
+10 -10
View File
@@ -62,7 +62,7 @@ func TestVMessGCM(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -162,7 +162,7 @@ func TestVMessGCMReadv(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -265,7 +265,7 @@ func TestVMessGCMUDP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -362,7 +362,7 @@ func TestVMessChacha20(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -463,7 +463,7 @@ func TestVMessKCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -568,7 +568,7 @@ func TestVMessKCPLarge(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -674,7 +674,7 @@ func TestVMessGCMMux(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -787,7 +787,7 @@ func TestVMessGCMMuxUDP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -910,7 +910,7 @@ func TestVMessGCMLengthAuth(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
@@ -1012,7 +1012,7 @@ func TestVMessGCMLengthAuthPlusNoTerminationSignal(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
},
},
+1 -1
View File
@@ -61,7 +61,7 @@ func TestWireguard(t *testing.T) {
Port: uint32(dest.Port),
},
},
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
}),
}
}
@@ -9,11 +9,9 @@ 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)
}
@@ -87,9 +85,6 @@ 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)
@@ -1,31 +0,0 @@
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
}
@@ -1,123 +0,0 @@
// 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
}
@@ -1,11 +0,0 @@
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;
}
@@ -1,93 +0,0 @@
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)
}
}
})
}
}
}
@@ -279,7 +279,7 @@ func runVLESSRealityCase(t *testing.T, bin string, mode trafficMode, payloadSize
},
Outbound: []*core.OutboundHandlerConfig{
{ProxySettings: serial.ToTypedMessage(&freedom.Config{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{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{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{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{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{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{
Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
})},
},
})
+8 -18
View File
@@ -32,9 +32,6 @@ type clientConn struct {
paddingSchedule []paddingTurn
packet *packetStream
deadlines *connectionDeadlines
done chan struct{}
closeOnce sync.Once
}
type clientState int
@@ -44,7 +41,7 @@ var (
clientStateProxy clientState = 2
)
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn) (*clientConn, error) {
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, padding []*Padding) (*clientConn, error) {
if len(rsaPublicKey) == 0 {
return nil, fmt.Errorf("empty rsa public key")
}
@@ -54,6 +51,10 @@ func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPubl
if len(password) > MaxLegacyPasswordLength {
return nil, fmt.Errorf("password is longer than %d bytes", MaxLegacyPasswordLength)
}
paddingSchedule, err := newPaddingSchedule(padding, true)
if err != nil {
return nil, fmt.Errorf("select padding profile: %w", err)
}
return &clientConn{
reader: bufio.NewReader(c),
writer: c,
@@ -66,15 +67,9 @@ func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPubl
hostname: hostname,
paddingSchedule: paddingSchedule,
deadlines: newConnectionDeadlines(c),
done: make(chan struct{}),
}, nil
}
// paddingPause applies one padding pause, stopping early on Close.
func (c *clientConn) paddingPause(d time.Duration) error {
return pausePadding(c.done, d)
}
func (c *clientConn) handshake() error {
c.handshakeLock.Lock()
defer c.handshakeLock.Unlock()
@@ -204,9 +199,7 @@ func (c *clientConn) handshake() error {
return fmt.Errorf("read login finished: %w", err)
}
// Set Compression is not compressed itself and must be handled before the
// packet that follows it, which already uses the compressed framing. The
// threshold only decides whether the framing applies: this writer never
// compresses, so a server-side threshold does not shrink padding turns.
// packet that follows it, which already uses the compressed framing.
if pkt.packetID == 0x03 {
var threshold Varint
if thresholdErr := pkt.readFields(&threshold); thresholdErr != nil {
@@ -214,7 +207,7 @@ func (c *clientConn) handshake() error {
}
if threshold >= 0 {
c.reader = newCompressionReader(c.reader)
c.writer = newCompressionWriter(c.writer)
c.writer = newCompressionWriter(c.writer, int32(threshold))
}
pkt, err = readPacket(c.reader)
if err != nil {
@@ -243,9 +236,7 @@ func (c *clientConn) handshake() error {
if err != nil {
return fmt.Errorf("write login acknowledged: %w", err)
}
c.reader = newPaddingReader(c.reader, true)
if err = runPaddingSchedule(c.writer, true, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause); err != nil {
_ = c.Close() // Unblock the startup reader if writing failed.
if err = runPaddingSchedule(c.writer, true, loginAcknowledgedLength, c.paddingSchedule); err != nil {
return fmt.Errorf("run startup padding: %w", err)
}
@@ -288,7 +279,6 @@ func (c *clientConn) Close() error {
c.closed = true
packet := c.packet
c.lifecycleMu.Unlock()
c.closeOnce.Do(func() { close(c.done) })
if packet != nil {
packet.Stop()
}
+34 -20
View File
@@ -1,6 +1,4 @@
// Minecraft compression framing, negotiated by the login Set Compression packet.
// The reader decodes whatever the peer sends, including deflated bodies; the
// writer always sends the uncompressed variant.
package xmc
import (
@@ -101,21 +99,14 @@ func (c *compressionReader) readFrame() error {
// compressionWriter converts a plain frame (VarInt body length, body) into the
// post-Set Compression framing. Frames are buffered until complete, because a
// caller may split one frame across several Write calls.
//
// It never compresses, whatever the negotiated threshold is. What XMC writes is
// padding and proxied bytes: the padding exists for its size on the wire, so
// deflating it would shrink a padded turn from tens of kilobytes to a hundred
// bytes and erase the shape it is there for, and proxied bytes are already
// encrypted or compressed by whoever produced them. Vanilla accepts an
// uncompressed body of any size when Data Length is zero, so the framing alone
// is enough to stay inside the protocol.
type compressionWriter struct {
w io.Writer
pending []byte
w io.Writer
threshold int32
pending []byte
}
func newCompressionWriter(w io.Writer) io.Writer {
return &compressionWriter{w: w}
func newCompressionWriter(w io.Writer, threshold int32) io.Writer {
return &compressionWriter{w: w, threshold: threshold}
}
func (c *compressionWriter) Write(p []byte) (int, error) {
@@ -165,13 +156,36 @@ func (c *compressionWriter) nextFrame() ([]byte, bool, error) {
}
func (c *compressionWriter) writeFrame(body []byte) error {
// Packet Length covers the Data Length varint and the body; a zero Data
// Length is the uncompressed variant.
packetLength := 1 + len(body)
if len(body) >= int(c.threshold) {
var compressed bytes.Buffer
zw := zlib.NewWriter(&compressed)
if _, err := zw.Write(body); err != nil {
_ = zw.Close()
return fmt.Errorf("compress packet: %w", err)
}
if err := zw.Close(); err != nil {
return fmt.Errorf("close compressor: %w", err)
}
var frame bytes.Buffer
packetLength := varintSize(Varint(len(body))) + compressed.Len()
frame.Grow(varintSize(Varint(packetLength)) + packetLength)
packetLengthVarint := Varint(packetLength)
if err := packetLengthVarint.writeTo(&frame); err != nil {
return err
}
bodyLength := Varint(len(body))
if err := bodyLength.writeTo(&frame); err != nil {
return err
}
frame.Write(compressed.Bytes())
return writeFull(c.w, frame.Bytes())
}
var frame bytes.Buffer
frame.Grow(varintSize(Varint(packetLength)) + packetLength)
packetLengthVarint := Varint(packetLength)
if err := packetLengthVarint.writeTo(&frame); err != nil {
frame.Grow(varintSize(Varint(1+len(body))) + 1 + len(body))
frameLength := Varint(1 + len(body))
if err := frameLength.writeTo(&frame); err != nil {
return err
}
frame.WriteByte(0)
@@ -2,7 +2,6 @@ package xmc
import (
"bytes"
"compress/zlib"
"crypto/rand"
"errors"
"io"
@@ -50,39 +49,39 @@ func randomBody(t *testing.T, size int) []byte {
return body
}
// TestCompressionWriterNeverCompresses pins the write policy: whatever the
// negotiated threshold is, XMC sends the uncompressed framing so that a padding
// turn keeps its wire size. A padded turn of zeros would otherwise deflate from
// tens of kilobytes to a hundred bytes and the shape would be gone.
func TestCompressionWriterNeverCompresses(t *testing.T) {
for _, size := range []int{1, 10, 255, 256, 257, 32768, 65535, 65536} {
for _, body := range [][]byte{bytes.Repeat([]byte{0}, size), randomBody(t, size)} {
func TestCompressionWriterThreshold(t *testing.T) {
for _, threshold := range []int32{0, 1, 256, 65536} {
for _, size := range []int{1, 10, 255, 256, 257, 65535, 65536} {
body := bytes.Repeat([]byte{0}, size)
var wire bytes.Buffer
w := newCompressionWriter(&wire)
w := newCompressionWriter(&wire, threshold)
if _, err := w.Write(plainFrame(body)); err != nil {
t.Fatalf("size %d: write: %v", size, err)
t.Fatalf("threshold %d size %d: write: %v", threshold, size, err)
}
frame := readWireFrame(t, bytes.NewReader(wire.Bytes()))
if frame.dataLength != 0 {
t.Fatalf("size %d: writer compressed the body (data length %d)", size, frame.dataLength)
wantCompressed := int32(size) >= threshold
if wantCompressed && frame.dataLength != size {
t.Fatalf("threshold %d size %d: want compressed data length %d, got %d", threshold, size, size, frame.dataLength)
}
if !bytes.Equal(frame.payload, body) {
t.Fatalf("size %d: payload mismatch", size)
}
if frame.packetLength != 1+size {
t.Fatalf("size %d: packet length %d, want %d", size, frame.packetLength, 1+size)
}
if wire.Len() != varintSize(Varint(1+size))+1+size {
t.Fatalf("size %d: frame is %d bytes on the wire, want %d", size, wire.Len(), varintSize(Varint(1+size))+1+size)
if !wantCompressed {
if frame.dataLength != 0 {
t.Fatalf("threshold %d size %d: want uncompressed frame, got data length %d", threshold, size, frame.dataLength)
}
if !bytes.Equal(frame.payload, body) {
t.Fatalf("threshold %d size %d: uncompressed payload mismatch", threshold, size)
}
if frame.packetLength != 1+size {
t.Fatalf("threshold %d size %d: packet length %d", threshold, size, frame.packetLength)
}
}
decoded, _, err := readFrame(newCompressionReader(bytes.NewReader(wire.Bytes())), maxUncompressedFrameBody)
if err != nil {
t.Fatalf("size %d: decode: %v", size, err)
t.Fatalf("threshold %d size %d: decode: %v", threshold, size, err)
}
if !bytes.Equal(decoded, body) {
t.Fatalf("size %d: round trip mismatch", size)
t.Fatalf("threshold %d size %d: round trip mismatch", threshold, size)
}
}
}
@@ -97,36 +96,38 @@ func TestCompressionRoundTripChunked(t *testing.T) {
bytes.Repeat([]byte("xmc"), 8*1024),
}
var wire bytes.Buffer
w := newCompressionWriter(&wire)
// One Write per frame, split into awkward chunk sizes.
for _, body := range cases {
frame := plainFrame(body)
for len(frame) > 0 {
n := 7
if n > len(frame) {
n = len(frame)
for _, threshold := range []int32{0, 256, 65536} {
var wire bytes.Buffer
w := newCompressionWriter(&wire, threshold)
// One Write per frame, split into awkward chunk sizes.
for _, body := range cases {
frame := plainFrame(body)
for len(frame) > 0 {
n := 7
if n > len(frame) {
n = len(frame)
}
if _, err := w.Write(frame[:n]); err != nil {
t.Fatalf("threshold %d: chunked write: %v", threshold, err)
}
frame = frame[n:]
}
if _, err := w.Write(frame[:n]); err != nil {
t.Fatalf("chunked write: %v", err)
}
frame = frame[n:]
}
}
r := newCompressionReader(bytes.NewReader(wire.Bytes()))
for i, want := range cases {
got, _, err := readFrame(r, maxUncompressedFrameBody)
if err != nil {
t.Fatalf("frame %d: decode: %v", i, err)
r := newCompressionReader(bytes.NewReader(wire.Bytes()))
for i, want := range cases {
got, _, err := readFrame(r, maxUncompressedFrameBody)
if err != nil {
t.Fatalf("threshold %d frame %d: decode: %v", threshold, i, err)
}
if !bytes.Equal(got, want) {
t.Fatalf("threshold %d frame %d: mismatch (%d vs %d bytes)", threshold, i, len(got), len(want))
}
}
if !bytes.Equal(got, want) {
t.Fatalf("frame %d: mismatch (%d vs %d bytes)", i, len(got), len(want))
if _, _, err := readFrame(r, maxUncompressedFrameBody); !errors.Is(err, io.EOF) {
t.Fatalf("threshold %d: expected EOF after the last frame, got %v", threshold, err)
}
}
if _, _, err := readFrame(r, maxUncompressedFrameBody); !errors.Is(err, io.EOF) {
t.Fatalf("expected EOF after the last frame, got %v", err)
}
}
func TestCompressionMultipleFramesOneWrite(t *testing.T) {
@@ -137,7 +138,7 @@ func TestCompressionMultipleFramesOneWrite(t *testing.T) {
}
var wire bytes.Buffer
w := newCompressionWriter(&wire)
w := newCompressionWriter(&wire, 256)
if _, err := w.Write(plain); err != nil {
t.Fatalf("write: %v", err)
}
@@ -175,40 +176,6 @@ func TestCompressionReaderUncompressedOverThreshold(t *testing.T) {
}
}
// The writer stopped compressing, but a real server still does, so the reader
// must keep decoding deflated bodies.
func TestCompressionReaderDecodesCompressedBody(t *testing.T) {
body := append(bytes.Repeat([]byte("xmc"), 4096), 0, 1, 2, 3)
var compressed bytes.Buffer
zw := zlib.NewWriter(&compressed)
if _, err := zw.Write(body); err != nil {
t.Fatal(err)
}
if err := zw.Close(); err != nil {
t.Fatal(err)
}
var wire bytes.Buffer
packetLength := Varint(varintSize(Varint(len(body))) + compressed.Len())
if err := packetLength.writeTo(&wire); err != nil {
t.Fatal(err)
}
dataLength := Varint(len(body))
if err := dataLength.writeTo(&wire); err != nil {
t.Fatal(err)
}
wire.Write(compressed.Bytes())
got, _, err := readFrame(newCompressionReader(bytes.NewReader(wire.Bytes())), maxUncompressedFrameBody)
if err != nil {
t.Fatalf("decode: %v", err)
}
if !bytes.Equal(got, body) {
t.Fatal("payload mismatch")
}
}
func TestCompressionReaderErrors(t *testing.T) {
// Compressed packet with a bogus body.
var badZlib bytes.Buffer
@@ -246,7 +213,7 @@ func TestCompressionReaderErrors(t *testing.T) {
func TestCompressionWriterInvalidFrameLength(t *testing.T) {
var wire bytes.Buffer
w := newCompressionWriter(&wire)
w := newCompressionWriter(&wire, 256)
if _, err := w.Write([]byte{0xff, 0xff, 0xff, 0xff, 0xff}); err == nil {
t.Fatal("expected an error for an invalid frame length prefix")
}
+14 -56
View File
@@ -23,11 +23,7 @@ func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *fi
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
paddingSchedule, err := c.paddingSchedule(true)
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
cc, err := newClientConn(conn, profiles, c.Password, c.RsaPublicKey, c.Hostname, paddingSchedule)
cc, err := newClientConn(conn, profiles, c.Password, c.RsaPublicKey, c.Hostname, c.Paddings)
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
@@ -40,11 +36,7 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
paddingSchedule, err := c.paddingSchedule(false)
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, paddingSchedule)
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, c.Paddings)
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
@@ -52,53 +44,16 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
return cc, nil
}
// ValidatePadding checks the configured startup turns (including their bounds)
// without selecting a built-in preset.
// ValidatePadding checks custom startup turns without selecting a built-in preset.
func (c *Config) ValidatePadding() error {
if c.NoPadding {
if len(c.Paddings) != 0 {
return fmt.Errorf("padding is disabled and configured at the same time")
}
return nil
}
_, err := paddingScheduleFromConfig(c.Paddings)
return err
}
// paddingSchedule selects the padding turns for one connection. An explicit
// empty configuration disables padding; an absent one keeps the built-in
// preset.
//
// A configured list is the complete schedule, not a replacement for its startup
// part: the built-in preset also carries a Play-state join tail, and that tail
// runs only with the preset. A user who captured their own login decides the
// whole shape, including whether it has a tail.
func (c *Config) paddingSchedule(isClient bool) ([]paddingTurn, error) {
if c.NoPadding {
if len(c.Paddings) != 0 {
return nil, fmt.Errorf("padding is disabled and configured at the same time")
}
return nil, nil
}
if len(c.Paddings) > 0 {
return paddingScheduleFromConfig(c.Paddings)
}
if isClient {
return newClientPaddingSchedule2612()
}
return newServerPaddingSchedule2612()
}
// paddingScheduleFromConfig builds the complete schedule from a configured list.
// The list replaces the preset entirely, including its Play-state join tail.
func paddingScheduleFromConfig(paddings []*Padding) ([]paddingTurn, error) {
if len(paddings) == 0 {
return nil, nil
}
if len(paddings) > maxPaddingTurns {
return nil, fmt.Errorf("too many padding turns: %d (at most %d)", len(paddings), maxPaddingTurns)
}
var totalLength, totalDelayMilliseconds int64
schedule := make([]paddingTurn, len(paddings))
for i, turn := range paddings {
if turn == nil || turn.LengthMin < 1 || turn.LengthMax < turn.LengthMin || turn.LengthMax > maxPaddingTurnLength {
@@ -110,14 +65,6 @@ func paddingScheduleFromConfig(paddings []*Padding) ([]paddingTurn, error) {
if turn.DelayMax > maxPaddingDelayMilliseconds {
return nil, fmt.Errorf("padding delay range %d-%d at turn %d is too large", turn.DelayMin, turn.DelayMax, i)
}
totalLength += turn.LengthMax
if totalLength > maxPaddingTotalLength {
return nil, fmt.Errorf("padding turns are longer than %d bytes in total", maxPaddingTotalLength)
}
totalDelayMilliseconds += turn.DelayMax
if totalDelayMilliseconds > int64(maxPaddingScheduleDelay/time.Millisecond) {
return nil, fmt.Errorf("padding pauses are longer than %s in total", maxPaddingScheduleDelay)
}
var direction paddingDirection
switch turn.Direction {
case 1:
@@ -143,3 +90,14 @@ func paddingScheduleFromConfig(paddings []*Padding) ([]paddingTurn, error) {
}
return schedule, nil
}
func newPaddingSchedule(paddings []*Padding, isClient bool) ([]paddingTurn, error) {
schedule, err := paddingScheduleFromConfig(paddings)
if err != nil || schedule != nil {
return schedule, err
}
if isClient {
return newClientPaddingSchedule2612()
}
return newServerPaddingSchedule2612()
}
+7 -26
View File
@@ -99,13 +99,8 @@ type Config struct {
RsaPublicKey []byte `protobuf:"bytes,9,opt,name=rsa_public_key,json=rsaPublicKey,proto3" json:"rsa_public_key,omitempty"`
Hostname string `protobuf:"bytes,10,opt,name=hostname,proto3" json:"hostname,omitempty"`
Profiles []*Profile `protobuf:"bytes,11,rep,name=profiles,proto3" json:"profiles,omitempty"`
// Padding turns. Empty uses the built-in preset, unless no_padding is set.
// A configured list is the complete schedule and replaces the preset
// entirely: the preset's Play-state join tail runs only with the preset.
Paddings []*Padding `protobuf:"bytes,12,rep,name=paddings,proto3" json:"paddings,omitempty"`
// Disables startup padding. The configuration sets this for an explicit
// empty "paddings" array, which an unset repeated field cannot express.
NoPadding bool `protobuf:"varint,14,opt,name=no_padding,json=noPadding,proto3" json:"no_padding,omitempty"`
// Startup padding turns. Empty uses the built-in preset.
Paddings []*Padding `protobuf:"bytes,12,rep,name=paddings,proto3" json:"paddings,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -182,27 +177,15 @@ func (x *Config) GetPaddings() []*Padding {
return nil
}
func (x *Config) GetNoPadding() bool {
if x != nil {
return x.NoPadding
}
return false
}
type Padding struct {
state protoimpl.MessageState `protogen:"open.v1"`
LengthMin int64 `protobuf:"varint,1,opt,name=length_min,json=lengthMin,proto3" json:"length_min,omitempty"`
LengthMax int64 `protobuf:"varint,2,opt,name=length_max,json=lengthMax,proto3" json:"length_max,omitempty"`
// 1 = client to server, 2 = server to client
Direction int32 `protobuf:"varint,3,opt,name=direction,proto3" json:"direction,omitempty"`
// Millisecond pause that leads into this turn: it sits between the previous
// padding turn (or Login Acknowledged, for the first turn) and this turn's
// bytes, so a captured gap is written on the turn that follows it. The side
// that sends the turn waits for a uniformly selected value in
// [delay_min, delay_max]; the peer spends exactly delay_min at the same
// place, so only the sending side jitters: use delay_min == delay_max to
// reproduce a captured gap. Nothing pauses after the last turn. Zero means
// no pause.
// Millisecond pause after this turn, including the last one. The sender
// waits for a uniformly selected value in [delay_min, delay_max]; the
// receiver waits at least delay_min. Zero means no delay.
DelayMin int64 `protobuf:"varint,4,opt,name=delay_min,json=delayMin,proto3" json:"delay_min,omitempty"`
DelayMax int64 `protobuf:"varint,5,opt,name=delay_max,json=delayMax,proto3" json:"delay_max,omitempty"`
unknownFields protoimpl.UnknownFields
@@ -283,7 +266,7 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
"\busername\x18\x01 \x01(\tR\busername\x12\x12\n" +
"\x04uuid\x18\x02 \x01(\fR\x04uuid\x12%\n" +
"\x0etextures_value\x18\x03 \x01(\tR\rtexturesValue\x12-\n" +
"\x12textures_signature\x18\x04 \x01(\tR\x11texturesSignature\"\xcb\x02\n" +
"\x12textures_signature\x18\x04 \x01(\tR\x11texturesSignature\"\xac\x02\n" +
"\x06Config\x12\x1a\n" +
"\bpassword\x18\x01 \x01(\tR\bpassword\x12&\n" +
"\x0frsa_private_key\x18\b \x01(\fR\rrsaPrivateKey\x12$\n" +
@@ -291,9 +274,7 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
"\bhostname\x18\n" +
" \x01(\tR\bhostname\x12J\n" +
"\bprofiles\x18\v \x03(\v2..xray.transport.internet.finalmask.xmc.ProfileR\bprofiles\x12J\n" +
"\bpaddings\x18\f \x03(\v2..xray.transport.internet.finalmask.xmc.PaddingR\bpaddings\x12\x1d\n" +
"\n" +
"no_padding\x18\x0e \x01(\bR\tnoPaddingJ\x04\b\x02\x10\x03\"\x9f\x01\n" +
"\bpaddings\x18\f \x03(\v2..xray.transport.internet.finalmask.xmc.PaddingR\bpaddingsJ\x04\b\x02\x10\x03\"\x9f\x01\n" +
"\aPadding\x12\x1d\n" +
"\n" +
"length_min\x18\x01 \x01(\x03R\tlengthMin\x12\x1d\n" +
+4 -14
View File
@@ -23,13 +23,8 @@ message Config {
bytes rsa_public_key = 9;
string hostname = 10;
repeated Profile profiles = 11;
// Padding turns. Empty uses the built-in preset, unless no_padding is set.
// A configured list is the complete schedule and replaces the preset
// entirely: the preset's Play-state join tail runs only with the preset.
// Startup padding turns. Empty uses the built-in preset.
repeated Padding paddings = 12;
// Disables startup padding. The configuration sets this for an explicit
// empty "paddings" array, which an unset repeated field cannot express.
bool no_padding = 14;
}
message Padding {
@@ -37,14 +32,9 @@ message Padding {
int64 length_max = 2;
// 1 = client to server, 2 = server to client
int32 direction = 3;
// Millisecond pause that leads into this turn: it sits between the previous
// padding turn (or Login Acknowledged, for the first turn) and this turn's
// bytes, so a captured gap is written on the turn that follows it. The side
// that sends the turn waits for a uniformly selected value in
// [delay_min, delay_max]; the peer spends exactly delay_min at the same
// place, so only the sending side jitters: use delay_min == delay_max to
// reproduce a captured gap. Nothing pauses after the last turn. Zero means
// no pause.
// Millisecond pause after this turn, including the last one. The sender
// waits for a uniformly selected value in [delay_min, delay_max]; the
// receiver waits at least delay_min. Zero means no delay.
int64 delay_min = 4;
int64 delay_max = 5;
}
@@ -1,11 +1,9 @@
package xmc
import (
"errors"
"net"
"strings"
"testing"
"time"
)
func TestClientRejectsLongLegacyPassword(t *testing.T) {
@@ -23,126 +21,3 @@ func TestClientRejectsLongLegacyPassword(t *testing.T) {
t.Fatal("expected the long password to be rejected")
}
}
func TestPaddingScheduleCaps(t *testing.T) {
turn := func(length, delay int64) *Padding {
return &Padding{LengthMin: length, LengthMax: length, Direction: 1, DelayMin: delay, DelayMax: delay}
}
t.Run("too many turns", func(t *testing.T) {
paddings := make([]*Padding, maxPaddingTurns+1)
for i := range paddings {
paddings[i] = turn(3, 0)
}
if _, err := paddingScheduleFromConfig(paddings); err == nil {
t.Fatal("expected a turn count error")
}
})
t.Run("too many bytes", func(t *testing.T) {
paddings := make([]*Padding, maxPaddingTotalLength/maxPaddingTurnLength+1)
for i := range paddings {
paddings[i] = turn(maxPaddingTurnLength, 0)
}
if _, err := paddingScheduleFromConfig(paddings); err == nil {
t.Fatal("expected a total length error")
}
})
t.Run("too much delay", func(t *testing.T) {
tooLong := int64(maxPaddingScheduleDelay/time.Millisecond) + 1
if _, err := paddingScheduleFromConfig([]*Padding{turn(3, tooLong)}); err == nil {
t.Fatal("expected a total delay error")
}
if _, err := paddingScheduleFromConfig([]*Padding{turn(3, int64(maxPaddingScheduleDelay/time.Millisecond))}); err != nil {
t.Fatalf("delay at the limit was rejected: %v", err)
}
})
}
func TestPaddingDisabled(t *testing.T) {
config := &Config{NoPadding: true}
if err := config.ValidatePadding(); err != nil {
t.Fatalf("disabled padding failed validation: %v", err)
}
schedule, err := config.paddingSchedule(true)
if err != nil {
t.Fatal(err)
}
if schedule != nil {
t.Fatalf("disabled padding returned %d turns", len(schedule))
}
config.Paddings = []*Padding{{LengthMin: 3, LengthMax: 3, Direction: 1}}
if err := config.ValidatePadding(); err == nil {
t.Fatal("expected a conflict between disabled and configured padding")
}
if _, err := config.paddingSchedule(false); err == nil {
t.Fatal("expected a conflict between disabled and configured padding")
}
preset := &Config{}
if schedule, err := preset.paddingSchedule(true); err != nil || len(schedule) == 0 {
t.Fatalf("client preset = %d turns, err %v", len(schedule), err)
}
if schedule, err := preset.paddingSchedule(false); err != nil || len(schedule) == 0 {
t.Fatalf("server preset = %d turns, err %v", len(schedule), err)
}
}
// TestConfiguredPaddingsReplaceTheWholePreset pins the documented policy: a
// configured list is the complete schedule, so the preset's Play-state join tail
// does not run behind it on either end.
func TestConfiguredPaddingsReplaceTheWholePreset(t *testing.T) {
config := &Config{Paddings: []*Padding{
{LengthMin: 44, LengthMax: 44, Direction: 1},
{LengthMin: 64, LengthMax: 64, Direction: 2},
}}
for _, isClient := range []bool{true, false} {
schedule, err := config.paddingSchedule(isClient)
if err != nil {
t.Fatal(err)
}
if len(schedule) != len(config.Paddings) {
t.Fatalf("isClient=%v: schedule has %d turns, want the %d configured turns", isClient, len(schedule), len(config.Paddings))
}
for i, turn := range schedule {
want := paddingClientToServer
if config.Paddings[i].Direction == 2 {
want = paddingServerToClient
}
if turn.direction != want || turn.minLength != int(config.Paddings[i].LengthMin) {
t.Fatalf("isClient=%v: turn %d = %+v, want the configured %+v", isClient, i, turn, config.Paddings[i])
}
}
}
// The preset, in contrast, carries the join tail behind the startup turns.
preset, err := (&Config{}).paddingSchedule(true)
if err != nil {
t.Fatal(err)
}
if len(preset) <= len(startupPaddingSchedule2612) {
t.Fatalf("preset has %d turns, want the startup turns plus the join tail", len(preset))
}
}
func TestCloseCancelsPaddingPause(t *testing.T) {
client, server := net.Pipe()
defer server.Close()
conn, err := newClientConn(client, []loginProfile{{Username: "TestUser"}}, "password", []byte{0x01}, "localhost", nil)
if err != nil {
t.Fatal(err)
}
if err := conn.Close(); err != nil {
t.Fatal(err)
}
started := time.Now()
if err := conn.paddingPause(time.Hour); !errors.Is(err, net.ErrClosed) {
t.Fatalf("expected net.ErrClosed, got %v", err)
}
if time.Since(started) > time.Second {
t.Fatal("closing the connection did not cancel the pause")
}
}
@@ -1,114 +0,0 @@
package xmc
import (
"bytes"
"crypto/x509"
"io"
"net"
"testing"
"time"
)
func TestHandshakeWithBidirectionalPadding(t *testing.T) {
t.Run("pipe", func(t *testing.T) {
client, server := net.Pipe()
testHandshakeWithPadding(t, client, server, 64*1024)
})
t.Run("tcp", func(t *testing.T) {
listener, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
if err != nil {
t.Fatal(err)
}
defer listener.Close()
client, err := net.DialTCP("tcp", nil, listener.Addr().(*net.TCPAddr))
if err != nil {
t.Fatal(err)
}
defer client.Close()
server, err := listener.AcceptTCP()
if err != nil {
t.Fatal(err)
}
defer server.Close()
for _, conn := range []*net.TCPConn{client, server} {
if err := conn.SetWriteBuffer(16 * 1024); err != nil {
t.Fatal(err)
}
if err := conn.SetReadBuffer(64 * 1024); err != nil {
t.Fatal(err)
}
}
testHandshakeWithPadding(t, client, server, maxPaddingTurnLength)
})
}
func testHandshakeWithPadding(t *testing.T, clientRaw, serverRaw net.Conn, length int64) {
t.Helper()
defer clientRaw.Close()
defer serverRaw.Close()
key, err := DeriveRSAKey("padding-regression")
if err != nil {
t.Fatal(err)
}
publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
t.Fatal(err)
}
profiles := []loginProfile{{Username: "TestUser", TexturesValue: "texture", TexturesSignature: "signature"}}
padding := []*Padding{
{Direction: 1, LengthMin: length, LengthMax: length},
{Direction: 2, LengthMin: length, LengthMax: length},
}
paddingSchedule, err := paddingScheduleFromConfig(padding)
if err != nil {
t.Fatal(err)
}
client, err := newClientConn(clientRaw, profiles, "password", publicKey, "localhost", paddingSchedule)
if err != nil {
t.Fatal(err)
}
defer client.Close()
server, err := wrapConnServer(serverRaw, profiles, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, paddingSchedule)
if err != nil {
t.Fatal(err)
}
defer server.Close()
for _, conn := range []net.Conn{client, server} {
if err := conn.SetDeadline(time.Now().Add(15 * time.Second)); err != nil {
t.Fatal(err)
}
}
results := make(chan error, 2)
go func() { results <- client.handshake() }()
go func() { results <- server.handshake() }()
for range 2 {
if err := <-results; err != nil {
t.Errorf("handshake: %v", err)
}
}
if t.Failed() {
return
}
// Both startup readers can already be waiting for the next packet. The
// first proxy payload in either direction must survive the handoff.
for _, pair := range [][2]net.Conn{{client, server}, {server, client}} {
want := bytes.Repeat([]byte("proxy payload"), 4096)
go func() {
_, err := pair[0].Write(want)
results <- err
}()
got := make([]byte, len(want))
if _, err := io.ReadFull(pair[1], got); err != nil {
t.Fatal(err)
}
if err := <-results; err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, want) {
t.Fatal("proxy payload changed after startup padding")
}
}
}
+23 -62
View File
@@ -5,7 +5,6 @@ import (
"fmt"
"io"
"math/big"
"net"
"time"
)
@@ -19,16 +18,6 @@ const (
maxPaddingChunkLength = 48 * 1024
maxPaddingTurnLength = 8 * 1024 * 1024
// A configured schedule is bounded so that one handshake cannot be told to
// send an arbitrary amount of padding: maxPaddingTurns limits the number of
// turns and maxPaddingTotalLength the worst-case sum of their lengths.
maxPaddingTurns = 256
maxPaddingTotalLength = 64 << 20
// maxPaddingScheduleDelay keeps the configured pauses inside the handshake
// deadline. A schedule that cannot finish before the deadline would fail
// every connection, so it is rejected when the configuration is built.
maxPaddingScheduleDelay = handshakeTimeout - 10*time.Second
// Frame padding carries the startup padding in ordinary Minecraft custom
// payload packets so that a vanilla server can parse the whole connection
// without taking the pipeline over. The channel is deliberately different
@@ -54,12 +43,10 @@ type paddingDelayRange struct {
}
type paddingTurn struct {
direction paddingDirection
minLength int
maxLength int
// delay leads into this turn: the side that sends it samples the range, the
// peer spends its minimum, and no pause follows the last turn.
delay paddingDelayRange
direction paddingDirection
minLength int
maxLength int
delay paddingDelayRange // pause after this turn, including the last one
variants []paddingVariant
startDelay paddingDelayRange
chunkDelay paddingDelayRange
@@ -70,37 +57,11 @@ type paddingTurn struct {
sendVariants []int
}
// pausePadding waits for one padding pause. It returns as soon as the
// connection is closed so that a handshake cannot keep sleeping after its
// connection is gone.
func pausePadding(done <-chan struct{}, d time.Duration) error {
if d <= 0 {
return nil
}
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-timer.C:
return nil
case <-done:
return net.ErrClosed
}
func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn) error {
return runPaddingScheduleWithSleep(writer, isClient, firstTurnPrefixLength, schedule, time.Sleep)
}
// runPaddingSchedule sends the local turns of the schedule and applies the
// configured pauses. A turn's pause leads into the turn, so the bytes of a turn
// always follow the pause that was configured next to it, and nothing pauses
// after the last turn: the proxy stream follows it directly. An empty schedule
// means padding is disabled and nothing is written or waited for.
//
// Nothing here checks when a peer's turn arrives: the turns are ordinary
// Minecraft packets that carry nothing to compare an early arrival against, and
// the startup reader drains them on its own while this schedule writes. A peer
// that stalls is bounded by maxPaddingScheduleDelay instead.
func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn, sleep func(time.Duration) error) error {
if len(schedule) == 0 {
return nil
}
func runPaddingScheduleWithSleep(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn, sleep func(time.Duration)) error {
if err := validatePaddingSchedule(schedule, firstTurnPrefixLength); err != nil {
return err
}
@@ -112,24 +73,24 @@ func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength i
}
if isClient != (turn.direction == paddingClientToServer) {
// The startup reader drains peer padding independently so writes
// cannot fill both connection buffers. The peer still spends the
// same pause at the same place in the schedule, which keeps both
// timelines in phase; it only knows the minimum.
if err := sleep(turn.delay.min); err != nil {
return err
// Padding is ordinary Minecraft traffic, so the peer's turns are
// never consumed here: they stay in the stream and are dropped as
// unknown packets by whoever reads it next. Both endpoints still
// apply the same minimum pause, including after the last turn.
if turn.delay.min > 0 {
sleep(turn.delay.min)
}
continue
}
if _, err := writePaddingTurnFrames(writer, turn, prefixLength, sleep, paddingFramePacketID(isClient)); err != nil {
return fmt.Errorf("write padding turn %d: %w", i, err)
}
delay, err := randomPaddingDelay(turn.delay)
if err != nil {
return fmt.Errorf("select padding turn %d delay: %w", i, err)
}
if err := sleep(delay); err != nil {
return err
}
if _, err := writePaddingTurnFrames(writer, turn, prefixLength, sleep, paddingFramePacketID(isClient)); err != nil {
return fmt.Errorf("write padding turn %d: %w", i, err)
if delay > 0 {
sleep(delay)
}
}
return nil
@@ -206,13 +167,13 @@ func paddingFramePacketID(isClient bool) int {
// writePaddingTurnFrames writes one padding turn as a sequence of valid
// Minecraft custom payload frames. Only the framing is native: payload bodies
// stay zero-filled, so the captured traffic shape is kept.
func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration) error, packetID int) (int, error) {
func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration), packetID int) (int, error) {
startDelay, err := randomPaddingDelay(turn.startDelay)
if err != nil {
return 0, fmt.Errorf("select padding start delay: %w", err)
}
if err := sleep(startDelay); err != nil {
return 0, err
if startDelay > 0 {
sleep(startDelay)
}
targetLength, chunks, delays, err := selectPaddingVariant(turn, prefixLength)
@@ -249,8 +210,8 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle
if delayErr != nil {
return written, fmt.Errorf("select padding chunk %d delay: %w", i, delayErr)
}
if delayErr = sleep(delay); delayErr != nil {
return written, delayErr
if delay > 0 {
sleep(delay)
}
}
frameLengths, planErr := paddingFramePlan(chunkLength)
@@ -2,10 +2,6 @@ package xmc
import (
"bytes"
"errors"
"io"
"net"
"strings"
"testing"
"time"
)
@@ -62,7 +58,7 @@ func TestWritePaddingTurnFramesIsMinecraftTraffic(t *testing.T) {
}
for i, turn := range turns {
var buffer bytes.Buffer
written, err := writePaddingTurnFrames(&buffer, turn, 0, noPaddingPause, configurationServerboundCustomPayload)
written, err := writePaddingTurnFrames(&buffer, turn, 0, func(time.Duration) {}, configurationServerboundCustomPayload)
if err != nil {
t.Fatalf("turn %d: %v", i, err)
}
@@ -107,7 +103,7 @@ func TestRunPaddingScheduleLeavesPeerTurnsAlone(t *testing.T) {
}
var out bytes.Buffer
if err := runPaddingSchedule(&out, true, 2, schedule, noPaddingPause); err != nil {
if err := runPaddingSchedule(&out, true, 2, schedule); err != nil {
t.Fatal(err)
}
@@ -135,154 +131,7 @@ func TestRunPaddingScheduleRejectsInvalidSchedule(t *testing.T) {
schedule := []paddingTurn{
{direction: paddingServerToClient, minLength: 10, maxLength: 10},
}
if err := runPaddingSchedule(&bytes.Buffer{}, true, 2, schedule, noPaddingPause); err == nil {
if err := runPaddingSchedule(&bytes.Buffer{}, true, 2, schedule); err == nil {
t.Fatal("expected an error for a prefixed server-to-client first turn")
}
}
func noPaddingPause(time.Duration) error { return nil }
func TestRunPaddingScheduleWithoutTurns(t *testing.T) {
var out bytes.Buffer
if err := runPaddingSchedule(&out, true, 2, nil, noPaddingPause); err != nil {
t.Fatal(err)
}
if out.Len() != 0 {
t.Fatalf("disabled padding wrote %d bytes", out.Len())
}
}
func TestRunPaddingScheduleStopsWhenClosed(t *testing.T) {
schedule := []paddingTurn{
{direction: paddingClientToServer, minLength: 44, maxLength: 44, delay: millisecondRange(1000, 1000)},
{direction: paddingClientToServer, minLength: 44, maxLength: 44},
}
var out bytes.Buffer
pauses := 0
sleep := func(d time.Duration) error {
if d <= 0 {
return nil
}
pauses++
return net.ErrClosed
}
err := runPaddingSchedule(&out, true, 2, schedule, sleep)
if !errors.Is(err, net.ErrClosed) {
t.Fatalf("expected net.ErrClosed, got %v", err)
}
if pauses != 1 {
t.Fatalf("pauses = %d, want 1", pauses)
}
// The pause leads into turn 0, so the cancelled pause came before its bytes.
if out.Len() != 0 {
t.Fatalf("schedule kept writing after a cancelled pause: %d bytes", out.Len())
}
}
// recordingWriter records one event per write, so a test can see where the
// pauses fall relative to the padding bytes.
type recordingWriter struct {
events *[]string
}
func (w recordingWriter) Write(p []byte) (int, error) {
*w.events = append(*w.events, "write")
return len(p), nil
}
// TestPaddingDelayLeadsIntoTheTurn pins the placement of a configured pause:
// it belongs to the turn it precedes, the peer spends its minimum at the same
// place, and the last turn is not followed by one.
func TestPaddingDelayLeadsIntoTheTurn(t *testing.T) {
schedule := []paddingTurn{
{direction: paddingClientToServer, minLength: 44, maxLength: 44, delay: millisecondRange(10, 10)},
{direction: paddingServerToClient, minLength: 20, maxLength: 20, delay: millisecondRange(20, 20)},
{direction: paddingClientToServer, minLength: 44, maxLength: 44, delay: millisecondRange(30, 30)},
}
run := func(isClient bool) []string {
var events []string
sleep := func(d time.Duration) error {
if d > 0 {
events = append(events, "pause "+d.String())
}
return nil
}
if err := runPaddingSchedule(recordingWriter{events: &events}, isClient, 2, schedule, sleep); err != nil {
t.Fatal(err)
}
return events
}
// The client sends turns 0 and 2, so it pauses before each of them and
// spends the minimum of turn 1 while the server sends it.
client := strings.Join(run(true), ",")
wantClient := "pause 10ms,write,pause 20ms,pause 30ms,write"
if client != wantClient {
t.Fatalf("client events = %q, want %q", client, wantClient)
}
// The server sends turn 1, so the same pauses lead into its bytes. The last
// turn's pause still happens, but nothing follows the final write.
server := strings.Join(run(false), ",")
wantServer := "pause 10ms,pause 20ms,write,pause 30ms"
if server != wantServer {
t.Fatalf("server events = %q, want %q", server, wantServer)
}
}
// TestPaddingDelayRangeJittersOnlyTheSender pins which value each end waits:
// the side that sends the turn samples the range, the peer spends the minimum.
func TestPaddingDelayRangeJittersOnlyTheSender(t *testing.T) {
schedule := []paddingTurn{
{direction: paddingClientToServer, minLength: 44, maxLength: 44, delay: millisecondRange(20, 200)},
{direction: paddingClientToServer, minLength: 44, maxLength: 44},
}
run := func(isClient bool) []time.Duration {
var pauses []time.Duration
sleep := func(d time.Duration) error {
if d > 0 {
pauses = append(pauses, d)
}
return nil
}
if err := runPaddingSchedule(io.Discard, isClient, 2, schedule, sleep); err != nil {
t.Fatal(err)
}
return pauses
}
// The peer, which sends nothing here, spends exactly the minimum.
if got := run(false); len(got) != 1 || got[0] != 20*time.Millisecond {
t.Fatalf("peer pauses = %v, want exactly [20ms]", got)
}
seenLarge := false
for i := 0; i < 64; i++ {
pauses := run(true)
if len(pauses) != 1 {
t.Fatalf("sender pauses = %v, want exactly one pause", pauses)
}
if pauses[0] < 20*time.Millisecond || pauses[0] > 200*time.Millisecond {
t.Fatalf("sender pause %s is outside the configured range", pauses[0])
}
if pauses[0] >= 20*time.Millisecond && pauses[0] <= 200*time.Millisecond && pauses[0] != 20*time.Millisecond {
seenLarge = true
}
}
if !seenLarge {
t.Fatal("the sender never sampled a value above the minimum")
}
}
func TestPaddingPauseReturnsOnClose(t *testing.T) {
done := make(chan struct{})
close(done)
started := time.Now()
if err := pausePadding(done, time.Hour); !errors.Is(err, net.ErrClosed) {
t.Fatalf("expected net.ErrClosed, got %v", err)
}
if time.Since(started) > time.Second {
t.Fatal("pausePadding did not return on close")
}
}
@@ -1,61 +0,0 @@
package xmc
import (
"bytes"
"io"
)
type paddingReadResult struct {
frame []byte
err error
}
type paddingReader struct {
reader io.Reader
first <-chan paddingReadResult
}
// newPaddingReader drains startup padding while the local padding schedule is
// writing. Buffer only the first non-padding packet, then let the caller resume
// reading the underlying stream. This keeps memory bounded without requiring
// matching padding lengths or an extra end-of-padding packet on the wire.
func newPaddingReader(reader io.Reader, isClient bool) io.Reader {
first := make(chan paddingReadResult, 1)
go func() {
frame, err := readPastPadding(reader, paddingFramePacketID(!isClient))
first <- paddingReadResult{frame: frame, err: err}
}()
return &paddingReader{reader: reader, first: first}
}
func readPastPadding(reader io.Reader, packetID int) ([]byte, error) {
for {
packet, err := readPacket(reader)
if err != nil {
return nil, err
}
if packet.packetID == packetID {
var channel String
if err := channel.readFrom(bytes.NewReader(packet.data)); err == nil && channel == paddingFrameChannel {
continue
}
}
payload := RestBytes(packet.data)
return encodePacket(packet.packetID, &payload)
}
}
func (r *paddingReader) Read(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
if r.first != nil {
result := <-r.first
r.first = nil
if result.err != nil {
return 0, result.err
}
r.reader = io.MultiReader(bytes.NewReader(result.frame), r.reader)
}
return r.reader.Read(p)
}
@@ -1,76 +0,0 @@
package xmc
import (
"bytes"
"errors"
"io"
"net"
"testing"
)
func TestPaddingReaderPreservesFollowingPackets(t *testing.T) {
for _, isClient := range []bool{true, false} {
packetID := paddingFramePacketID(!isClient)
var wire bytes.Buffer
paddingChannel := String(paddingFrameChannel)
padding := RestBytes(make([]byte, 1024))
if err := writePacket(&wire, packetID, &paddingChannel, &padding); err != nil {
t.Fatal(err)
}
var want bytes.Buffer
unknownChannel := String("other:channel")
payload := RestBytes("preserve unknown custom payloads")
if err := writePacket(&want, packetID, &unknownChannel, &payload); err != nil {
t.Fatal(err)
}
id := Long(42)
if err := writePacket(&want, configurationKeepAlive, &id); err != nil {
t.Fatal(err)
}
channel := String(packetChannel)
if err := writePacket(&want, packetID, &channel, &payload); err != nil {
t.Fatal(err)
}
wire.Write(want.Bytes())
got, err := io.ReadAll(newPaddingReader(&wire, isClient))
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, want.Bytes()) {
t.Fatalf("client=%v: non-padding packets changed", isClient)
}
}
}
func TestPaddingReaderReadErrors(t *testing.T) {
for _, test := range []struct {
name string
wire []byte
err error
}{
{name: "eof", err: io.EOF},
{name: "truncated", wire: []byte{2, 1}, err: io.ErrUnexpectedEOF},
} {
t.Run(test.name, func(t *testing.T) {
reader := newPaddingReader(bytes.NewReader(test.wire), true)
if _, err := reader.Read(make([]byte, 1)); !errors.Is(err, test.err) {
t.Fatalf("got %v, want %v", err, test.err)
}
})
}
}
func TestPaddingReaderUnblocksOnClose(t *testing.T) {
client, server := net.Pipe()
defer server.Close()
reader := newPaddingReader(client, true)
if n, err := reader.Read(nil); n != 0 || err != nil {
t.Fatalf("empty read = %d, %v", n, err)
}
if err := client.Close(); err != nil {
t.Fatal(err)
}
if _, err := reader.Read(make([]byte, 1)); !errors.Is(err, io.ErrClosedPipe) {
t.Fatalf("closed read = %v", err)
}
}
+6 -14
View File
@@ -41,9 +41,6 @@ type serverConn struct {
paddingSchedule []paddingTurn
packet *packetStream
deadlines *connectionDeadlines
done chan struct{}
closeOnce sync.Once
}
func (c *serverConn) handshake() error {
@@ -248,9 +245,7 @@ func (c *serverConn) handshake() error {
if err = validateLoginAcknowledgedPacket(pkt); err != nil {
return err
}
c.reader = newPaddingReader(c.reader, false)
if err = runPaddingSchedule(c.writer, false, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause); err != nil {
_ = c.Close() // Unblock the startup reader if writing failed.
if err = runPaddingSchedule(c.writer, false, loginAcknowledgedLength, c.paddingSchedule); err != nil {
return fmt.Errorf("run startup padding: %w", err)
}
@@ -307,18 +302,12 @@ func (c *serverConn) Close() error {
c.closed = true
packet := c.packet
c.lifecycleMu.Unlock()
c.closeOnce.Do(func() { close(c.done) })
if packet != nil {
packet.Stop()
}
return c.c.Close()
}
// paddingPause applies one padding pause, stopping early on Close.
func (c *serverConn) paddingPause(d time.Duration) error {
return pausePadding(c.done, d)
}
func (c *serverConn) LocalAddr() net.Addr {
return c.c.LocalAddr()
}
@@ -339,7 +328,7 @@ func (c *serverConn) SetWriteDeadline(t time.Time) error {
return c.deadlines.setWriteDeadline(t)
}
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, paddingSchedule []paddingTurn) (*serverConn, error) {
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, padding []*Padding) (*serverConn, error) {
if len(profiles) == 0 {
return nil, fmt.Errorf("empty profiles")
}
@@ -353,6 +342,10 @@ func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPri
if err != nil {
return nil, fmt.Errorf("parse rsa private key: %w", err)
}
paddingSchedule, err := newPaddingSchedule(padding, false)
if err != nil {
return nil, fmt.Errorf("select padding profile: %w", err)
}
s := &serverConn{
reader: bufio.NewReader(c),
@@ -365,7 +358,6 @@ func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPri
rsaPublicKey: rsaPublicKey,
paddingSchedule: paddingSchedule,
deadlines: newConnectionDeadlines(c),
done: make(chan struct{}),
}
return s, nil
+1 -1
View File
@@ -91,7 +91,7 @@ func (h *HunkReaderWriter) ReadMultiBuffer() (buf.MultiBuffer, error) {
}
}
if len(h.buf) == buf.Size {
if cap(h.buf) >= buf.Size {
b := h.buf
h.index = len(h.buf)
return buf.MultiBuffer{buf.NewExisted(b)}, nil
@@ -74,10 +74,14 @@ func (h *MultiHunkReaderWriter) ReadMultiBuffer() (buf.MultiBuffer, error) {
continue
}
if len(b) == buf.Size {
if cap(b) >= buf.Size {
mb = append(mb, buf.NewExisted(b))
} else {
mb = buf.MergeBytes(mb, b)
nb := buf.New()
nb.Extend(int32(len(b)))
copy(nb.Bytes(), b)
mb = append(mb, nb)
}
}
+1 -1
View File
@@ -84,7 +84,7 @@ func OriginalDst(la, ra net.Addr) (net.IP, int, error) {
nl.sxport[0], nl.sxport[1] = byte(raPort>>8), byte(raPort)
nl.dxport[0], nl.dxport[1] = byte(laPort>>8), byte(laPort)
if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, fd, DIOCNATLOOK, uintptr(unsafe.Pointer(&nl))); errno != 0 {
return net.IP{}, -1, os.NewSyscallError("ioctl", errno)
return net.IP{}, -1, os.NewSyscallError("ioctl", err)
}
odPort := nl.rdxport
-3
View File
@@ -227,9 +227,6 @@ func createHTTPClient(dest net.Destination, streamSettings *internet.MemoryStrea
conn, err := tr.DialEarly(ctx, udpAddr, tlsCfg, cfg)
if err != nil {
// pktConn first: tr.Close() waits for the read from it to return, which with dialerProxy has no deadline
pktConn.Close()
tr.Close()
return nil, err
}
context.AfterFunc(conn.Context(), func() { tr.Close(); pktConn.Close() })
+7 -8
View File
@@ -270,12 +270,18 @@ var PresetFingerprints = map[string]*utls.ClientHelloID{
var ModernFingerprints = map[string]*utls.ClientHelloID{
// One of these will be chosen as `random` at startup
// All of them must have X25519MLKEM768 before optional X25519, otherwise REALITY servers (since v26.9.9) will reject them
"hellofirefox_120": &utls.HelloFirefox_120,
"hellofirefox_148": &utls.HelloFirefox_148,
"hellochrome_120": &utls.HelloChrome_120,
"hellochrome_131": &utls.HelloChrome_131,
"hellochrome_133": &utls.HelloChrome_133,
"hellochrome_155": &utls.HelloChrome_155,
"helloios_13": &utls.HelloIOS_13,
"helloios_14": &utls.HelloIOS_14,
"helloedge_106": &utls.HelloEdge_106,
"hellosafari_26_3": &utls.HelloSafari_26_3,
"hello360_11_0": &utls.Hello360_11_0,
"helloqq_11_1": &utls.HelloQQ_11_1,
}
var OtherFingerprints = map[string]*utls.ClientHelloID{
@@ -292,7 +298,6 @@ var OtherFingerprints = map[string]*utls.ClientHelloID{
"hellofirefox_99": &utls.HelloFirefox_99,
"hellofirefox_102": &utls.HelloFirefox_102,
"hellofirefox_105": &utls.HelloFirefox_105,
"hellofirefox_120": &utls.HelloFirefox_120,
"hellochrome_auto": &utls.HelloChrome_Auto,
"hellochrome_58": &utls.HelloChrome_58,
"hellochrome_62": &utls.HelloChrome_62,
@@ -304,23 +309,17 @@ var OtherFingerprints = map[string]*utls.ClientHelloID{
"hellochrome_100": &utls.HelloChrome_100,
"hellochrome_102": &utls.HelloChrome_102,
"hellochrome_106_shuffle": &utls.HelloChrome_106_Shuffle,
"hellochrome_120": &utls.HelloChrome_120,
"helloios_auto": &utls.HelloIOS_Auto,
"helloios_11_1": &utls.HelloIOS_11_1,
"helloios_12_1": &utls.HelloIOS_12_1,
"helloios_13": &utls.HelloIOS_13,
"helloios_14": &utls.HelloIOS_14,
"helloandroid_11_okhttp": &utls.HelloAndroid_11_OkHttp,
"helloedge_85": &utls.HelloEdge_85,
"helloedge_106": &utls.HelloEdge_106,
"helloedge_auto": &utls.HelloEdge_Auto,
"hellosafari_16_0": &utls.HelloSafari_16_0,
"hellosafari_auto": &utls.HelloSafari_Auto,
"hello360_auto": &utls.Hello360_Auto,
"hello360_7_5": &utls.Hello360_7_5,
"hello360_11_0": &utls.Hello360_11_0,
"helloqq_auto": &utls.HelloQQ_Auto,
"helloqq_11_1": &utls.HelloQQ_11_1,
// Chrome betas
"hellochrome_100_psk": &utls.HelloChrome_100_PSK,
+5 -7
View File
@@ -5,7 +5,6 @@ import (
goerrors "errors"
"io"
"sync"
"sync/atomic"
"time"
"github.com/xtls/xray-core/common"
@@ -25,7 +24,7 @@ type connEntry struct {
link *transport.Link
timer *signal.ActivityTimer
cancel context.CancelFunc
closed atomic.Bool
closed bool
}
func (c *connEntry) Close() error {
@@ -34,9 +33,10 @@ func (c *connEntry) Close() error {
}
func (c *connEntry) terminate() {
if c.closed.Swap(true) {
if c.closed {
panic("terminate called more than once")
}
c.closed = true
c.cancel()
common.Interrupt(c.link.Reader)
common.Interrupt(c.link.Writer)
@@ -77,7 +77,7 @@ func (v *Dispatcher) getInboundRay(ctx context.Context, dest net.Destination) (*
}
if v.conn != nil {
if v.conn.closed.Load() {
if v.conn.closed {
v.conn = nil
} else {
return v.conn, nil
@@ -144,9 +144,7 @@ func handleInput(ctx context.Context, conn *connEntry, dest net.Destination, cal
mb, err := input.ReadMultiBuffer()
if err != nil {
if conn.closed.Load() {
errors.LogDebugInner(ctx, err, "UDP input closed locally")
} else if !goerrors.Is(err, io.EOF) {
if !goerrors.Is(err, io.EOF) {
errors.LogInfoInner(ctx, err, "failed to handle UDP input")
}
return