Compare commits

...
Author SHA1 Message Date
Meo597 84ce7568bb Lua: Expose Go slices as read-only 2026-11-20 05:16:13 +08:00
MinyandGitHub 02cf0f60ea Dependency: Update github.com/klauspost/compress to v1.20.4 to fix CVE-2026-116591 (#7431)
https://github.com/XTLS/Xray-core/pull/7431#issuecomment-7016054619
2026-11-19 17:13:28 +00:00
f73471e6b4 gRPC transport: Pass standard size buffer (#7449)
https://github.com/XTLS/Xray-core/pull/7438#issuecomment-7008713358

Fixes https://github.com/XTLS/Xray-core/issues/7369 and https://github.com/XTLS/Xray-core/pull/7424

---------

Co-authored-by: b84330808 <b84330808@gmail.com>
Co-authored-by: anonymousmeower <arasouli@duck.com>
2026-11-19 13:48:04 +00:00
8e07407486 XHTTP/3 client: Close the UDP socket when the QUIC dial fails (#7413)
https://github.com/XTLS/Xray-core/pull/7413#pullrequestreview-5975182281

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: 风扇滑翔翼 <Fangliding.fshxy@outlook.com>
2026-11-19 12:54:02 +00:00
febc082f03 DNS: Avoid mutating cache records during cleanup (#7442)
https://github.com/XTLS/Xray-core/pull/7442#pullrequestreview-5958707394

---------

Co-authored-by: Meow <197331664+Meo597@users.noreply.github.com>
2026-11-19 12:36:34 +00:00
anonymousmeowerandGitHub 09b1b0701f Sockopt: Report the real ioctl error from OriginalDst on Darwin (#7367)
https://github.com/XTLS/Xray-core/pull/7367#issuecomment-7008748396
2026-11-19 12:14:35 +00:00
MeowandGitHub ce074ce572 Env: Remove XRAY_CONE_DISABLED (#6110)
https://github.com/XTLS/Xray-core/pull/6057#issuecomment-4364744151
https://github.com/XTLS/Xray-core/pull/6075#issuecomment-4395258425
https://github.com/XTLS/Xray-core/pull/6110#issuecomment-7003152469
2026-11-19 11:25:41 +00:00
b1dfdf25e7 uTLS: Pick "random" only from fingerprints that have X25519MLKEM768 (#7432)
https://github.com/XTLS/Xray-core/issues/7259#issuecomment-6718349626

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:07:29 +00:00
Roy Hill-PercivalandGitHub 1c5a1fbf70 TUN inbound: End UDP flows and cancel dispatches when the inbound closes (#7350)
https://github.com/XTLS/Xray-core/pull/7350#pullrequestreview-5901009138
2026-11-19 07:57:32 +00:00
deadnewsandGitHub b983473390 Socks & HTTP inbounds: Add email to access log (#7437)
Fixes https://github.com/XTLS/Xray-core/issues/7436
2026-11-19 07:11:16 +00:00
5e861653c2 VMess inbound: Refactor code to use DispatchLink() (#5143)
https://github.com/XTLS/Xray-core/pull/5143#issuecomment-3403697498
https://github.com/XTLS/Xray-core/pull/5143#issuecomment-6743282472
https://github.com/XTLS/Xray-core/pull/5143#issuecomment-7000643202

---------

Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com>
2026-11-19 06:38:22 +00:00
36112cd886 Routing: Fix process for Linux IPv4-mapped sockets (#7414)
https://github.com/XTLS/Xray-core/pull/7414#issuecomment-6987317102

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 18:13:31 +00:00
b1905088c3 transport/internet/udp/dispatcher.go: Avoid info-level read failure after local session termination; Fix race (#7411)
https://github.com/XTLS/Xray-core/issues/4621#issuecomment-2803983542
https://github.com/XTLS/Xray-core/pull/7411#issuecomment-6893907446
https://github.com/XTLS/Xray-core/pull/7364#issuecomment-6915895563

---------

Co-authored-by: Meow <197331664+Meo597@users.noreply.github.com>
2026-11-18 12:14:26 +00:00
381e450943 DNS: Add udp+local:// support and udp:// (remote) as well (#7420)
https://github.com/XTLS/Xray-core/pull/7380#issuecomment-6977561366

Closes https://github.com/XTLS/Xray-core/issues/7321#issuecomment-6674139825

---------

Co-authored-by: Ivan Zorin <creator@localzet.com>
2026-11-18 11:50:30 +00:00
7daa8e4b6a Direct/Freedom outbound: Rename finalRules to firewall; Add reply to firewall; Merge Block/Blackhole outbound; Move proxyProtocol to "proxy-protocol" TCP finalmask (#7281)
https://github.com/XTLS/Xray-core/pull/7238#issuecomment-6467092152
https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6484050347
https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6484439860
https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6621021705
https://github.com/XTLS/Xray-core/pull/7329#issuecomment-6623818990
https://github.com/XTLS/Xray-core/pull/7329#issuecomment-6624149740
https://github.com/XTLS/Xray-core/pull/7329#issuecomment-6625219097
https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6627156942
https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6850640864
https://github.com/XTLS/Xray-core/pull/7281#issuecomment-6973501579

---------

Co-authored-by: Codex <codex@openai.com>
2026-11-18 10:39:20 +00:00
yangdujunandGitHub a32023be5f XMC finalmask: Bound padding schedules; Fix delay placement; Stop compressing frames (#7423)
https://github.com/XTLS/Xray-core/pull/7402#issuecomment-6912788851
https://github.com/XTLS/Xray-core/pull/7430#issuecomment-6917170115
https://github.com/XTLS/Xray-core/pull/7423#issuecomment-6973045579
2026-11-18 08:27:34 +00:00
TurboRigbyandGitHub 82b5b76bc5 XMC finalmask: Prevent deadlock during bidirectional startup padding (#7430)
https://github.com/XTLS/Xray-core/pull/7430#issuecomment-6954499005
2026-11-17 16:43:50 +00:00
yangdujunandRPRXX f781c68715 XMC finalmask: Switch to native frame padding (breaking); delay supports range (receiver waits at least minimal ms) (#7402)
https://github.com/XTLS/Xray-core/pull/6769#issuecomment-6117945421
https://github.com/XTLS/Xray-core/issues/7394#issuecomment-6855385193
https://github.com/XTLS/Xray-core/pull/6769#issuecomment-6880324101
https://github.com/XTLS/Xray-core/pull/7402#issuecomment-6887468010
https://github.com/XTLS/Xray-core/pull/7402#issuecomment-6890345279
https://github.com/XTLS/Xray-core/pull/7402#issuecomment-6896090317
https://github.com/XTLS/Xray-core/issues/7394#issuecomment-6897315492
https://github.com/XTLS/Xray-core/pull/7402#issuecomment-6912788851
2026-11-16 09:49:32 +00:00
5d17b872ed XMC finalmask: Make startup paddings configurable (direction, length and delay) (#6769)
https://github.com/XTLS/Xray-core/pull/6487#issuecomment-5008140264
https://github.com/XTLS/Xray-core/pull/6769#issuecomment-5861391675
https://github.com/XTLS/Xray-core/pull/6769#issuecomment-6056420905
https://github.com/XTLS/Xray-core/issues/7394#issuecomment-6876480694
https://github.com/XTLS/Xray-core/pull/7401#issuecomment-6876702404
https://github.com/XTLS/Xray-core/pull/6769#issuecomment-6876963752

Closes https://github.com/XTLS/Xray-core/issues/6732#issuecomment-5575293343

---------

Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com>
2026-11-14 15:58:21 +00:00
100 changed files with 2898 additions and 2375 deletions
+8 -5
View File
@@ -124,14 +124,17 @@ func (c *CacheController) writeAndShrink(expiredKeys []string) {
if rec == nil { if rec == nil {
continue continue
} }
if rec.A != nil && rec.A.Expire.Before(now) { a, aaaa := rec.A, rec.AAAA
rec.A = nil if a != nil && a.Expire.Before(now) {
a = nil
} }
if rec.AAAA != nil && rec.AAAA.Expire.Before(now) { if aaaa != nil && aaaa.Expire.Before(now) {
rec.AAAA = nil aaaa = nil
} }
if rec.A == nil && rec.AAAA == nil { if a == nil && aaaa == nil {
delete(c.ips, domain) 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{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -210,7 +210,7 @@ func TestUDPServer(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -350,7 +350,7 @@ func TestPrioritizedDomain(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -421,7 +421,7 @@ func TestUDPServerIPv6(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -490,7 +490,7 @@ func TestStaticHostDomain(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -577,7 +577,7 @@ func TestIPMatch(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -696,7 +696,7 @@ func TestLocalDomain(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -953,7 +953,7 @@ func TestMultiMatchPrioritizedDomain(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
+4
View File
@@ -68,6 +68,10 @@ func NewServer(ctx context.Context, dest net.Destination, dispatcher routing.Dis
return NewTCPNameServer(u, dispatcher, disableCache, serveStale, serveExpiredTTL, clientIP) return NewTCPNameServer(u, dispatcher, disableCache, serveStale, serveExpiredTTL, clientIP)
case strings.EqualFold(u.Scheme, "tcp+local"): // DNS-over-TCP Local mode case strings.EqualFold(u.Scheme, "tcp+local"): // DNS-over-TCP Local mode
return NewTCPLocalNameServer(u, disableCache, serveStale, serveExpiredTTL, clientIP) 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"): case strings.EqualFold(u.String(), "fakedns"):
var fd dns.FakeDNSEngine var fd dns.FakeDNSEngine
err = core.RequireFeatures(ctx, func(fdns dns.FakeDNSEngine) { err = core.RequireFeatures(ctx, func(fdns dns.FakeDNSEngine) {
+45
View File
@@ -2,12 +2,15 @@ package dns
import ( import (
"context" "context"
"io"
"net/url"
"strings" "strings"
"sync" "sync"
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/xtls/xray-core/common" "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/errors"
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol/dns" "github.com/xtls/xray-core/common/protocol/dns"
@@ -15,6 +18,8 @@ import (
"github.com/xtls/xray-core/common/task" "github.com/xtls/xray-core/common/task"
dns_feature "github.com/xtls/xray-core/features/dns" dns_feature "github.com/xtls/xray-core/features/dns"
"github.com/xtls/xray-core/features/routing" "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" "github.com/xtls/xray-core/transport/internet/udp"
"golang.org/x/net/dns/dnsmessage" "golang.org/x/net/dns/dnsmessage"
) )
@@ -59,6 +64,46 @@ func NewClassicNameServer(address net.Destination, dispatcher routing.Dispatcher
return s 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. // Name implements Server.
func (s *ClassicNameServer) Name() string { func (s *ClassicNameServer) Name() string {
return s.cacheController.name return s.cacheController.name
+1 -7
View File
@@ -273,8 +273,7 @@ type udpWorker struct {
checker *task.Periodic checker *task.Periodic
activeConn map[connID]*udpConn activeConn map[connID]*udpConn
ctx context.Context ctx context.Context
cone bool
} }
func (w *udpWorker) getConnection(id connID) (*udpConn, bool) { func (w *udpWorker) getConnection(id connID) (*udpConn, bool) {
@@ -316,9 +315,6 @@ func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest
src: source, src: source,
} }
if originalDest.IsValid() { if originalDest.IsValid() {
if !w.cone {
id.dest = originalDest
}
b.UDP = &originalDest b.UDP = &originalDest
} }
conn, existing := w.getConnection(id) conn, existing := w.getConnection(id)
@@ -418,8 +414,6 @@ func (w *udpWorker) Start() error {
return err return err
} }
w.cone = w.ctx.Value("cone").(bool)
w.checker = &task.Periodic{ w.checker = &task.Periodic{
Interval: time.Minute, Interval: time.Minute,
Execute: w.clean, Execute: w.clean,
+3 -3
View File
@@ -48,7 +48,7 @@ func TestOutboundWithoutStatCounter(t *testing.T) {
ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{}}) ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{}})
h, _ := NewHandler(ctx, &core.OutboundHandlerConfig{ h, _ := NewHandler(ctx, &core.OutboundHandlerConfig{
Tag: "tag", Tag: "tag",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
}) })
conn, _ := h.(*Handler).Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146)) conn, _ := h.(*Handler).Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146))
_, ok := conn.(*stat.CounterConnection) _, ok := conn.(*stat.CounterConnection)
@@ -78,7 +78,7 @@ func TestOutboundWithStatCounter(t *testing.T) {
ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{}}) ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{}})
h, _ := NewHandler(ctx, &core.OutboundHandlerConfig{ h, _ := NewHandler(ctx, &core.OutboundHandlerConfig{
Tag: "tag", Tag: "tag",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
}) })
conn, _ := h.(*Handler).Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146)) conn, _ := h.(*Handler).Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146))
_, ok := conn.(*stat.CounterConnection) _, ok := conn.(*stat.CounterConnection)
@@ -117,7 +117,7 @@ func TestTagsCache(t *testing.T) {
tag := fmt.Sprintf("%s%d", tags_prefix, idx) tag := fmt.Sprintf("%s%d", tags_prefix, idx)
cfg := &core.OutboundHandlerConfig{ cfg := &core.OutboundHandlerConfig{
Tag: tag, Tag: tag,
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
} }
if h, err := NewHandler(ctx, cfg); err == nil { if h, err := NewHandler(ctx, cfg); err == nil {
if err := ohm.AddHandler(ctx, h); err == nil { if err := ohm.AddHandler(ctx, h); err == nil {
+2 -3
View File
@@ -24,7 +24,6 @@ import (
"github.com/xtls/xray-core/features/outbound" "github.com/xtls/xray-core/features/outbound"
"github.com/xtls/xray-core/features/routing" "github.com/xtls/xray-core/features/routing"
routing_session "github.com/xtls/xray-core/features/routing/session" routing_session "github.com/xtls/xray-core/features/routing/session"
"github.com/xtls/xray-core/proxy/blackhole"
"github.com/xtls/xray-core/proxy/freedom" "github.com/xtls/xray-core/proxy/freedom"
) )
@@ -397,9 +396,9 @@ end`)
serial.ToTypedMessage(&proxyman.OutboundConfig{}), serial.ToTypedMessage(&proxyman.OutboundConfig{}),
}, },
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{Tag: "default", ProxySettings: serial.ToTypedMessage(&blackhole.Config{})}, {Tag: "default", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{ {Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
})}, })},
}, },
}) })
+1 -1
View File
@@ -23,7 +23,7 @@ func RegisterLua(L *lua.LState) {
return 0 return 0
} }
xlua.PushWithDirectMethods(L, matcher, map[string]xlua.DirectMethod{ xlua.PushWithDirectMethods(L, matcher, map[string]xlua.DirectMethod{
"Match": newLuaDomainMatch(xlua.NewSlicePusher[uint32](L)), "Match": newLuaDomainMatch(xlua.NewReadOnlySlicePusher[uint32](L)),
"MatchAny": luaDomainMatchAny, "MatchAny": luaDomainMatchAny,
}) })
return 1 return 1
+3 -1
View File
@@ -104,7 +104,9 @@ for _, value in ipairs({matcher, domain}) do
assert(not pcall(function() return value ^ {} end)) assert(not pcall(function() return value ^ {} end))
end end
assert(domain:matchAny("example.com")) assert(domain:matchAny("example.com"))
assert(#domain:Match("example.com") == 1) local indices = domain:Match("example.com")
assert(#indices == 1)
assert(not pcall(function() indices[1] = 7 end))
assert(domain:match("example.com")[1] == 0) assert(domain:match("example.com")[1] == 0)
assert(not pcall(function() matcher:AnyMatch() end)) assert(not pcall(function() matcher:AnyMatch() end))
assert(not pcall(function() matcher:AnyMatch(matched, true) end)) assert(not pcall(function() matcher:AnyMatch(matched, true) end))
+3 -3
View File
@@ -8,10 +8,10 @@ import (
luar "layeh.com/gopher-luar" 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, // The returned function wraps slices without reflection or metatable lookup,
// and pushes nil for nil slices. Use it with this state or its coroutines. // 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 metatable := luar.MT(L, []T(nil)).LTable
return func(L *glua.LState, values []T) { return func(L *glua.LState, values []T) {
if values == nil { if values == nil {
@@ -38,7 +38,7 @@ func NewReadOnlySlicePusher[T any](L *glua.LState) func(*glua.LState, []T) {
}) })
setSliceReadOnly[[]T](L, readOnly) setSliceReadOnly[[]T](L, readOnly)
} }
return NewSlicePusher[T](L) return newSlicePusher[T](L)
} }
func setSliceReadOnly[S ~[]E, E any](L *glua.LState, readOnly *glua.LFunction) { func setSliceReadOnly[S ~[]E, E any](L *glua.LState, readOnly *glua.LFunction) {
+21 -43
View File
@@ -9,53 +9,20 @@ import (
luar "layeh.com/gopher-luar" luar "layeh.com/gopher-luar"
) )
func TestSlicePusher(t *testing.T) { func TestReadOnlySlicePusher(t *testing.T) {
L := glua.NewState() L := glua.NewState()
defer L.Close() defer L.Close()
push := NewSlicePusher[int](L) push := NewReadOnlySlicePusher[int](L)
values := []int{3, 5} values := []int{3, 5}
L.SetGlobal("getValues", L.NewFunction(func(L *glua.LState) int { L.SetGlobal("getValues", L.NewFunction(func(L *glua.LState) int {
push(L, values) push(L, values)
return 1 return 1
})) }))
if err := L.DoString(` if err := L.DoString(`
local values = getValues() local co = coroutine.create(function() return getValues() end)
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) local ok, result = coroutine.resume(co)
assert(ok and result == true) assert(ok, result)
`); err != nil { values = result
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(#values == 2 and values[1] == 3 and values[2] == 5)
assert(not pcall(function() values[1] = 7 end)) assert(not pcall(function() values[1] = 7 end))
assert(not pcall(function() return values + 7 end)) assert(not pcall(function() return values + 7 end))
@@ -69,6 +36,17 @@ assert(sum == 8)
if &got[0] != &values[0] || values[0] != 3 || values[1] != 5 { if &got[0] != &values[0] || values[0] != 3 || values[1] != 5 {
t.Fatal("read-only binding copied or modified the slice") 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) { func TestReadOnlyIPSlicePusher(t *testing.T) {
@@ -230,23 +208,23 @@ assert(not pcall(function() return nested + nested end))
} }
} }
func TestSlicePusherMetatablePerState(t *testing.T) { func TestReadOnlySlicePusherMetatablePerState(t *testing.T) {
first := glua.NewState() first := glua.NewState()
defer first.Close() defer first.Close()
second := glua.NewState() second := glua.NewState()
defer second.Close() defer second.Close()
NewSlicePusher[int](first)(first, []int{1}) NewReadOnlySlicePusher[int](first)(first, []int{1})
NewSlicePusher[int](second)(second, []int{1}) NewReadOnlySlicePusher[int](second)(second, []int{1})
if first.Get(-1).(*glua.LUserData).Metatable == second.Get(-1).(*glua.LUserData).Metatable { if first.Get(-1).(*glua.LUserData).Metatable == second.Get(-1).(*glua.LUserData).Metatable {
t.Fatal("independent states share a slice metatable") t.Fatal("independent states share a slice metatable")
} }
} }
func BenchmarkSlicePusher(b *testing.B) { func BenchmarkReadOnlySlicePusher(b *testing.B) {
L := glua.NewState() L := glua.NewState()
defer L.Close() defer L.Close()
ips := []net.IP{net.ParseIP("127.0.0.1")} ips := []net.IP{net.ParseIP("127.0.0.1")}
pushIPs := NewSlicePusher[net.IP](L) pushIPs := NewReadOnlySlicePusher[net.IP](L)
for _, benchmark := range []struct { for _, benchmark := range []struct {
name string name string
push func(*glua.LState, []net.IP) push func(*glua.LState, []net.IP)
+2 -4
View File
@@ -671,7 +671,7 @@ string.__tostring = nil
L.SetGlobal("testNativeError", L.Get(-1)) L.SetGlobal("testNativeError", L.Get(-1))
L.Pop(1) L.Pop(1)
L.SetGlobal("testGoStruct", luar.New(L, &struct{ Value string }{"readable field"})) L.SetGlobal("testGoStruct", luar.New(L, &struct{ Value string }{"readable field"}))
NewSlicePusher[net.IP](L)(L, []net.IP{net.ParseIP("192.0.2.1")}) NewReadOnlySlicePusher[net.IP](L)(L, []net.IP{net.ParseIP("192.0.2.1")})
L.SetGlobal("testIPs", L.Get(-1)) L.SetGlobal("testIPs", L.Get(-1))
L.Pop(1) L.Pop(1)
userdata := L.NewUserData() userdata := L.NewUserData()
@@ -865,9 +865,7 @@ assert(not ok and a == "{<address> <address>}")
PushUserData(L, struct{ Pointer *int }{&target}) PushUserData(L, struct{ Pointer *int }{&target})
L.SetGlobal("testObject", L.Get(-1)) L.SetGlobal("testObject", L.Get(-1))
L.Pop(1) L.Pop(1)
NewSlicePusher[int](L)(L, []int{1}) L.SetGlobal("testValues", luar.New(L, []int{1}))
L.SetGlobal("testValues", L.Get(-1))
L.Pop(1)
L.SetGlobal("testPanic", L.NewFunction(func(L *glua.LState) int { L.SetGlobal("testPanic", L.NewFunction(func(L *glua.LState) int {
panic(struct{ First, Second *int }{&target, &target}) panic(struct{ First, Second *int }{&target, &target})
})) }))
+12 -11
View File
@@ -8,6 +8,7 @@ import (
"fmt" "fmt"
"net" "net"
"os" "os"
"slices"
"strconv" "strconv"
"strings" "strings"
@@ -31,7 +32,7 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
switch network { switch network {
case "tcp": case "tcp":
if net.ParseIP(srcIP).To4() != nil { if net.ParseIP(srcIP).To4() != nil {
procFiles = []string{"/proc/net/tcp"} procFiles = []string{"/proc/net/tcp", "/proc/net/tcp6"}
} else { } else {
procFiles = []string{"/proc/net/tcp6"} procFiles = []string{"/proc/net/tcp6"}
} }
@@ -45,14 +46,18 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
panic("Unsupported network type for process lookup.") panic("Unsupported network type for process lookup.")
} }
targetHexAddr := formatProcNetAddress(net.ParseIP(srcIP), Port(srcPort)) 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)))
}
portFallback := "" portFallback := ""
if network == "udp" { if network == "udp" {
portFallback = fmt.Sprintf(":%04X", srcPort) portFallback = fmt.Sprintf(":%04X", srcPort)
} }
inode, err := findInodeInFiles(procFiles, targetHexAddr, portFallback) inode, err := findInodeInFiles(procFiles, targetHexAddrs, portFallback)
if err != nil { if err != nil {
return 0, "", "", errors.New("could not search in ", strings.Join(procFiles, " and ")).Base(err) return 0, "", "", errors.New("could not search in ", strings.Join(procFiles, " and ")).Base(err)
} }
@@ -84,13 +89,9 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
return pid, procName, absPath, nil 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 { func formatProcNetAddress(addr net.IP, port Port) string {
var ipBytes []byte ipBytes := []byte(addr)
if ipv4 := addr.To4(); ipv4 != nil {
ipBytes = ipv4
} else {
ipBytes = addr.To16()
}
var formatted strings.Builder var formatted strings.Builder
formatted.Grow(len(ipBytes)*2 + 5) formatted.Grow(len(ipBytes)*2 + 5)
@@ -101,7 +102,7 @@ func formatProcNetAddress(addr net.IP, port Port) string {
return formatted.String() return formatted.String()
} }
func findInodeInFiles(filePaths []string, targetHexAddr, portFallback string) (string, error) { func findInodeInFiles(filePaths []string, targetHexAddrs []string, portFallback string) (string, error) {
onlyMatchedPort := "" onlyMatchedPort := ""
for i, filePath := range filePaths { for i, filePath := range filePaths {
@@ -122,7 +123,7 @@ func findInodeInFiles(filePaths []string, targetHexAddr, portFallback string) (s
} }
localAddress := fields[1] localAddress := fields[1]
if localAddress == targetHexAddr { if slices.Contains(targetHexAddrs, localAddress) {
return fields[9], nil return fields[9], nil
} }
if portFallback != "" && strings.HasSuffix(localAddress, portFallback) { if portFallback != "" && strings.HasSuffix(localAddress, portFallback) {
+50
View File
@@ -0,0 +1,50 @@
//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,7 +16,6 @@ const (
UseReadV = "xray.buf.readv" UseReadV = "xray.buf.readv"
UseFreedomSplice = "xray.buf.splice" UseFreedomSplice = "xray.buf.splice"
UseVmessPadding = "xray.vmess.padding" UseVmessPadding = "xray.vmess.padding"
UseCone = "xray.cone.disabled"
UseStrictJSON = "xray.json.strict" UseStrictJSON = "xray.json.strict"
BufferSize = "xray.ray.buffer.size" BufferSize = "xray.ray.buffer.size"
-3
View File
@@ -63,9 +63,6 @@ func init() {
} }
func GetGlobalID(ctx context.Context) (globalID [8]byte) { 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 && 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") { (inbound.Name == "dokodemo-door" || inbound.Name == "socks" || inbound.Name == "shadowsocks" || inbound.Name == "tun") {
h := blake3.New(8, ensureBaseKey()) h := blake3.New(8, ensureBaseKey())
+3 -3
View File
@@ -53,7 +53,7 @@ func TestXrayDial(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -105,7 +105,7 @@ func TestXrayDialUDPConn(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -174,7 +174,7 @@ func TestXrayDialUDP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
-2
View File
@@ -192,8 +192,6 @@ func initInstanceWithConfig(config *Config, server *Instance) (bool, error) {
if err := platform.ReloadEnvSettings(); err != nil { if err := platform.ReloadEnvSettings(); err != nil {
return true, errors.New("failed to reload environment settings").Base(err) 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 { for _, appSettings := range config.App {
settings, err := appSettings.GetInstance() settings, err := appSettings.GetInstance()
+1 -1
View File
@@ -45,7 +45,7 @@ require (
github.com/huin/goupnp v1.2.0 // indirect github.com/huin/goupnp v1.2.0 // indirect
github.com/jackpal/go-nat-pmp v1.0.2 // indirect github.com/jackpal/go-nat-pmp v1.0.2 // indirect
github.com/juju/ratelimit v1.0.2 // indirect github.com/juju/ratelimit v1.0.2 // indirect
github.com/klauspost/compress v1.20.1 // indirect github.com/klauspost/compress v1.20.4 // indirect
github.com/koron/go-ssdp v0.0.4 // indirect github.com/koron/go-ssdp v0.0.4 // indirect
github.com/libp2p/go-netroute v0.2.1 // indirect github.com/libp2p/go-netroute v0.2.1 // indirect
github.com/molecule-man/go-brrr v1.2.0 // indirect github.com/molecule-man/go-brrr v1.2.0 // indirect
+2
View File
@@ -33,6 +33,8 @@ 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/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 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= 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 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ=
github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/koron/go-ssdp v0.0.4 h1:1IDwrghSKYM7yLf7XCzbByg2sJ/JcNOZRXS2jczTwz0= github.com/koron/go-ssdp v0.0.4 h1:1IDwrghSKYM7yLf7XCzbByg2sJ/JcNOZRXS2jczTwz0=
+12 -6
View File
@@ -5,7 +5,8 @@ import (
"strings" "strings"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/proxy/blackhole" "github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/proxy/freedom"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
) )
@@ -19,24 +20,29 @@ type BlackholeConfig struct {
} }
func (v *BlackholeConfig) Build() (proto.Message, error) { func (v *BlackholeConfig) Build() (proto.Message, error) {
config := new(blackhole.Config) errors.PrintDeprecatedFeatureWarning(`"blackhole" outbound`, `"freedom" outbound with a blocking "firewall" rule`)
rule := &freedom.FirewallConfig{
Action: freedom.RuleAction_Block,
Delay: &freedom.Range{},
LogLevel: log.Severity_Unknown.Enum(),
}
if v.Response != nil { if v.Response != nil {
responseName := strings.ToLower(v.Response.Type) responseName := strings.ToLower(v.Response.Type)
switch responseName { switch responseName {
case "none", "": case "none", "":
config.Response = &blackhole.Response{Type: "none"} rule.Reply = &freedom.Reply{Type: "none"}
case "http": case "http":
config.Response = &blackhole.Response{Type: "http"} rule.Reply = &freedom.Reply{Type: "http"}
case "custom": case "custom":
data, err := base64.StdEncoding.DecodeString(v.Response.CustomResponseData) data, err := base64.StdEncoding.DecodeString(v.Response.CustomResponseData)
if err != nil { if err != nil {
return nil, errors.New("failed to decode custom response data: " + err.Error()) return nil, errors.New("failed to decode custom response data: " + err.Error())
} }
config.Response = &blackhole.Response{Type: "custom", CustomResponseData: data} rule.Reply = &freedom.Reply{Type: "custom", CustomResponseData: data}
default: default:
return nil, errors.New("unknown blackhole response: " + responseName) return nil, errors.New("unknown blackhole response: " + responseName)
} }
} }
return config, nil return &freedom.Config{Firewall: []*freedom.FirewallConfig{rule}}, nil
} }
+26 -9
View File
@@ -3,8 +3,9 @@ package conf_test
import ( import (
"testing" "testing"
"github.com/xtls/xray-core/common/log"
. "github.com/xtls/xray-core/infra/conf" . "github.com/xtls/xray-core/infra/conf"
"github.com/xtls/xray-core/proxy/blackhole" "github.com/xtls/xray-core/proxy/freedom"
) )
func TestHTTPResponseJSON(t *testing.T) { func TestHTTPResponseJSON(t *testing.T) {
@@ -20,14 +21,25 @@ func TestHTTPResponseJSON(t *testing.T) {
} }
}`, }`,
Parser: loadJSON(creator), Parser: loadJSON(creator),
Output: &blackhole.Config{ Output: &freedom.Config{
Response: &blackhole.Response{Type: "http"}, Firewall: []*freedom.FirewallConfig{{
Action: freedom.RuleAction_Block,
Delay: &freedom.Range{},
LogLevel: log.Severity_Unknown.Enum(),
Reply: &freedom.Reply{Type: "http"},
}},
}, },
}, },
{ {
Input: `{}`, Input: `{}`,
Parser: loadJSON(creator), Parser: loadJSON(creator),
Output: &blackhole.Config{}, Output: &freedom.Config{
Firewall: []*freedom.FirewallConfig{{
Action: freedom.RuleAction_Block,
Delay: &freedom.Range{},
LogLevel: log.Severity_Unknown.Enum(),
}},
},
}, },
}) })
} }
@@ -46,11 +58,16 @@ func TestCustomResponseJSON(t *testing.T) {
} }
}`, }`,
Parser: loadJSON(creator), Parser: loadJSON(creator),
Output: &blackhole.Config{ Output: &freedom.Config{
Response: &blackhole.Response{ Firewall: []*freedom.FirewallConfig{{
Type: "custom", Action: freedom.RuleAction_Block,
CustomResponseData: []byte("custom response"), Delay: &freedom.Range{},
}, LogLevel: log.Severity_Unknown.Enum(),
Reply: &freedom.Reply{
Type: "custom",
CustomResponseData: []byte("custom response"),
},
}},
}, },
}, },
}) })
+68 -28
View File
@@ -18,16 +18,17 @@ import (
) )
type FreedomConfig struct { type FreedomConfig struct {
TargetStrategy string `json:"targetStrategy"` TargetStrategy string `json:"targetStrategy"`
DomainStrategy string `json:"domainStrategy"` DomainStrategy string `json:"domainStrategy"`
Redirect string `json:"redirect"` Redirect string `json:"redirect"`
UserLevel uint32 `json:"userLevel"` UserLevel uint32 `json:"userLevel"`
Fragment *Fragment `json:"fragment"` Fragment *Fragment `json:"fragment"`
Noise *Noise `json:"noise"` Noise *Noise `json:"noise"`
Noises []*Noise `json:"noises"` Noises []*Noise `json:"noises"`
ProxyProtocol uint32 `json:"proxyProtocol"` ProxyProtocol uint32 `json:"proxyProtocol"`
IPsBlocked *StringList `json:"ipsBlocked"` IPsBlocked *StringList `json:"ipsBlocked"`
FinalRules []*FreedomFinalRuleConfig `json:"finalRules"` Firewall []*FreedomFirewallConfig `json:"firewall"`
FinalRules []*FreedomFirewallConfig `json:"finalRules"`
} }
type Fragment struct { type Fragment struct {
@@ -44,21 +45,45 @@ type Noise struct {
ApplyTo string `json:"applyTo"` ApplyTo string `json:"applyTo"`
} }
type FreedomFinalRuleConfig struct { type FreedomFirewallConfig struct {
Action string `json:"action"` Action string `json:"action"`
Network *NetworkList `json:"network"` Network *NetworkList `json:"network"`
Port *PortList `json:"port"` Port *PortList `json:"port"`
IP *StringList `json:"ip"` IP *StringList `json:"ip"`
Delay *Int32Range `json:"delay"` Delay *Int32Range `json:"delay"`
LogLevel string `json:"logLevel"` LogLevel string `json:"logLevel"`
BlockDelay *Int32Range `json:"blockDelay"` Reply *FreedomReplyConfig `json:"reply"`
BlockDelay *Int32Range `json:"blockDelay"`
}
type FreedomReplyConfig struct {
Type string `json:"type"`
CustomResponseData string `json:"customResponseData"`
}
func (c *FreedomReplyConfig) Build() (*freedom.Reply, error) {
replyType := strings.ToLower(c.Type)
switch replyType {
case "none", "":
return &freedom.Reply{Type: "none"}, nil
case "http":
return &freedom.Reply{Type: "http"}, nil
case "custom":
data, err := base64.StdEncoding.DecodeString(c.CustomResponseData)
if err != nil {
return nil, errors.New("failed to decode custom reply data: " + err.Error())
}
return &freedom.Reply{Type: "custom", CustomResponseData: data}, nil
default:
return nil, errors.New("unknown firewall reply: " + replyType)
}
} }
// Build implements Buildable // Build implements Buildable
func (c *FreedomConfig) Build() (proto.Message, error) { func (c *FreedomConfig) Build() (proto.Message, error) {
if c.IPsBlocked != nil { if c.IPsBlocked != nil {
// todo: remove legacy // todo: remove legacy
errors.LogWarning(context.Background(), `The feature "ipsBlocked" has been removed and migrated to "finalRules". Please update your config(s) according to release note and documentation.`) errors.LogWarning(context.Background(), `The feature "ipsBlocked" has been removed and migrated to "firewall". Please update your config(s) according to release note and documentation.`)
} }
config := new(freedom.Config) config := new(freedom.Config)
@@ -184,15 +209,22 @@ func (c *FreedomConfig) Build() (proto.Message, error) {
} }
if c.ProxyProtocol > 0 && c.ProxyProtocol <= 2 { if c.ProxyProtocol > 0 && c.ProxyProtocol <= 2 {
config.ProxyProtocol = c.ProxyProtocol errors.PrintDeprecatedFeatureWarning(`"proxyProtocol" in Freedom`, `"proxy-protocol" in "streamSettings.finalmask.tcp"`)
} }
for _, r := range c.FinalRules { firewall := c.Firewall
if c.FinalRules != nil {
errors.PrintDeprecatedFeatureWarning("finalRules", "firewall")
if firewall == nil {
firewall = c.FinalRules
}
}
for _, r := range firewall {
rule, err := r.Build() rule, err := r.Build()
if err != nil { if err != nil {
return nil, err return nil, err
} }
config.FinalRules = append(config.FinalRules, rule) config.Firewall = append(config.Firewall, rule)
} }
return config, nil return config, nil
@@ -254,8 +286,8 @@ func ParseNoise(noise *Noise) (*freedom.Noise, error) {
return NConfig, nil return NConfig, nil
} }
func (c *FreedomFinalRuleConfig) Build() (*freedom.FinalRuleConfig, error) { func (c *FreedomFirewallConfig) Build() (*freedom.FirewallConfig, error) {
rule := &freedom.FinalRuleConfig{} rule := &freedom.FirewallConfig{}
switch strings.ToLower(c.Action) { switch strings.ToLower(c.Action) {
case "allow": case "allow":
@@ -283,13 +315,13 @@ func (c *FreedomFinalRuleConfig) Build() (*freedom.FinalRuleConfig, error) {
} }
if c.BlockDelay != nil { if c.BlockDelay != nil {
errors.PrintDeprecatedFeatureWarning("finalRules.blockDelay", "finalRules.delay") errors.PrintDeprecatedFeatureWarning("firewall.blockDelay", "firewall.delay")
c.Delay = c.BlockDelay c.Delay = c.BlockDelay
} }
if rule.Action != freedom.RuleAction_Block { if rule.Action != freedom.RuleAction_Block {
if c.Delay != nil || c.LogLevel != "" { if c.Delay != nil || c.LogLevel != "" || c.Reply != nil {
return nil, errors.New("delay and logLevel are only supported for block finalRules") return nil, errors.New("delay, logLevel and reply are only supported for firewall action block")
} }
return rule, nil return rule, nil
} }
@@ -301,6 +333,14 @@ func (c *FreedomFinalRuleConfig) Build() (*freedom.FinalRuleConfig, error) {
} }
} }
if c.Reply != nil {
reply, err := c.Reply.Build()
if err != nil {
return nil, err
}
rule.Reply = reply
}
switch strings.ToLower(c.LogLevel) { switch strings.ToLower(c.LogLevel) {
case "", "info": case "", "info":
rule.LogLevel = log.Severity_Info.Enum() rule.LogLevel = log.Severity_Info.Enum()
@@ -313,7 +353,7 @@ func (c *FreedomFinalRuleConfig) Build() (*freedom.FinalRuleConfig, error) {
case "error": case "error":
rule.LogLevel = log.Severity_Error.Enum() rule.LogLevel = log.Severity_Error.Enum()
default: default:
return nil, errors.New("unknown finalRules.logLevel: ", c.LogLevel) return nil, errors.New("unknown firewall.logLevel: ", c.LogLevel)
} }
return rule, nil return rule, nil
+11 -3
View File
@@ -42,13 +42,17 @@ func TestFreedomConfig(t *testing.T) {
}, },
{ {
Input: `{ Input: `{
"finalRules": [{ "firewall": [{
"action": "block", "action": "block",
"network": "tcp,udp", "network": "tcp,udp",
"port": "53,443", "port": "53,443",
"ip": ["10.0.0.0/8", "2001:db8::/32"], "ip": ["10.0.0.0/8", "2001:db8::/32"],
"delay": "30-60", "delay": "30-60",
"logLevel": "debug" "logLevel": "debug",
"reply": {
"type": "custom",
"customResponseData": "Y3VzdG9tIHJlc3BvbnNl"
}
}, { }, {
"action": "allow", "action": "allow",
"network": ["udp"] "network": ["udp"]
@@ -56,7 +60,7 @@ func TestFreedomConfig(t *testing.T) {
}`, }`,
Parser: loadJSON(creator), Parser: loadJSON(creator),
Output: &freedom.Config{ Output: &freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{ Firewall: []*freedom.FirewallConfig{
{ {
Action: freedom.RuleAction_Block, Action: freedom.RuleAction_Block,
Networks: []net.Network{net.Network_TCP, net.Network_UDP}, Networks: []net.Network{net.Network_TCP, net.Network_UDP},
@@ -90,6 +94,10 @@ func TestFreedomConfig(t *testing.T) {
}, },
Delay: &freedom.Range{Min: 30, Max: 60}, Delay: &freedom.Range{Min: 30, Max: 60},
LogLevel: log.Severity_Debug.Enum(), LogLevel: log.Severity_Debug.Enum(),
Reply: &freedom.Reply{
Type: "custom",
CustomResponseData: []byte("custom response"),
},
}, },
{ {
Action: freedom.RuleAction_Allow, Action: freedom.RuleAction_Allow,
+99 -15
View File
@@ -18,6 +18,7 @@ import (
"github.com/xtls/xray-core/common/geodata" "github.com/xtls/xray-core/common/geodata"
xlua "github.com/xtls/xray-core/common/lua" xlua "github.com/xtls/xray-core/common/lua"
"github.com/xtls/xray-core/common/net" "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"
"github.com/xtls/xray-core/transport/internet/finalmask/filter" "github.com/xtls/xray-core/transport/internet/finalmask/filter"
"github.com/xtls/xray-core/transport/internet/finalmask/fragment" "github.com/xtls/xray-core/transport/internet/finalmask/fragment"
@@ -26,6 +27,7 @@ import (
"github.com/xtls/xray-core/transport/internet/finalmask/mkcp/header" "github.com/xtls/xray-core/transport/internet/finalmask/mkcp/header"
"github.com/xtls/xray-core/transport/internet/finalmask/mkcp/original" "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/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/realm"
"github.com/xtls/xray-core/transport/internet/finalmask/salamander" "github.com/xtls/xray-core/transport/internet/finalmask/salamander"
"github.com/xtls/xray-core/transport/internet/finalmask/sudoku" "github.com/xtls/xray-core/transport/internet/finalmask/sudoku"
@@ -76,11 +78,12 @@ var (
customVarNamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) customVarNamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
tcpmaskLoader = NewJSONConfigLoader(ConfigCreatorCache{ tcpmaskLoader = NewJSONConfigLoader(ConfigCreatorCache{
"filter": func() interface{} { return new(Filter) }, "filter": func() interface{} { return new(Filter) },
"header-custom": func() interface{} { return new(HeaderCustomTCP) }, "header-custom": func() interface{} { return new(HeaderCustomTCP) },
"fragment": func() interface{} { return new(FragmentMask) }, "proxy-protocol": func() interface{} { return new(ProxyProtocol) },
"sudoku": func() interface{} { return new(Sudoku) }, "fragment": func() interface{} { return new(FragmentMask) },
"xmc": func() interface{} { return new(XMC) }, "sudoku": func() interface{} { return new(Sudoku) },
"xmc": func() interface{} { return new(XMC) },
}, "type", "settings") }, "type", "settings")
udpmaskLoader = NewJSONConfigLoader(ConfigCreatorCache{ udpmaskLoader = NewJSONConfigLoader(ConfigCreatorCache{
@@ -97,6 +100,32 @@ var (
}, "type", "settings") }, "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 { type Filter struct {
BlockedSourceIPs []string `json:"blockedSourceIPs"` BlockedSourceIPs []string `json:"blockedSourceIPs"`
AllowedSourceIPs []string `json:"allowedSourceIPs"` AllowedSourceIPs []string `json:"allowedSourceIPs"`
@@ -932,9 +961,25 @@ func (c *XDNS) Build() (proto.Message, error) {
} }
type XMC struct { type XMC struct {
Hostname string `json:"hostname"` Hostname string `json:"hostname"`
Profiles []XMCProfile `json:"profiles"` Profiles []XMCProfile `json:"profiles"`
Password string `json:"password"` 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 string `json:"delay,omitempty"`
} }
type XMCProfile struct { type XMCProfile struct {
@@ -977,6 +1022,48 @@ func (c *XMC) Build() (proto.Message, error) {
if c.Password == "" { if c.Password == "" {
return nil, fmt.Errorf("empty password") return nil, fmt.Errorf("empty password")
} }
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}
for i, turn := range c.Paddings {
minimum, maximum, err := ParseRangeString(turn.Length)
if err != nil {
return nil, fmt.Errorf("minecraft padding turn %d length: %w", i, err)
}
delayMinimum, delayMaximum, err := ParseRangeString(turn.Delay)
if err != nil {
return nil, fmt.Errorf("minecraft padding turn %d delay: %w", i, err)
}
var direction int32
switch turn.Direction {
case "c2s", "client-to-server":
direction = 1
case "s2c", "server-to-client":
direction = 2
default:
return nil, fmt.Errorf("minecraft padding turn %d: invalid direction %q (must be \"c2s\" or \"s2c\")", i, turn.Direction)
}
config.Paddings = append(config.Paddings, &xmc.Padding{
LengthMin: int64(minimum),
LengthMax: int64(maximum),
Direction: direction,
DelayMin: int64(delayMinimum),
DelayMax: int64(delayMaximum),
})
}
if err := config.ValidatePadding(); err != nil {
return nil, fmt.Errorf("minecraft padding: %w", err)
}
rsaPrivateKey, err := xmc.DeriveRSAKey(c.Password) rsaPrivateKey, err := xmc.DeriveRSAKey(c.Password)
if err != nil { if err != nil {
@@ -997,13 +1084,10 @@ func (c *XMC) Build() (proto.Message, error) {
profiles = append(profiles, profile) profiles = append(profiles, profile)
} }
return &xmc.Config{ config.RsaPrivateKey = x509.MarshalPKCS1PrivateKey(rsaPrivateKey)
Password: c.Password, config.RsaPublicKey = rsaPublicKey
Hostname: c.Hostname, config.Profiles = profiles
RsaPrivateKey: x509.MarshalPKCS1PrivateKey(rsaPrivateKey), return config, nil
RsaPublicKey: rsaPublicKey,
Profiles: profiles,
}, nil
} }
type Xicmp struct { type Xicmp struct {
+117
View File
@@ -1,6 +1,7 @@
package conf package conf
import ( import (
"encoding/json"
"strings" "strings"
"testing" "testing"
@@ -10,6 +11,11 @@ import (
func TestXMCBuildProfile(t *testing.T) { func TestXMCBuildProfile(t *testing.T) {
built, err := (&XMC{ built, err := (&XMC{
Password: "test-password", Password: "test-password",
Paddings: []XMCPaddingTurn{
{Length: "3", Direction: "c2s"},
{Length: "127-129", Direction: "s2c", Delay: "100"},
{Length: "8388608", Direction: "c2s", Delay: "50-150"},
},
Profiles: []XMCProfile{ Profiles: []XMCProfile{
{ {
Username: "TestUser", Username: "TestUser",
@@ -26,6 +32,19 @@ func TestXMCBuildProfile(t *testing.T) {
if len(config.Profiles) != 1 || len(config.Profiles[0].Uuid) != 16 { if len(config.Profiles) != 1 || len(config.Profiles[0].Uuid) != 16 {
t.Fatalf("unexpected profiles: %+v", config.Profiles) t.Fatalf("unexpected profiles: %+v", config.Profiles)
} }
if len(config.Paddings) != 3 || config.Paddings[0].LengthMin != 3 || config.Paddings[0].LengthMax != 3 ||
config.Paddings[1].LengthMin != 127 || config.Paddings[1].LengthMax != 129 ||
config.Paddings[2].LengthMin != 8388608 || config.Paddings[2].LengthMax != 8388608 {
t.Fatalf("unexpected padding: %v", config.Paddings)
}
if config.Paddings[0].Direction != 1 || config.Paddings[1].Direction != 2 || config.Paddings[2].Direction != 1 {
t.Fatalf("unexpected padding directions: %v, %v, %v", config.Paddings[0].Direction, config.Paddings[1].Direction, config.Paddings[2].Direction)
}
if config.Paddings[0].DelayMin != 0 || config.Paddings[0].DelayMax != 0 ||
config.Paddings[1].DelayMin != 100 || config.Paddings[1].DelayMax != 100 ||
config.Paddings[2].DelayMin != 50 || config.Paddings[2].DelayMax != 150 {
t.Fatalf("unexpected padding delays: %v, %v, %v", config.Paddings[0].DelayMin, config.Paddings[1].DelayMin, config.Paddings[2].DelayMin)
}
} }
func TestXMCBuildRequiresProfile(t *testing.T) { func TestXMCBuildRequiresProfile(t *testing.T) {
@@ -34,3 +53,101 @@ func TestXMCBuildRequiresProfile(t *testing.T) {
t.Fatalf("expected required profiles error, got %v", err) t.Fatalf("expected required profiles error, got %v", err)
} }
} }
func TestXMCBuildRejectsPadding(t *testing.T) {
for name, padding := range map[string]string{
"empty_length": `[{"length": "", "direction": "c2s"}]`,
"zero_length": `[{"length": "0", "direction": "c2s"}]`,
"one_length": `[{"length": "1", "direction": "c2s"}]`,
"two_length": `[{"length": "2", "direction": "c2s"}]`,
"negative_length": `[{"length": "-1", "direction": "c2s"}]`,
"reversed_range": `[{"length": "64-32", "direction": "c2s"}]`,
"oversized_length": `[{"length": "8388609", "direction": "c2s"}]`,
"huge_length": `[{"length": "4294967299", "direction": "c2s"}]`,
"overflow_length": `[{"length": "9223372036854775808", "direction": "c2s"}]`,
"invalid_range_format": `[{"length": "1-2-3", "direction": "c2s"}]`,
"invalid_direction": `[{"length": "3", "direction": "invalid"}]`,
"missing_direction": `[{"length": "3"}]`,
"numeric_direction": `[{"length": "3", "direction": "1"}]`,
"negative_delay": `[{"length": "3", "direction": "c2s", "delay": "-1"}]`,
"reversed_delay": `[{"length": "3", "direction": "c2s", "delay": "10-5"}]`,
"invalid_delay_format": `[{"length": "3", "direction": "c2s", "delay": "abc"}]`,
"huge_delay": `[{"length": "3", "direction": "c2s", "delay": "9223372036854775807"}]`,
} {
t.Run(name, func(t *testing.T) {
var config XMC
if err := json.Unmarshal([]byte(`{"paddings":`+padding+`}`), &config); err != nil {
t.Fatal(err)
}
config.Password = "test-password"
config.Profiles = []XMCProfile{{
Username: "TestUser", UUID: "00112233-4455-6677-8899-aabbccddeeff",
TexturesValue: "textures-value", TexturesSignature: "textures-signature",
}}
if _, err := config.Build(); err == nil {
t.Fatalf("expected error for padding %s, got success", padding)
} else {
t.Logf("correctly rejected: %v", err)
}
})
}
}
func TestXMCBuildRejectsLongPassword(t *testing.T) {
profile := XMCProfile{
Username: "TestUser", UUID: "00112233-4455-6677-8899-aabbccddeeff",
TexturesValue: "textures-value", TexturesSignature: "textures-signature",
}
// The verify token and the password share one RSA-1024 PKCS#1 v1.5 block,
// so the password cannot exceed xmc.MaxLegacyPasswordLength bytes.
valid := strings.Repeat("p", xmc.MaxLegacyPasswordLength)
if _, err := (&XMC{Password: valid, Profiles: []XMCProfile{profile}}).Build(); err != nil {
t.Fatalf("password of %d bytes was rejected: %v", len(valid), err)
}
tooLong := valid + "p"
_, err := (&XMC{Password: tooLong, Profiles: []XMCProfile{profile}}).Build()
if err == nil || !strings.Contains(err.Error(), "longer than") {
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)
}
}
+10 -1
View File
@@ -407,7 +407,16 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
return nil, errors.New("the masque transport can only be used by the masque outbound") return nil, errors.New("the masque transport can only be used by the masque outbound")
} }
if fc, ok := ts.(*freedom.Config); ok { if _, ok := rawConfig.(*BlackholeConfig); ok {
// The legacy blackhole outbound never used its transport settings.
senderSettings.StreamSettings = nil
} else if fc, ok := ts.(*freedom.Config); ok {
if legacy := rawConfig.(*FreedomConfig); legacy.ProxyProtocol > 0 && legacy.ProxyProtocol <= 2 {
if senderSettings.StreamSettings == nil {
senderSettings.StreamSettings = &internet.StreamConfig{}
}
addProxyProtocolMask(senderSettings.StreamSettings, legacy.ProxyProtocol)
}
if senderSettings.StreamSettings != nil && if senderSettings.StreamSettings != nil &&
senderSettings.StreamSettings.SocketSettings != nil && senderSettings.StreamSettings.SocketSettings != nil &&
senderSettings.StreamSettings.SocketSettings.AddressPortStrategy != internet.AddressPortStrategy_None { senderSettings.StreamSettings.SocketSettings.AddressPortStrategy != internet.AddressPortStrategy_None {
-1
View File
@@ -35,7 +35,6 @@ import (
_ "github.com/xtls/xray-core/app/observatory" _ "github.com/xtls/xray-core/app/observatory"
// Inbound and outbound proxies. // Inbound and outbound proxies.
_ "github.com/xtls/xray-core/proxy/blackhole"
_ "github.com/xtls/xray-core/proxy/dns" _ "github.com/xtls/xray-core/proxy/dns"
_ "github.com/xtls/xray-core/proxy/dokodemo" _ "github.com/xtls/xray-core/proxy/dokodemo"
_ "github.com/xtls/xray-core/proxy/freedom" _ "github.com/xtls/xray-core/proxy/freedom"
-88
View File
@@ -1,88 +0,0 @@
// Package blackhole is an outbound handler that blocks all connections.
package blackhole
import (
"bytes"
"context"
"net/http"
"time"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/dice"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/common/signal"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/internet"
)
// Handler is an outbound connection that silently swallow the entire payload.
type Handler struct {
response []byte
}
var http403response = http.Response{
StatusCode: 403,
ProtoMajor: 1,
ProtoMinor: 1,
Header: http.Header{
"Connection": {"close"},
"Cache-Control": {"max-age=3600, public"},
},
}
// New creates a new blackhole handler.
func New(ctx context.Context, config *Config) (*Handler, error) {
response := []byte{}
if config.Response != nil {
switch config.Response.Type {
case "", "none":
case "http":
var data bytes.Buffer
common.Must(http403response.Write(&data))
response = data.Bytes()
case "custom":
response = config.Response.CustomResponseData
default:
return nil, errors.New("unknown blackhole response: " + config.Response.Type)
}
}
return &Handler{
response: response,
}, nil
}
// Process implements OutboundHandler.Dispatch().
func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
outbounds := session.OutboundsFromContext(ctx)
ob := outbounds[len(outbounds)-1]
ob.Name = "blackhole"
if len(h.response) > 0 {
mbc := buf.MultiBufferContainer{}
common.Must2(mbc.Write(h.response))
link.Writer.WriteMultiBuffer(mbc.MultiBuffer)
// Sleep a little here to make sure the response is sent to client.
time.Sleep(time.Second)
}
defer common.Interrupt(link.Writer)
defer common.Interrupt(link.Reader)
// wait to drain all the possible incoming UDP data
if ob.Target.Network == net.Network_UDP {
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, func() {
cancel()
}, time.Duration(30+dice.Roll(61))*time.Second)
go buf.Copy(link.Reader, buf.Discard, buf.UpdateActivity(timer))
<-ctx.Done()
}
return nil
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return New(ctx, config.(*Config))
}))
}
-76
View File
@@ -1,76 +0,0 @@
package blackhole_test
import (
"bufio"
"bytes"
"context"
"crypto/rand"
"net/http"
"testing"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/proxy/blackhole"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/pipe"
)
func TestBlackholeHTTPResponse(t *testing.T) {
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{}})
handler, err := blackhole.New(ctx, &blackhole.Config{
Response: &blackhole.Response{Type: "http"},
})
common.Must(err)
reader, writer := pipe.New(pipe.WithoutSizeLimit())
dataCh := make(chan buf.MultiBuffer, 1)
go func() {
mb := common.Must2(reader.ReadMultiBuffer())
dataCh <- mb
}()
link := transport.Link{
Reader: reader,
Writer: writer,
}
common.Must(handler.Process(ctx, &link, nil))
mb := <-dataCh
data := make([]byte, mb.Len())
mb.Copy(data)
resp := common.Must2(http.ReadResponse(bufio.NewReader(bytes.NewBuffer(data)), nil))
if resp.StatusCode != 403 {
t.Errorf("expected 403 response, got %d", resp.StatusCode)
}
}
func TestBlackholeCustomResponse(t *testing.T) {
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{}})
// slightly bigger than a buffer
expected := make([]byte, buf.Size+1000)
if _, err := rand.Read(expected); err != nil {
t.Fatal(err)
}
handler, err := blackhole.New(ctx, &blackhole.Config{
Response: &blackhole.Response{
Type: "custom",
CustomResponseData: expected,
},
})
common.Must(err)
reader, writer := pipe.New(pipe.WithoutSizeLimit())
var actual buf.MultiBuffer
var rerr error
go func() {
actual, rerr = reader.ReadMultiBuffer()
}()
link := transport.Link{Reader: reader, Writer: writer}
common.Must(handler.Process(ctx, &link, nil))
common.Must(rerr)
if actual.String() != string(expected) {
t.Errorf("custom response mismatch")
}
}
-180
View File
@@ -1,180 +0,0 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.12
// protoc (unknown)
// source: proxy/blackhole/config.proto
package blackhole
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Response struct {
state protoimpl.MessageState `protogen:"open.v1"`
Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"`
CustomResponseData []byte `protobuf:"bytes,2,opt,name=custom_response_data,json=customResponseData,proto3" json:"custom_response_data,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Response) Reset() {
*x = Response{}
mi := &file_proxy_blackhole_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Response) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Response) ProtoMessage() {}
func (x *Response) ProtoReflect() protoreflect.Message {
mi := &file_proxy_blackhole_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Response.ProtoReflect.Descriptor instead.
func (*Response) Descriptor() ([]byte, []int) {
return file_proxy_blackhole_config_proto_rawDescGZIP(), []int{0}
}
func (x *Response) GetType() string {
if x != nil {
return x.Type
}
return ""
}
func (x *Response) GetCustomResponseData() []byte {
if x != nil {
return x.CustomResponseData
}
return nil
}
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
Response *Response `protobuf:"bytes,1,opt,name=response,proto3" json:"response,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_proxy_blackhole_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_proxy_blackhole_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_proxy_blackhole_config_proto_rawDescGZIP(), []int{1}
}
func (x *Config) GetResponse() *Response {
if x != nil {
return x.Response
}
return nil
}
var File_proxy_blackhole_config_proto protoreflect.FileDescriptor
const file_proxy_blackhole_config_proto_rawDesc = "" +
"\n" +
"\x1cproxy/blackhole/config.proto\x12\x14xray.proxy.blackhole\"P\n" +
"\bResponse\x12\x12\n" +
"\x04type\x18\x01 \x01(\tR\x04type\x120\n" +
"\x14custom_response_data\x18\x02 \x01(\fR\x12customResponseData\"D\n" +
"\x06Config\x12:\n" +
"\bresponse\x18\x01 \x01(\v2\x1e.xray.proxy.blackhole.ResponseR\bresponseB^\n" +
"\x18com.xray.proxy.blackholeP\x01Z)github.com/xtls/xray-core/proxy/blackhole\xaa\x02\x14Xray.Proxy.Blackholeb\x06proto3"
var (
file_proxy_blackhole_config_proto_rawDescOnce sync.Once
file_proxy_blackhole_config_proto_rawDescData []byte
)
func file_proxy_blackhole_config_proto_rawDescGZIP() []byte {
file_proxy_blackhole_config_proto_rawDescOnce.Do(func() {
file_proxy_blackhole_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_blackhole_config_proto_rawDesc), len(file_proxy_blackhole_config_proto_rawDesc)))
})
return file_proxy_blackhole_config_proto_rawDescData
}
var file_proxy_blackhole_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_proxy_blackhole_config_proto_goTypes = []any{
(*Response)(nil), // 0: xray.proxy.blackhole.Response
(*Config)(nil), // 1: xray.proxy.blackhole.Config
}
var file_proxy_blackhole_config_proto_depIdxs = []int32{
0, // 0: xray.proxy.blackhole.Config.response:type_name -> xray.proxy.blackhole.Response
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_proxy_blackhole_config_proto_init() }
func file_proxy_blackhole_config_proto_init() {
if File_proxy_blackhole_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_blackhole_config_proto_rawDesc), len(file_proxy_blackhole_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_blackhole_config_proto_goTypes,
DependencyIndexes: file_proxy_blackhole_config_proto_depIdxs,
MessageInfos: file_proxy_blackhole_config_proto_msgTypes,
}.Build()
File_proxy_blackhole_config_proto = out.File
file_proxy_blackhole_config_proto_goTypes = nil
file_proxy_blackhole_config_proto_depIdxs = nil
}
-16
View File
@@ -1,16 +0,0 @@
syntax = "proto3";
package xray.proxy.blackhole;
option csharp_namespace = "Xray.Proxy.Blackhole";
option go_package = "github.com/xtls/xray-core/proxy/blackhole";
option java_package = "com.xray.proxy.blackhole";
option java_multiple_files = true;
message Response {
string type = 1;
bytes custom_response_data = 2;
}
message Config {
Response response = 1;
}
-19
View File
@@ -1,19 +0,0 @@
package blackhole_test
import (
"context"
"testing"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/proxy/blackhole"
)
func TestHTTPResponse(t *testing.T) {
handler, err := blackhole.New(context.Background(), &blackhole.Config{
Response: &blackhole.Response{Type: "http"},
})
common.Must(err)
if handler == nil {
t.Error("expected HTTP response handler")
}
}
+130 -74
View File
@@ -352,32 +352,28 @@ func (x *Range) GetMax() uint64 {
return 0 return 0
} }
type FinalRuleConfig struct { type Reply struct {
state protoimpl.MessageState `protogen:"open.v1"` state protoimpl.MessageState `protogen:"open.v1"`
Action RuleAction `protobuf:"varint,1,opt,name=action,proto3,enum=xray.proxy.freedom.RuleAction" json:"action,omitempty"` Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"`
Networks []net.Network `protobuf:"varint,2,rep,packed,name=networks,proto3,enum=xray.common.net.Network" json:"networks,omitempty"` CustomResponseData []byte `protobuf:"bytes,2,opt,name=custom_response_data,json=customResponseData,proto3" json:"custom_response_data,omitempty"`
PortList *net.PortList `protobuf:"bytes,3,opt,name=port_list,json=portList,proto3" json:"port_list,omitempty"` unknownFields protoimpl.UnknownFields
Ip []*geodata.IPRule `protobuf:"bytes,4,rep,name=ip,proto3" json:"ip,omitempty"` sizeCache protoimpl.SizeCache
Delay *Range `protobuf:"bytes,5,opt,name=delay,proto3" json:"delay,omitempty"`
LogLevel *log.Severity `protobuf:"varint,6,opt,name=log_level,json=logLevel,proto3,enum=xray.common.log.Severity,oneof" json:"log_level,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
} }
func (x *FinalRuleConfig) Reset() { func (x *Reply) Reset() {
*x = FinalRuleConfig{} *x = Reply{}
mi := &file_proxy_freedom_config_proto_msgTypes[4] mi := &file_proxy_freedom_config_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi) ms.StoreMessageInfo(mi)
} }
func (x *FinalRuleConfig) String() string { func (x *Reply) String() string {
return protoimpl.X.MessageStringOf(x) return protoimpl.X.MessageStringOf(x)
} }
func (*FinalRuleConfig) ProtoMessage() {} func (*Reply) ProtoMessage() {}
func (x *FinalRuleConfig) ProtoReflect() protoreflect.Message { func (x *Reply) ProtoReflect() protoreflect.Message {
mi := &file_proxy_freedom_config_proto_msgTypes[4] mi := &file_proxy_freedom_config_proto_msgTypes[4]
if x != nil { if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
@@ -389,69 +385,132 @@ func (x *FinalRuleConfig) ProtoReflect() protoreflect.Message {
return mi.MessageOf(x) return mi.MessageOf(x)
} }
// Deprecated: Use FinalRuleConfig.ProtoReflect.Descriptor instead. // Deprecated: Use Reply.ProtoReflect.Descriptor instead.
func (*FinalRuleConfig) Descriptor() ([]byte, []int) { func (*Reply) Descriptor() ([]byte, []int) {
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{4} return file_proxy_freedom_config_proto_rawDescGZIP(), []int{4}
} }
func (x *FinalRuleConfig) GetAction() RuleAction { func (x *Reply) GetType() string {
if x != nil {
return x.Type
}
return ""
}
func (x *Reply) GetCustomResponseData() []byte {
if x != nil {
return x.CustomResponseData
}
return nil
}
type FirewallConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Action RuleAction `protobuf:"varint,1,opt,name=action,proto3,enum=xray.proxy.freedom.RuleAction" json:"action,omitempty"`
Networks []net.Network `protobuf:"varint,2,rep,packed,name=networks,proto3,enum=xray.common.net.Network" json:"networks,omitempty"`
PortList *net.PortList `protobuf:"bytes,3,opt,name=port_list,json=portList,proto3" json:"port_list,omitempty"`
Ip []*geodata.IPRule `protobuf:"bytes,4,rep,name=ip,proto3" json:"ip,omitempty"`
Delay *Range `protobuf:"bytes,5,opt,name=delay,proto3" json:"delay,omitempty"`
LogLevel *log.Severity `protobuf:"varint,6,opt,name=log_level,json=logLevel,proto3,enum=xray.common.log.Severity,oneof" json:"log_level,omitempty"`
Reply *Reply `protobuf:"bytes,7,opt,name=reply,proto3" json:"reply,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *FirewallConfig) Reset() {
*x = FirewallConfig{}
mi := &file_proxy_freedom_config_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *FirewallConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*FirewallConfig) ProtoMessage() {}
func (x *FirewallConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_freedom_config_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use FirewallConfig.ProtoReflect.Descriptor instead.
func (*FirewallConfig) Descriptor() ([]byte, []int) {
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{5}
}
func (x *FirewallConfig) GetAction() RuleAction {
if x != nil { if x != nil {
return x.Action return x.Action
} }
return RuleAction_Allow return RuleAction_Allow
} }
func (x *FinalRuleConfig) GetNetworks() []net.Network { func (x *FirewallConfig) GetNetworks() []net.Network {
if x != nil { if x != nil {
return x.Networks return x.Networks
} }
return nil return nil
} }
func (x *FinalRuleConfig) GetPortList() *net.PortList { func (x *FirewallConfig) GetPortList() *net.PortList {
if x != nil { if x != nil {
return x.PortList return x.PortList
} }
return nil return nil
} }
func (x *FinalRuleConfig) GetIp() []*geodata.IPRule { func (x *FirewallConfig) GetIp() []*geodata.IPRule {
if x != nil { if x != nil {
return x.Ip return x.Ip
} }
return nil return nil
} }
func (x *FinalRuleConfig) GetDelay() *Range { func (x *FirewallConfig) GetDelay() *Range {
if x != nil { if x != nil {
return x.Delay return x.Delay
} }
return nil return nil
} }
func (x *FinalRuleConfig) GetLogLevel() log.Severity { func (x *FirewallConfig) GetLogLevel() log.Severity {
if x != nil && x.LogLevel != nil { if x != nil && x.LogLevel != nil {
return *x.LogLevel return *x.LogLevel
} }
return log.Severity(0) return log.Severity(0)
} }
func (x *FirewallConfig) GetReply() *Reply {
if x != nil {
return x.Reply
}
return nil
}
type Config struct { type Config struct {
state protoimpl.MessageState `protogen:"open.v1"` 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"` 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"` 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"` 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"` 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"` Noises []*Noise `protobuf:"bytes,7,rep,name=noises,proto3" json:"noises,omitempty"`
FinalRules []*FinalRuleConfig `protobuf:"bytes,8,rep,name=final_rules,json=finalRules,proto3" json:"final_rules,omitempty"` Firewall []*FirewallConfig `protobuf:"bytes,8,rep,name=firewall,proto3" json:"firewall,omitempty"`
unknownFields protoimpl.UnknownFields unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache sizeCache protoimpl.SizeCache
} }
func (x *Config) Reset() { func (x *Config) Reset() {
*x = Config{} *x = Config{}
mi := &file_proxy_freedom_config_proto_msgTypes[5] mi := &file_proxy_freedom_config_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi) ms.StoreMessageInfo(mi)
} }
@@ -463,7 +522,7 @@ func (x *Config) String() string {
func (*Config) ProtoMessage() {} func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message { func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_proxy_freedom_config_proto_msgTypes[5] mi := &file_proxy_freedom_config_proto_msgTypes[6]
if x != nil { if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil { if ms.LoadMessageInfo() == nil {
@@ -476,7 +535,7 @@ func (x *Config) ProtoReflect() protoreflect.Message {
// Deprecated: Use Config.ProtoReflect.Descriptor instead. // Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) { func (*Config) Descriptor() ([]byte, []int) {
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{5} return file_proxy_freedom_config_proto_rawDescGZIP(), []int{6}
} }
func (x *Config) GetDomainStrategy() internet.DomainStrategy { func (x *Config) GetDomainStrategy() internet.DomainStrategy {
@@ -507,13 +566,6 @@ func (x *Config) GetFragment() *Fragment {
return nil return nil
} }
func (x *Config) GetProxyProtocol() uint32 {
if x != nil {
return x.ProxyProtocol
}
return 0
}
func (x *Config) GetNoises() []*Noise { func (x *Config) GetNoises() []*Noise {
if x != nil { if x != nil {
return x.Noises return x.Noises
@@ -521,9 +573,9 @@ func (x *Config) GetNoises() []*Noise {
return nil return nil
} }
func (x *Config) GetFinalRules() []*FinalRuleConfig { func (x *Config) GetFirewall() []*FirewallConfig {
if x != nil { if x != nil {
return x.FinalRules return x.Firewall
} }
return nil return nil
} }
@@ -558,26 +610,28 @@ const file_proxy_freedom_config_proto_rawDesc = "" +
"\bapply_to\x18\x06 \x01(\tR\aapplyTo\"+\n" + "\bapply_to\x18\x06 \x01(\tR\aapplyTo\"+\n" +
"\x05Range\x12\x10\n" + "\x05Range\x12\x10\n" +
"\x03min\x18\x01 \x01(\x04R\x03min\x12\x10\n" + "\x03min\x18\x01 \x01(\x04R\x03min\x12\x10\n" +
"\x03max\x18\x02 \x01(\x04R\x03max\"\xe0\x02\n" + "\x03max\x18\x02 \x01(\x04R\x03max\"M\n" +
"\x0fFinalRuleConfig\x126\n" + "\x05Reply\x12\x12\n" +
"\x04type\x18\x01 \x01(\tR\x04type\x120\n" +
"\x14custom_response_data\x18\x02 \x01(\fR\x12customResponseData\"\x90\x03\n" +
"\x0eFirewallConfig\x126\n" +
"\x06action\x18\x01 \x01(\x0e2\x1e.xray.proxy.freedom.RuleActionR\x06action\x124\n" + "\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" + "\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" + "\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" + "\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" + "\x05delay\x18\x05 \x01(\v2\x19.xray.proxy.freedom.RangeR\x05delay\x12;\n" +
"\tlog_level\x18\x06 \x01(\x0e2\x19.xray.common.log.SeverityH\x00R\blogLevel\x88\x01\x01B\f\n" + "\tlog_level\x18\x06 \x01(\x0e2\x19.xray.common.log.SeverityH\x00R\blogLevel\x88\x01\x01\x12/\n" +
"\x05reply\x18\a \x01(\v2\x19.xray.proxy.freedom.ReplyR\x05replyB\f\n" +
"\n" + "\n" +
"_log_level\"\xaf\x03\n" + "_log_level\"\x88\x03\n" +
"\x06Config\x12P\n" + "\x06Config\x12P\n" +
"\x0fdomain_strategy\x18\x01 \x01(\x0e2'.xray.transport.internet.DomainStrategyR\x0edomainStrategy\x12Z\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" + "\x14destination_override\x18\x03 \x01(\v2'.xray.proxy.freedom.DestinationOverrideR\x13destinationOverride\x12\x1d\n" +
"\n" + "\n" +
"user_level\x18\x04 \x01(\rR\tuserLevel\x128\n" + "user_level\x18\x04 \x01(\rR\tuserLevel\x128\n" +
"\bfragment\x18\x05 \x01(\v2\x1c.xray.proxy.freedom.FragmentR\bfragment\x12%\n" + "\bfragment\x18\x05 \x01(\v2\x1c.xray.proxy.freedom.FragmentR\bfragment\x121\n" +
"\x0eproxy_protocol\x18\x06 \x01(\rR\rproxyProtocol\x121\n" + "\x06noises\x18\a \x03(\v2\x19.xray.proxy.freedom.NoiseR\x06noises\x12>\n" +
"\x06noises\x18\a \x03(\v2\x19.xray.proxy.freedom.NoiseR\x06noises\x12D\n" + "\bfirewall\x18\b \x03(\v2\".xray.proxy.freedom.FirewallConfigR\bfirewallJ\x04\b\x06\x10\a*\"\n" +
"\vfinal_rules\x18\b \x03(\v2#.xray.proxy.freedom.FinalRuleConfigR\n" +
"finalRules*\"\n" +
"\n" + "\n" +
"RuleAction\x12\t\n" + "RuleAction\x12\t\n" +
"\x05Allow\x10\x00\x12\t\n" + "\x05Allow\x10\x00\x12\t\n" +
@@ -597,40 +651,42 @@ func file_proxy_freedom_config_proto_rawDescGZIP() []byte {
} }
var file_proxy_freedom_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_proxy_freedom_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_proxy_freedom_config_proto_msgTypes = make([]protoimpl.MessageInfo, 6) var file_proxy_freedom_config_proto_msgTypes = make([]protoimpl.MessageInfo, 7)
var file_proxy_freedom_config_proto_goTypes = []any{ var file_proxy_freedom_config_proto_goTypes = []any{
(RuleAction)(0), // 0: xray.proxy.freedom.RuleAction (RuleAction)(0), // 0: xray.proxy.freedom.RuleAction
(*DestinationOverride)(nil), // 1: xray.proxy.freedom.DestinationOverride (*DestinationOverride)(nil), // 1: xray.proxy.freedom.DestinationOverride
(*Fragment)(nil), // 2: xray.proxy.freedom.Fragment (*Fragment)(nil), // 2: xray.proxy.freedom.Fragment
(*Noise)(nil), // 3: xray.proxy.freedom.Noise (*Noise)(nil), // 3: xray.proxy.freedom.Noise
(*Range)(nil), // 4: xray.proxy.freedom.Range (*Range)(nil), // 4: xray.proxy.freedom.Range
(*FinalRuleConfig)(nil), // 5: xray.proxy.freedom.FinalRuleConfig (*Reply)(nil), // 5: xray.proxy.freedom.Reply
(*Config)(nil), // 6: xray.proxy.freedom.Config (*FirewallConfig)(nil), // 6: xray.proxy.freedom.FirewallConfig
(*protocol.ServerEndpoint)(nil), // 7: xray.common.protocol.ServerEndpoint (*Config)(nil), // 7: xray.proxy.freedom.Config
(net.Network)(0), // 8: xray.common.net.Network (*protocol.ServerEndpoint)(nil), // 8: xray.common.protocol.ServerEndpoint
(*net.PortList)(nil), // 9: xray.common.net.PortList (net.Network)(0), // 9: xray.common.net.Network
(*geodata.IPRule)(nil), // 10: xray.common.geodata.IPRule (*net.PortList)(nil), // 10: xray.common.net.PortList
(log.Severity)(0), // 11: xray.common.log.Severity (*geodata.IPRule)(nil), // 11: xray.common.geodata.IPRule
(internet.DomainStrategy)(0), // 12: xray.transport.internet.DomainStrategy (log.Severity)(0), // 12: xray.common.log.Severity
(internet.DomainStrategy)(0), // 13: xray.transport.internet.DomainStrategy
} }
var file_proxy_freedom_config_proto_depIdxs = []int32{ var file_proxy_freedom_config_proto_depIdxs = []int32{
7, // 0: xray.proxy.freedom.DestinationOverride.server:type_name -> xray.common.protocol.ServerEndpoint 8, // 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 0, // 1: xray.proxy.freedom.FirewallConfig.action:type_name -> xray.proxy.freedom.RuleAction
8, // 2: xray.proxy.freedom.FinalRuleConfig.networks:type_name -> xray.common.net.Network 9, // 2: xray.proxy.freedom.FirewallConfig.networks:type_name -> xray.common.net.Network
9, // 3: xray.proxy.freedom.FinalRuleConfig.port_list:type_name -> xray.common.net.PortList 10, // 3: xray.proxy.freedom.FirewallConfig.port_list:type_name -> xray.common.net.PortList
10, // 4: xray.proxy.freedom.FinalRuleConfig.ip:type_name -> xray.common.geodata.IPRule 11, // 4: xray.proxy.freedom.FirewallConfig.ip:type_name -> xray.common.geodata.IPRule
4, // 5: xray.proxy.freedom.FinalRuleConfig.delay:type_name -> xray.proxy.freedom.Range 4, // 5: xray.proxy.freedom.FirewallConfig.delay:type_name -> xray.proxy.freedom.Range
11, // 6: xray.proxy.freedom.FinalRuleConfig.log_level:type_name -> xray.common.log.Severity 12, // 6: xray.proxy.freedom.FirewallConfig.log_level:type_name -> xray.common.log.Severity
12, // 7: xray.proxy.freedom.Config.domain_strategy:type_name -> xray.transport.internet.DomainStrategy 5, // 7: xray.proxy.freedom.FirewallConfig.reply:type_name -> xray.proxy.freedom.Reply
1, // 8: xray.proxy.freedom.Config.destination_override:type_name -> xray.proxy.freedom.DestinationOverride 13, // 8: xray.proxy.freedom.Config.domain_strategy:type_name -> xray.transport.internet.DomainStrategy
2, // 9: xray.proxy.freedom.Config.fragment:type_name -> xray.proxy.freedom.Fragment 1, // 9: xray.proxy.freedom.Config.destination_override:type_name -> xray.proxy.freedom.DestinationOverride
3, // 10: xray.proxy.freedom.Config.noises:type_name -> xray.proxy.freedom.Noise 2, // 10: xray.proxy.freedom.Config.fragment:type_name -> xray.proxy.freedom.Fragment
5, // 11: xray.proxy.freedom.Config.final_rules:type_name -> xray.proxy.freedom.FinalRuleConfig 3, // 11: xray.proxy.freedom.Config.noises:type_name -> xray.proxy.freedom.Noise
12, // [12:12] is the sub-list for method output_type 6, // 12: xray.proxy.freedom.Config.firewall:type_name -> xray.proxy.freedom.FirewallConfig
12, // [12:12] is the sub-list for method input_type 13, // [13:13] is the sub-list for method output_type
12, // [12:12] is the sub-list for extension type_name 13, // [13:13] is the sub-list for method input_type
12, // [12:12] is the sub-list for extension extendee 13, // [13:13] is the sub-list for extension type_name
0, // [0:12] is the sub-list for field type_name 13, // [13:13] is the sub-list for extension extendee
0, // [0:13] is the sub-list for field type_name
} }
func init() { file_proxy_freedom_config_proto_init() } func init() { file_proxy_freedom_config_proto_init() }
@@ -638,14 +694,14 @@ func file_proxy_freedom_config_proto_init() {
if File_proxy_freedom_config_proto != nil { if File_proxy_freedom_config_proto != nil {
return return
} }
file_proxy_freedom_config_proto_msgTypes[4].OneofWrappers = []any{} file_proxy_freedom_config_proto_msgTypes[5].OneofWrappers = []any{}
type x struct{} type x struct{}
out := protoimpl.TypeBuilder{ out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{ File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(), GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_freedom_config_proto_rawDesc), len(file_proxy_freedom_config_proto_rawDesc)), RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_freedom_config_proto_rawDesc), len(file_proxy_freedom_config_proto_rawDesc)),
NumEnums: 1, NumEnums: 1,
NumMessages: 6, NumMessages: 7,
NumExtensions: 0, NumExtensions: 0,
NumServices: 0, NumServices: 0,
}, },
+9 -3
View File
@@ -47,21 +47,27 @@ enum RuleAction {
Block = 1; Block = 1;
} }
message FinalRuleConfig { message Reply {
string type = 1;
bytes custom_response_data = 2;
}
message FirewallConfig {
RuleAction action = 1; RuleAction action = 1;
repeated xray.common.net.Network networks = 2; repeated xray.common.net.Network networks = 2;
xray.common.net.PortList port_list = 3; xray.common.net.PortList port_list = 3;
repeated xray.common.geodata.IPRule ip = 4; repeated xray.common.geodata.IPRule ip = 4;
Range delay = 5; Range delay = 5;
optional xray.common.log.Severity log_level = 6; optional xray.common.log.Severity log_level = 6;
Reply reply = 7;
} }
message Config { message Config {
reserved 6;
xray.transport.internet.DomainStrategy domain_strategy = 1; xray.transport.internet.DomainStrategy domain_strategy = 1;
DestinationOverride destination_override = 3; DestinationOverride destination_override = 3;
uint32 user_level = 4; uint32 user_level = 4;
Fragment fragment = 5; Fragment fragment = 5;
uint32 proxy_protocol = 6;
repeated Noise noises = 7; repeated Noise noises = 7;
repeated FinalRuleConfig final_rules = 8; repeated FirewallConfig firewall = 8;
} }
+83 -54
View File
@@ -1,14 +1,15 @@
package freedom package freedom
import ( import (
"bytes"
"context" "context"
"crypto/rand" "crypto/rand"
"io" "io"
"net/http"
"strings" "strings"
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/pires/go-proxyproto"
"github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/crypto" "github.com/xtls/xray-core/common/crypto"
@@ -35,10 +36,20 @@ import (
var ( var (
useSplice atomic.Bool useSplice atomic.Bool
allNetworks [8]bool allNetworks [8]bool
defaultBlockPrivateRule *FinalRule defaultBlockPrivateRule *Firewall
defaultBlockAllRule *FinalRule defaultBlockAllRule *Firewall
) )
var http403response = http.Response{
StatusCode: 403,
ProtoMajor: 1,
ProtoMinor: 1,
Header: http.Header{
"Connection": {"close"},
"Cache-Control": {"max-age=3600, public"},
},
}
func reloadEnvSettings() error { func reloadEnvSettings() error {
const defaultFlagValue = "NOT_DEFINED_AT_ALL" const defaultFlagValue = "NOT_DEFINED_AT_ALL"
value := platform.NewEnvFlag(platform.UseFreedomSplice).GetValue(func() string { return defaultFlagValue }) value := platform.NewEnvFlag(platform.UseFreedomSplice).GetValue(func() string { return defaultFlagValue })
@@ -72,45 +83,60 @@ func init() {
allNetworks[i] = true allNetworks[i] = true
} }
defaultBlockPrivateRule = &FinalRule{ defaultBlockPrivateRule = &Firewall{
action: RuleAction_Block, action: RuleAction_Block,
network: allNetworks, network: allNetworks,
ip: geodata.GetPrivateIPMatcher(), ip: geodata.GetPrivateIPMatcher(),
logLevel: log.Severity_Warning.Enum(), logLevel: log.Severity_Warning.Enum(),
} }
defaultBlockAllRule = &FinalRule{ defaultBlockAllRule = &Firewall{
action: RuleAction_Block, action: RuleAction_Block,
network: allNetworks, network: allNetworks,
logLevel: log.Severity_Warning.Enum(), logLevel: log.Severity_Warning.Enum(),
} }
} }
type FinalRule struct { type Firewall struct {
action RuleAction action RuleAction
network [8]bool network [8]bool
port net.MemoryPortList port net.MemoryPortList
ip geodata.IPMatcher ip geodata.IPMatcher
delay *Range delay *Range
logLevel *log.Severity logLevel *log.Severity
reply []byte
} }
// Handler handles Freedom connections. // Handler handles Freedom connections.
type Handler struct { type Handler struct {
policyManager policy.Manager policyManager policy.Manager
config *Config config *Config
finalRules []*FinalRule firewall []*Firewall
resolveStrategy internet.DomainStrategy resolveStrategy internet.DomainStrategy
usesDialerProxy bool usesDialerProxy bool
} }
func buildFinalRule(config *FinalRuleConfig) (*FinalRule, error) { func buildRule(config *FirewallConfig) (*Firewall, error) {
rule := &FinalRule{ rule := &Firewall{
action: config.GetAction(), action: config.GetAction(),
delay: config.GetDelay(), delay: config.GetDelay(),
logLevel: config.LogLevel, 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 { if len(config.Networks) == 0 {
rule.network = allNetworks rule.network = allNetworks
} else { } else {
@@ -134,25 +160,25 @@ func buildFinalRule(config *FinalRuleConfig) (*FinalRule, error) {
return rule, nil return rule, nil
} }
func (r *FinalRule) matchNetwork(network net.Network) bool { func (r *Firewall) matchNetwork(network net.Network) bool {
return r.network[int(network)] return r.network[int(network)]
} }
func (r *FinalRule) matchPort(port net.Port) bool { func (r *Firewall) matchPort(port net.Port) bool {
if len(r.port) == 0 { if len(r.port) == 0 {
return true return true
} }
return r.port.Contains(port) return r.port.Contains(port)
} }
func (r *FinalRule) matchIP(addr net.Address) bool { func (r *Firewall) matchIP(addr net.Address) bool {
if r.ip == nil { if r.ip == nil {
return true return true
} }
return addr != nil && addr.Family().IsIP() && r.ip.Match(addr.IP()) return addr != nil && addr.Family().IsIP() && r.ip.Match(addr.IP())
} }
func (r *FinalRule) Apply(network net.Network, address net.Address, port net.Port) bool { func (r *Firewall) Apply(network net.Network, address net.Address, port net.Port) bool {
if !r.matchNetwork(network) { if !r.matchNetwork(network) {
return false return false
} }
@@ -162,7 +188,7 @@ func (r *FinalRule) Apply(network net.Network, address net.Address, port net.Por
return r.matchIP(address) return r.matchIP(address)
} }
func getDefaultFinalRule(inbound *session.Inbound) *FinalRule { func getDefaultRule(inbound *session.Inbound) *Firewall {
if inbound == nil { if inbound == nil {
return nil return nil
} }
@@ -179,8 +205,8 @@ func getDefaultFinalRule(inbound *session.Inbound) *FinalRule {
return nil return nil
} }
func (h *Handler) matchFinalRule(network net.Network, address net.Address, port net.Port, defaultRule *FinalRule) *FinalRule { func (h *Handler) matchRule(network net.Network, address net.Address, port net.Port, defaultRule *Firewall) *Firewall {
for _, rule := range h.finalRules { for _, rule := range h.firewall {
if rule.Apply(network, address, port) { if rule.Apply(network, address, port) {
return rule return rule
} }
@@ -195,19 +221,19 @@ func (h *Handler) matchFinalRule(network net.Network, address net.Address, port
func (h *Handler) Init(config *Config, pm policy.Manager) error { func (h *Handler) Init(config *Config, pm policy.Manager) error {
h.config = config h.config = config
h.policyManager = pm h.policyManager = pm
if h.usesDialerProxy { // freedom is not the final outbound, final rules do not apply if h.usesDialerProxy { // freedom is not the final outbound, firewall does not apply
if len(config.FinalRules) > 0 { if len(config.Firewall) > 0 {
errors.LogWarning(context.Background(), `The "finalRules" setting is ignored when "sockopt.dialerProxy" is set, since freedom is not the final outbound.`) errors.LogWarning(context.Background(), `The "firewall" setting is ignored when "sockopt.dialerProxy" is set, since freedom is not the final outbound.`)
} }
return nil return nil
} }
h.finalRules = make([]*FinalRule, 0, len(config.FinalRules)) h.firewall = make([]*Firewall, 0, len(config.Firewall))
for _, rc := range config.FinalRules { for _, rc := range config.Firewall {
rule, err := buildFinalRule(rc) rule, err := buildRule(rc)
if err != nil { if err != nil {
return errors.New("failed to build final rule").Base(err) return errors.New("failed to build firewall rule").Base(err)
} }
h.finalRules = append(h.finalRules, rule) h.firewall = append(h.firewall, rule)
} }
return nil return nil
} }
@@ -217,7 +243,7 @@ func (h *Handler) policy() policy.Session {
return p return p
} }
func (r *FinalRule) blockDuration() time.Duration { func (r *Firewall) blockDuration() time.Duration {
min := uint64(30) min := uint64(30)
max := uint64(90) max := uint64(90)
if r.delay != nil { if r.delay != nil {
@@ -231,7 +257,7 @@ func (r *FinalRule) blockDuration() time.Duration {
return time.Duration(min+uint64(dice.Roll(int(span+1)))) * time.Second return time.Duration(min+uint64(dice.Roll(int(span+1)))) * time.Second
} }
func (r *FinalRule) log(ctx context.Context, msg ...interface{}) { func (r *Firewall) log(ctx context.Context, msg ...interface{}) {
level := log.Severity_Info level := log.Severity_Info
if r.logLevel != nil { if r.logLevel != nil {
level = *r.logLevel level = *r.logLevel
@@ -248,10 +274,17 @@ func (r *FinalRule) log(ctx context.Context, msg ...interface{}) {
} }
} }
func (h *Handler) blackhole(ctx context.Context, input buf.Reader, output buf.Writer, rule *FinalRule, dest *net.Destination) error { func (h *Handler) blackhole(ctx context.Context, input buf.Reader, output buf.Writer, rule *Firewall, dest *net.Destination) error {
delay := rule.blockDuration() delay := rule.blockDuration()
rule.log(ctx, "target blocked by a finalrule: ", *dest, ", blackholing connection for ", delay) rule.log(ctx, "target blocked by a firewall rule: ", *dest, ", blackholing connection for ", delay)
defer common.Close(output) 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{}) done := make(chan struct{})
go func() { // a DispatchLink inbound's reader ignores Interrupt, so don't wait for this copy go func() { // a DispatchLink inbound's reader ignores Interrupt, so don't wait for this copy
_ = buf.Copy(input, buf.Discard) _ = buf.Copy(input, buf.Discard)
@@ -285,10 +318,16 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
} }
ob.Name = "freedom" ob.Name = "freedom"
ob.CanSpliceCopy = 1 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) inbound := session.InboundFromContext(ctx)
var defaultRule *FinalRule var defaultRule *Firewall
if !h.usesDialerProxy { // freedom is not the final outbound, final rules do not apply (and the domain is not resolved) if !h.usesDialerProxy { // freedom is not the final outbound, firewall does not apply (and the domain is not resolved)
defaultRule = getDefaultFinalRule(inbound) defaultRule = getDefaultRule(inbound)
} }
destination := ob.Target destination := ob.Target
@@ -316,10 +355,10 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
var conn stat.Connection var conn stat.Connection
var blockedDest *net.Destination var blockedDest *net.Destination
var blockedRule *FinalRule var blockedRule *Firewall
err := retry.ExponentialBackoff(5, 100).On(func() error { err := retry.ExponentialBackoff(5, 100).On(func() error {
if destination.Address.Family().IsDomain() { if destination.Address.Family().IsDomain() {
if defaultRule != nil || len(h.finalRules) > 0 { if defaultRule != nil || len(h.firewall) > 0 {
if strategy := h.resolveStrategy; strategy.HasStrategy() { if strategy := h.resolveStrategy; strategy.HasStrategy() {
ips, err := internet.LookupForIP(destination.Address.Domain(), strategy, outGateway) ips, err := internet.LookupForIP(destination.Address.Domain(), strategy, outGateway)
if err != nil { // non-force may still dial with system DNS if err != nil { // non-force may still dial with system DNS
@@ -330,7 +369,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
} }
for _, ip := range ips { for _, ip := range ips {
if addr := net.IPAddress(ip); addr != nil { if addr := net.IPAddress(ip); addr != nil {
if rule := h.matchFinalRule(destination.Network, addr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block { if rule := h.matchRule(destination.Network, addr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
blockedDest = &destination blockedDest = &destination
blockedDest.Address = addr blockedDest.Address = addr
blockedRule = rule blockedRule = rule
@@ -345,7 +384,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
} }
for _, addr := range addrs { for _, addr := range addrs {
if ipAddr := net.IPAddress(addr.IP); ipAddr != nil { if ipAddr := net.IPAddress(addr.IP); ipAddr != nil {
if rule := h.matchFinalRule(destination.Network, ipAddr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block { if rule := h.matchRule(destination.Network, ipAddr, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
blockedDest = &destination blockedDest = &destination
blockedDest.Address = ipAddr blockedDest.Address = ipAddr
blockedRule = rule blockedRule = rule
@@ -356,7 +395,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
} }
} }
} else { } else {
if rule := h.matchFinalRule(destination.Network, destination.Address, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block { if rule := h.matchRule(destination.Network, destination.Address, destination.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
blockedDest = &destination blockedDest = &destination
blockedRule = rule blockedRule = rule
return nil return nil
@@ -377,25 +416,15 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
if blockedDest != nil { if blockedDest != nil {
return h.blackhole(ctx, input, output, blockedRule, blockedDest) return h.blackhole(ctx, input, output, blockedRule, blockedDest)
} }
if destination.Address.Family().IsDomain() && (defaultRule != nil || len(h.finalRules) > 0) { if destination.Address.Family().IsDomain() && (defaultRule != nil || len(h.firewall) > 0) {
// pre-check may fail or dialer may select another IP // pre-check may fail or dialer may select another IP
remoteDest := net.DestinationFromAddr(conn.RemoteAddr()) remoteDest := net.DestinationFromAddr(conn.RemoteAddr())
if rule := h.matchFinalRule(remoteDest.Network, remoteDest.Address, remoteDest.Port, defaultRule); rule != nil && rule.action == RuleAction_Block { if rule := h.matchRule(remoteDest.Network, remoteDest.Address, remoteDest.Port, defaultRule); rule != nil && rule.action == RuleAction_Block {
conn.Close() conn.Close()
return h.blackhole(ctx, input, output, rule, &remoteDest) 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() defer conn.Close()
errors.LogInfo(ctx, "connection opened to ", destination, ", local endpoint ", conn.LocalAddr(), ", remote endpoint ", conn.RemoteAddr()) errors.LogInfo(ctx, "connection opened to ", destination, ", local endpoint ", conn.LocalAddr(), ", remote endpoint ", conn.RemoteAddr())
@@ -484,7 +513,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
return nil return nil
} }
func NewPacketReader(conn net.Conn, h *Handler, defaultRule *FinalRule, UDPOverride net.Destination, DialDest net.Destination) buf.Reader { func NewPacketReader(conn net.Conn, h *Handler, defaultRule *Firewall, UDPOverride net.Destination, DialDest net.Destination) buf.Reader {
iConn := conn iConn := conn
statConn, ok := iConn.(*stat.CounterConnection) statConn, ok := iConn.(*stat.CounterConnection)
if ok { if ok {
@@ -517,7 +546,7 @@ type PacketReader struct {
*net.PacketConnWrapper *net.PacketConnWrapper
stats.Counter stats.Counter
Handler *Handler Handler *Handler
DefaultRule *FinalRule DefaultRule *Firewall
IsOverridden bool IsOverridden bool
InitUnchangedAddr net.Address InitUnchangedAddr net.Address
InitChangedAddr net.Address InitChangedAddr net.Address
@@ -534,7 +563,7 @@ func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
} }
udpAddr := d.(*net.UDPAddr) udpAddr := d.(*net.UDPAddr)
sourceAddr := net.IPAddress(udpAddr.IP) sourceAddr := net.IPAddress(udpAddr.IP)
if rule := r.Handler.matchFinalRule(net.Network_UDP, sourceAddr, net.Port(udpAddr.Port), r.DefaultRule); rule != nil && rule.action == RuleAction_Block { if rule := r.Handler.matchRule(net.Network_UDP, sourceAddr, net.Port(udpAddr.Port), r.DefaultRule); rule != nil && rule.action == RuleAction_Block {
continue continue
} }
b.Resize(0, int32(n)) b.Resize(0, int32(n))
@@ -559,7 +588,7 @@ func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
} }
// DialDest means the dial target used in the dialer when creating conn // DialDest means the dial target used in the dialer when creating conn
func NewPacketWriter(conn net.Conn, h *Handler, defaultRule *FinalRule, UDPOverride net.Destination, DialDest net.Destination, outGateway net.Address) buf.Writer { func NewPacketWriter(conn net.Conn, h *Handler, defaultRule *Firewall, UDPOverride net.Destination, DialDest net.Destination, outGateway net.Address) buf.Writer {
iConn := conn iConn := conn
statConn, ok := iConn.(*stat.CounterConnection) statConn, ok := iConn.(*stat.CounterConnection)
if ok { if ok {
@@ -593,7 +622,7 @@ type PacketWriter struct {
*net.PacketConnWrapper *net.PacketConnWrapper
stats.Counter stats.Counter
*Handler *Handler
DefaultRule *FinalRule DefaultRule *Firewall
UDPOverride net.Destination UDPOverride net.Destination
// Dest of udp packets might be a domain, we will resolve them to IP // Dest of udp packets might be a domain, we will resolve them to IP
@@ -652,7 +681,7 @@ func (w *PacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
} }
} }
} }
if rule := w.matchFinalRule(net.Network_UDP, b.UDP.Address, b.UDP.Port, w.DefaultRule); rule != nil && rule.action == RuleAction_Block { if rule := w.matchRule(net.Network_UDP, b.UDP.Address, b.UDP.Port, w.DefaultRule); rule != nil && rule.action == RuleAction_Block {
b.Release() b.Release()
continue continue
} }
+87
View File
@@ -0,0 +1,87 @@
package freedom
import (
"bufio"
"bytes"
"context"
"net/http"
"testing"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/transport"
)
func TestUnconditionalBlockFastPath(t *testing.T) {
for _, network := range []net.Network{net.Network_TCP, net.Network_UDP} {
t.Run(network.String(), func(t *testing.T) {
const reply = "blocked"
h := new(Handler)
if err := h.Init(&Config{Firewall: []*FirewallConfig{{
Action: RuleAction_Block,
Delay: &Range{},
Reply: &Reply{Type: "custom", CustomResponseData: []byte(reply)},
}}}, nil); err != nil {
t.Fatal(err)
}
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
Target: net.Destination{Network: network, Address: net.DomainAddress("blocked.invalid"), Port: 443},
}})
var output bytes.Buffer
link := &transport.Link{
Reader: buf.NewReader(bytes.NewReader(nil)),
Writer: &buf.BufferToBytesWriter{Writer: &output},
}
// An unconditional block must finish without touching the dialer or resolving the domain.
if err := h.Process(ctx, link, nil); err != nil {
t.Fatal(err)
}
if output.String() != reply {
t.Fatalf("reply = %q, want %q", output.String(), reply)
}
})
}
}
func TestFirewallReply(t *testing.T) {
custom := bytes.Repeat([]byte("custom response"), buf.Size)
for _, test := range []struct {
name string
reply *Reply
want []byte
}{
{name: "default"},
{name: "none", reply: &Reply{Type: "none"}},
{name: "http", reply: &Reply{Type: "http"}},
{name: "custom", reply: &Reply{Type: "custom", CustomResponseData: custom}, want: custom},
} {
t.Run(test.name, func(t *testing.T) {
rule, err := buildRule(&FirewallConfig{
Action: RuleAction_Block,
Delay: &Range{},
Reply: test.reply,
})
if err != nil {
t.Fatal(err)
}
var output bytes.Buffer
dest := net.TCPDestination(net.LocalHostIP, 80)
if err := new(Handler).blackhole(context.Background(), buf.NewReader(bytes.NewReader(nil)), &buf.BufferToBytesWriter{Writer: &output}, rule, &dest); err != nil {
t.Fatal(err)
}
if test.name == "http" {
response, err := http.ReadResponse(bufio.NewReader(&output), nil)
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusForbidden {
t.Fatalf("HTTP status = %d, want 403", response.StatusCode)
}
} else if !bytes.Equal(output.Bytes(), test.want) {
t.Fatalf("reply has %d bytes, want %d", output.Len(), len(test.want))
}
})
}
}
+1
View File
@@ -150,6 +150,7 @@ Start:
To: request.URL, To: request.URL,
Status: log.AccessAccepted, Status: log.AccessAccepted,
Reason: "", Reason: "",
Email: inbound.User.Email,
}) })
if strings.EqualFold(request.Method, "CONNECT") { if strings.EqualFold(request.Method, "CONNECT") {
+1 -3
View File
@@ -25,7 +25,6 @@ type Server struct {
config *ServerConfig config *ServerConfig
validator *Validator validator *Validator
policyManager policy.Manager policyManager policy.Manager
cone bool
} }
// NewServer create a new Shadowsocks server. // NewServer create a new Shadowsocks server.
@@ -47,7 +46,6 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
config: config, config: config,
validator: validator, validator: validator,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
} }
return s, nil return s, nil
@@ -185,7 +183,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
data.UDP = &destination data.UDP = &destination
if !s.cone || dest == nil { if dest == nil {
dest = &destination dest = &destination
} }
+3 -3
View File
@@ -29,7 +29,6 @@ import (
type Server struct { type Server struct {
config *ServerConfig config *ServerConfig
policyManager policy.Manager policyManager policy.Manager
cone bool
httpServer *http.Server httpServer *http.Server
} }
@@ -39,7 +38,6 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
s := &Server{ s := &Server{
config: config, config: config,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
} }
httpConfig := &http.ServerConfig{ httpConfig := &http.ServerConfig{
UserLevel: config.UserLevel, UserLevel: config.UserLevel,
@@ -149,6 +147,7 @@ func (s *Server) processTCP(ctx context.Context, conn stat.Connection, dispatche
To: dest, To: dest,
Status: log.AccessAccepted, Status: log.AccessAccepted,
Reason: "", Reason: "",
Email: inbound.User.Email,
}) })
} }
if inbound.CanSpliceCopy == 2 { if inbound.CanSpliceCopy == 2 {
@@ -270,12 +269,13 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
To: destination, To: destination,
Status: log.AccessAccepted, Status: log.AccessAccepted,
Reason: "", Reason: "",
Email: inbound.User.Email,
}) })
} }
payload.UDP = &destination payload.UDP = &destination
if !s.cone || dest == nil { if dest == nil {
dest = &destination dest = &destination
} }
+1 -3
View File
@@ -38,7 +38,6 @@ type Server struct {
policyManager policy.Manager policyManager policy.Manager
validator *Validator validator *Validator
fallbacks map[string]map[string]map[string]*Fallback // or nil fallbacks map[string]map[string]map[string]*Fallback // or nil
cone bool
} }
// NewServer creates a new trojan inbound handler. // NewServer creates a new trojan inbound handler.
@@ -59,7 +58,6 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
server := &Server{ server := &Server{
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
validator: validator, validator: validator,
cone: ctx.Value("cone").(bool),
} }
if config.Fallbacks != nil { if config.Fallbacks != nil {
@@ -302,7 +300,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, sessionPolicy policy.Sess
} }
errors.LogInfo(ctx, "tunnelling request to ", destination) errors.LogInfo(ctx, "tunnelling request to ", destination)
if !s.cone || dest == nil { if dest == nil {
dest = &destination dest = &destination
} }
+9 -1
View File
@@ -25,7 +25,10 @@ import (
// Handler is managing object that tie together tun interface, ip stack and dispatch connections to the routing // Handler is managing object that tie together tun interface, ip stack and dispatch connections to the routing
type Handler struct { 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 ctx context.Context
cancel context.CancelFunc
config *Config config *Config
stack Stack stack Stack
tun Tun tun Tun
@@ -96,7 +99,7 @@ func (t *Handler) Init(ctx context.Context, pm policy.Manager, dispatcher routin
t.sniffingRequest = content.SniffingRequest t.sniffingRequest = content.SniffingRequest
} }
t.ctx = core.ToBackgroundDetachedContext(ctx) t.ctx, t.cancel = context.WithCancel(core.ToBackgroundDetachedContext(ctx))
t.policyManager = pm t.policyManager = pm
t.dispatcher = dispatcher t.dispatcher = dispatcher
@@ -265,6 +268,11 @@ func (t *Handler) HandleConnection(conn net.Conn, destination net.Destination) {
// Close implements common.Closable. // Close implements common.Closable.
func (t *Handler) Close() error { 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)) return errors.Combine(common.CloseIfExists(t.stack), common.CloseIfExists(t.tun))
} }
+34
View File
@@ -179,3 +179,37 @@ func TestHandlerCountsTunConnectionTraffic(t *testing.T) {
t.Fatalf("connection write mismatch: got %q, want %q", got, "downlink") 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,6 +148,11 @@ func (s *stack) Close() error {
for _, u := range sockets { for _, u := range sockets {
u.queue.close() 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 return nil
} }
+1 -2
View File
@@ -17,7 +17,6 @@ import (
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/core" "github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/proxy/blackhole"
proxydns "github.com/xtls/xray-core/proxy/dns" proxydns "github.com/xtls/xray-core/proxy/dns"
"github.com/xtls/xray-core/proxy/freedom" "github.com/xtls/xray-core/proxy/freedom"
) )
@@ -73,7 +72,7 @@ func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.Na
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})}, {Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})}, {Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
{Tag: "block", ProxySettings: serial.ToTypedMessage(&blackhole.Config{})}, {Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
}, },
}) })
if err != nil { if err != nil {
+23
View File
@@ -16,6 +16,8 @@ type udpConnectionHandler struct {
sync.RWMutex sync.RWMutex
udpConns map[net.Destination]*udpConn 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) handleConnection func(conn net.Conn, dest net.Destination)
writePacket func(data []byte, src net.Destination, dst net.Destination) error writePacket func(data []byte, src net.Destination, dst net.Destination) error
@@ -51,6 +53,10 @@ func (u *udpConnectionHandler) HandlePacket(src net.Destination, dst net.Destina
u.Lock() u.Lock()
defer u.Unlock() defer u.Unlock()
if u.closed {
data.Release()
return
}
conn, found = u.udpConns[src] conn, found = u.udpConns[src]
if !found { if !found {
conn = &udpConn{handler: u, queue: newPacketQueue(udpQueueLimit), src: src, dst: dst} conn = &udpConn{handler: u, queue: newPacketQueue(udpQueueLimit), src: src, dst: dst}
@@ -66,6 +72,23 @@ 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) { func (u *udpConnectionHandler) connectionFinished(conn *udpConn) {
u.Lock() u.Lock()
// Close runs twice per flow; a newer conn may already own this src. // Close runs twice per flow; a newer conn may already own this src.
+36
View File
@@ -89,3 +89,39 @@ func TestPacketQueueDropsDrainedStorage(t *testing.T) {
t.Fatalf("drained queue still holds %d slots", cap(q.items)) 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)
}
}
+1 -3
View File
@@ -50,7 +50,6 @@ func init() {
type Handler struct { type Handler struct {
server *protocol.ServerSpec server *protocol.ServerSpec
policyManager policy.Manager policyManager policy.Manager
cone bool
encryption *encryption.ClientInstance encryption *encryption.ClientInstance
reverse *Reverse reverse *Reverse
@@ -78,7 +77,6 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
handler := &Handler{ handler := &Handler{
server: server, server: server,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
} }
a := handler.server.User.Account.(*vless.MemoryAccount) a := handler.server.User.Account.(*vless.MemoryAccount)
@@ -300,7 +298,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
clientReader := link.Reader // .(*pipe.Reader) clientReader := link.Reader // .(*pipe.Reader)
clientWriter := link.Writer // .(*pipe.Writer) clientWriter := link.Writer // .(*pipe.Writer)
trafficState := proxy.NewTrafficState(account.ID.Bytes()) trafficState := proxy.NewTrafficState(account.ID.Bytes())
if request.Command == protocol.RequestCommandUDP && (requestAddons.Flow == vless.XRV || (h.cone && request.Port != 53 && request.Port != 443)) { if request.Command == protocol.RequestCommandUDP && (requestAddons.Flow == vless.XRV || (request.Port != 53 && request.Port != 443)) {
request.Command = protocol.RequestCommandMux request.Command = protocol.RequestCommandMux
request.Address = net.DomainAddress("v1.mux.cool") request.Address = net.DomainAddress("v1.mux.cool")
request.Port = net.Port(666) request.Port = net.Port(666)
+17 -76
View File
@@ -14,8 +14,6 @@ import (
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol" "github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/session" "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/common/uuid"
"github.com/xtls/xray-core/core" "github.com/xtls/xray-core/core"
feature_inbound "github.com/xtls/xray-core/features/inbound" feature_inbound "github.com/xtls/xray-core/features/inbound"
@@ -23,6 +21,7 @@ import (
"github.com/xtls/xray-core/features/routing" "github.com/xtls/xray-core/features/routing"
"github.com/xtls/xray-core/proxy/vmess" "github.com/xtls/xray-core/proxy/vmess"
"github.com/xtls/xray-core/proxy/vmess/encoding" "github.com/xtls/xray-core/proxy/vmess/encoding"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/internet/stat" "github.com/xtls/xray-core/transport/internet/stat"
) )
@@ -185,44 +184,6 @@ func (h *Handler) RemoveUser(ctx context.Context, email string) error {
return nil 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(). // Process implements proxy.Inbound.Process().
func (h *Handler) Process(ctx context.Context, network net.Network, connection stat.Connection, dispatcher routing.Dispatcher) error { func (h *Handler) Process(ctx context.Context, network net.Network, connection stat.Connection, dispatcher routing.Dispatcher) error {
sessionPolicy := h.policyManager.ForLevel(0) sessionPolicy := h.policyManager.ForLevel(0)
@@ -273,49 +234,29 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
inbound.CanSpliceCopy = 3 inbound.CanSpliceCopy = 3
inbound.User = request.User inbound.User = request.User
sessionPolicy = h.policyManager.ForLevel(request.User.Level) bodyReader, err := svrSession.DecodeRequestBody(request, reader)
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 { if err != nil {
return errors.New("failed to dispatch request to ", request.Destination()).Base(err) return errors.New("failed to start decoding").Base(err)
} }
requestDone := func() error { writer := buf.NewBufferedWriter(buf.NewWriter(connection))
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) response := &protocol.ResponseHeader{
Command: h.generateCommand(ctx, request),
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
} }
svrSession.EncodeResponseHeader(response, writer)
responseDone := func() error { bodyWriter, err := svrSession.EncodeResponseBody(request, writer)
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) if err != nil {
return errors.New("failed to start decoding response").Base(err)
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)
} }
writer.SetFlushNext()
requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer)) if err := dispatcher.DispatchLink(ctx, request.Destination(), &transport.Link{
if err := task.Run(ctx, requestDonePost, responseDone); err != nil { Reader: bodyReader,
common.Interrupt(link.Reader) Writer: bodyWriter,
common.Interrupt(link.Writer) },
return errors.New("connection ends").Base(err) ); err != nil {
return errors.New("failed to dispatch request").Base(err)
} }
return nil return nil
} }
+1 -3
View File
@@ -32,7 +32,6 @@ import (
type Handler struct { type Handler struct {
server *protocol.ServerSpec server *protocol.ServerSpec
policyManager policy.Manager policyManager policy.Manager
cone bool
} }
// New creates a new VMess outbound handler. // New creates a new VMess outbound handler.
@@ -49,7 +48,6 @@ func New(ctx context.Context, config *Config) (*Handler, error) {
handler := &Handler{ handler := &Handler{
server: server, server: server,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
cone: ctx.Value("cone").(bool),
} }
return handler, nil return handler, nil
@@ -143,7 +141,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
} }
}, sessionPolicy.Timeouts.ConnectionIdle) }, sessionPolicy.Timeouts.ConnectionIdle)
if request.Command == protocol.RequestCommandUDP && h.cone && request.Port != 53 && request.Port != 443 { if request.Command == protocol.RequestCommandUDP && request.Port != 53 && request.Port != 443 {
request.Command = protocol.RequestCommandMux request.Command = protocol.RequestCommandMux
request.Address = net.DomainAddress("v1.mux.cool") request.Address = net.DomainAddress("v1.mux.cool")
request.Port = net.Port(666) request.Port = net.Port(666)
+5 -5
View File
@@ -71,7 +71,7 @@ func TestCommanderListenConfigurationItem(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
Tag: "default-outbound", Tag: "default-outbound",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
}, },
}, },
} }
@@ -166,7 +166,7 @@ func TestCommanderRemoveHandler(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
Tag: "default-outbound", Tag: "default-outbound",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
}, },
}, },
} }
@@ -262,7 +262,7 @@ func TestCommanderListHandlers(t *testing.T) {
{ {
Tag: "default-outbound", Tag: "default-outbound",
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{}), SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{}),
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
}, },
}, },
} }
@@ -390,7 +390,7 @@ func TestCommanderAddRemoveUser(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -579,7 +579,7 @@ func TestCommanderStats(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
+1 -2
View File
@@ -13,7 +13,6 @@ import (
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/core" "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/freedom"
"github.com/xtls/xray-core/proxy/socks" "github.com/xtls/xray-core/proxy/socks"
"github.com/xtls/xray-core/testing/servers/tcp" "github.com/xtls/xray-core/testing/servers/tcp"
@@ -78,7 +77,7 @@ func TestResolveIP(t *testing.T) {
}, },
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
}, },
{ {
Tag: "direct", Tag: "direct",
+2 -2
View File
@@ -60,7 +60,7 @@ func TestDokodemoTCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -163,7 +163,7 @@ func TestDokodemoUDP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
+10 -11
View File
@@ -21,7 +21,6 @@ import (
"github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/common/uuid" "github.com/xtls/xray-core/common/uuid"
core "github.com/xtls/xray-core/core" 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/dokodemo"
"github.com/xtls/xray-core/proxy/freedom" "github.com/xtls/xray-core/proxy/freedom"
v2http "github.com/xtls/xray-core/proxy/http" v2http "github.com/xtls/xray-core/proxy/http"
@@ -62,7 +61,7 @@ func TestPassiveConnection(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -123,7 +122,7 @@ func TestDialerProxy(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -152,7 +151,7 @@ func TestDialerProxy(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -254,7 +253,7 @@ func TestDialerProxyOverKCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -283,7 +282,7 @@ func TestDialerProxyOverKCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{ SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{ StreamSettings: &internet.StreamConfig{
@@ -402,11 +401,11 @@ func TestBlackhole(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
Tag: "direct", Tag: "direct",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
}, },
{ {
Tag: "blocked", Tag: "blocked",
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
}, },
}, },
App: []*serial.TypedMessage{ App: []*serial.TypedMessage{
@@ -517,7 +516,7 @@ func TestUDPConnection(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -582,7 +581,7 @@ func TestDomainSniffing(t *testing.T) {
}, },
{ {
Tag: "direct", Tag: "direct",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
}, },
}, },
App: []*serial.TypedMessage{ App: []*serial.TypedMessage{
@@ -669,7 +668,7 @@ func TestDialXray(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
+6 -6
View File
@@ -50,7 +50,7 @@ func TestHttpConformance(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -113,7 +113,7 @@ func TestHttpError(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -163,7 +163,7 @@ func TestHTTPConnectMethod(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -245,7 +245,7 @@ func TestHttpPost(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -317,7 +317,7 @@ func TestHttpBasicAuth(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -405,7 +405,7 @@ func TestHTTPOutboundServerFirst(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{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), Port: uint32(dest.Port),
}, },
}, },
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
} }
} }
+1 -1
View File
@@ -63,7 +63,7 @@ func TestMetrics(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
Tag: "default-outbound", Tag: "default-outbound",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
}, },
}, },
} }
+2 -2
View File
@@ -85,7 +85,7 @@ func TestVMessClosing(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -193,7 +193,7 @@ func TestZeroBuffer(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
+4 -5
View File
@@ -17,7 +17,6 @@ import (
"github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/common/uuid" "github.com/xtls/xray-core/common/uuid"
core "github.com/xtls/xray-core/core" 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/dokodemo"
"github.com/xtls/xray-core/proxy/freedom" "github.com/xtls/xray-core/proxy/freedom"
"github.com/xtls/xray-core/proxy/vmess" "github.com/xtls/xray-core/proxy/vmess"
@@ -100,7 +99,7 @@ func TestReverseProxy(t *testing.T) {
}, },
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
}, },
}, },
} }
@@ -151,7 +150,7 @@ func TestReverseProxy(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
Tag: "freedom", Tag: "freedom",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
}, },
{ {
Tag: "reverse", Tag: "reverse",
@@ -275,7 +274,7 @@ func TestReverseProxyLongRunning(t *testing.T) {
}, },
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
}, },
}, },
} }
@@ -340,7 +339,7 @@ func TestReverseProxyLongRunning(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
Tag: "freedom", Tag: "freedom",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
}, },
{ {
Tag: "reverse", Tag: "reverse",
+2 -2
View File
@@ -91,7 +91,7 @@ func testShadowsocks2022Tcp(t *testing.T, method string, password string) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -176,7 +176,7 @@ func testShadowsocks2022Udp(t *testing.T, method string, password string) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
+4 -4
View File
@@ -53,7 +53,7 @@ func TestShadowsocksChaCha20Poly1305TCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -141,7 +141,7 @@ func TestShadowsocksAES256GCMTCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -236,7 +236,7 @@ func TestShadowsocksAES128GCMUDP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -330,7 +330,7 @@ func TestShadowsocksAES128GCMUDPMux(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
+6 -7
View File
@@ -11,7 +11,6 @@ import (
"github.com/xtls/xray-core/common/protocol" "github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/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/dokodemo"
"github.com/xtls/xray-core/proxy/freedom" "github.com/xtls/xray-core/proxy/freedom"
"github.com/xtls/xray-core/proxy/http" "github.com/xtls/xray-core/proxy/http"
@@ -51,7 +50,7 @@ func TestSocksBridgeTCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -128,7 +127,7 @@ func TestSocksWithHttpRequest(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -217,7 +216,7 @@ func TestSocksBridageUDP(t *testing.T) {
}, },
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
}, },
}, },
} }
@@ -331,11 +330,11 @@ func TestSocksBridageUDPWithRouting(t *testing.T) {
}, },
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}}),
}, },
{ {
Tag: "out", Tag: "out",
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}), ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}}}),
}, },
}, },
} }
@@ -435,7 +434,7 @@ func TestSocksConformanceMod(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
+10 -10
View File
@@ -69,7 +69,7 @@ func TestSimpleTLSConnection(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -182,7 +182,7 @@ func TestAutoIssuingCertificate(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -287,7 +287,7 @@ func TestTLSOverKCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -387,7 +387,7 @@ func TestTLSOverWebSocket(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -503,7 +503,7 @@ func TestGRPC(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -619,7 +619,7 @@ func TestGRPCMultiMode(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -728,7 +728,7 @@ func TestSimpleTLSConnectionPinned(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -827,7 +827,7 @@ func TestSimpleTLSConnectionPinnedWrongCert(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -925,7 +925,7 @@ func TestUTLSConnectionPinned(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -1025,7 +1025,7 @@ func TestUTLSConnectionPinnedWrongCert(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
+1 -1
View File
@@ -63,7 +63,7 @@ func TestHTTPConnectionHeader(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
+8 -8
View File
@@ -70,7 +70,7 @@ func TestVless(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -175,7 +175,7 @@ func TestVlessTls(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -298,7 +298,7 @@ func TestVlessXtlsVision(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -430,7 +430,7 @@ func TestVlessXtlsVisionReality(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -569,7 +569,7 @@ func TestVlessRealityFingerprints(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -661,7 +661,7 @@ func TestVlessRealityFingerprints(t *testing.T) {
wg.Wait() wg.Wait()
} }
// A blocked connection must close after finalRules.delay even while the client keeps it open and sends nothing. // A blocked connection must close after firewall.delay even while the client keeps it open and sends nothing.
func TestVlessBlockDelay(t *testing.T) { func TestVlessBlockDelay(t *testing.T) {
tcpServer := tcp.Server{ tcpServer := tcp.Server{
MsgProcessor: xor, MsgProcessor: xor,
@@ -695,7 +695,7 @@ func TestVlessBlockDelay(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{ Firewall: []*freedom.FirewallConfig{
{ {
Action: freedom.RuleAction_Block, Action: freedom.RuleAction_Block,
Delay: &freedom.Range{Min: delay, Max: delay}, 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) t.Fatalf("connection is still open after %v", elapsed)
} }
if elapsed < blockDuration { if elapsed < blockDuration {
t.Fatalf("connection is closed after %v, before finalRules.delay", elapsed) t.Fatalf("connection is closed after %v, before firewall.delay", elapsed)
} }
}) })
} }
+10 -10
View File
@@ -62,7 +62,7 @@ func TestVMessGCM(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -162,7 +162,7 @@ func TestVMessGCMReadv(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -265,7 +265,7 @@ func TestVMessGCMUDP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -362,7 +362,7 @@ func TestVMessChacha20(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -463,7 +463,7 @@ func TestVMessKCP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -568,7 +568,7 @@ func TestVMessKCPLarge(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -674,7 +674,7 @@ func TestVMessGCMMux(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -787,7 +787,7 @@ func TestVMessGCMMuxUDP(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -910,7 +910,7 @@ func TestVMessGCMLengthAuth(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
@@ -1012,7 +1012,7 @@ func TestVMessGCMLengthAuthPlusNoTerminationSignal(t *testing.T) {
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ {
ProxySettings: serial.ToTypedMessage(&freedom.Config{ ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
}, },
}, },
+1 -1
View File
@@ -61,7 +61,7 @@ func TestWireguard(t *testing.T) {
Port: uint32(dest.Port), Port: uint32(dest.Port),
}, },
}, },
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
}), }),
} }
} }
@@ -9,9 +9,11 @@ import (
"github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/session"
) )
type Dialer struct { type Dialer struct {
Source net.Addr
DialTCP func(net.Destination) (net.Conn, error) DialTCP func(net.Destination) (net.Conn, error)
DialUDP func(net.Destination) (net.Conn, error) DialUDP func(net.Destination) (net.Conn, error)
} }
@@ -85,6 +87,9 @@ func (fm *FinalMask) DialTCP(ctx context.Context, dest net.Destination) (net.Con
return &net.PacketConnWrapper{PacketConn: conn, Dest: addr}, err 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 { for i := range fm.tcpMasks {
var newConn net.Conn var newConn net.Conn
newConn, err = fm.tcpMasks[i].WrapConnClient(conn, &dest, dialer) newConn, err = fm.tcpMasks[i].WrapConnClient(conn, &dest, dialer)
@@ -0,0 +1,31 @@
package proxyprotocol
import (
"github.com/pires/go-proxyproto"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/transport/internet/finalmask"
)
func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *finalmask.Dialer) (net.Conn, error) {
version := c.Version
if version == 0 {
version = 2
}
if version != 1 && version != 2 {
return nil, errors.New("PROXY protocol version must be 1 or 2")
}
source := conn.LocalAddr()
if dialer != nil && dialer.Source != nil {
source = dialer.Source
}
header := proxyproto.HeaderProxyFromAddrs(byte(version), source, conn.RemoteAddr())
if _, err := header.WriteTo(conn); err != nil {
return nil, errors.New("failed to write PROXY protocol header").Base(err)
}
return conn, nil
}
func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
return proxyproto.NewConn(conn, proxyproto.WithPolicy(proxyproto.REQUIRE)), nil
}
@@ -0,0 +1,123 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.12
// protoc (unknown)
// source: transport/internet/finalmask/proxyprotocol/config.proto
package proxyprotocol
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
Version uint32 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_transport_internet_finalmask_proxyprotocol_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_transport_internet_finalmask_proxyprotocol_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescGZIP(), []int{0}
}
func (x *Config) GetVersion() uint32 {
if x != nil {
return x.Version
}
return 0
}
var File_transport_internet_finalmask_proxyprotocol_config_proto protoreflect.FileDescriptor
const file_transport_internet_finalmask_proxyprotocol_config_proto_rawDesc = "" +
"\n" +
"7transport/internet/finalmask/proxyprotocol/config.proto\x12/xray.transport.internet.finalmask.proxyprotocol\"\"\n" +
"\x06Config\x12\x18\n" +
"\aversion\x18\x01 \x01(\rR\aversionB\xaf\x01\n" +
"3com.xray.transport.internet.finalmask.proxyprotocolP\x01ZDgithub.com/xtls/xray-core/transport/internet/finalmask/proxyprotocol\xaa\x02/Xray.Transport.Internet.Finalmask.ProxyProtocolb\x06proto3"
var (
file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescOnce sync.Once
file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescData []byte
)
func file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescGZIP() []byte {
file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescOnce.Do(func() {
file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_transport_internet_finalmask_proxyprotocol_config_proto_rawDesc), len(file_transport_internet_finalmask_proxyprotocol_config_proto_rawDesc)))
})
return file_transport_internet_finalmask_proxyprotocol_config_proto_rawDescData
}
var file_transport_internet_finalmask_proxyprotocol_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_transport_internet_finalmask_proxyprotocol_config_proto_goTypes = []any{
(*Config)(nil), // 0: xray.transport.internet.finalmask.proxyprotocol.Config
}
var file_transport_internet_finalmask_proxyprotocol_config_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_transport_internet_finalmask_proxyprotocol_config_proto_init() }
func file_transport_internet_finalmask_proxyprotocol_config_proto_init() {
if File_transport_internet_finalmask_proxyprotocol_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_transport_internet_finalmask_proxyprotocol_config_proto_rawDesc), len(file_transport_internet_finalmask_proxyprotocol_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_transport_internet_finalmask_proxyprotocol_config_proto_goTypes,
DependencyIndexes: file_transport_internet_finalmask_proxyprotocol_config_proto_depIdxs,
MessageInfos: file_transport_internet_finalmask_proxyprotocol_config_proto_msgTypes,
}.Build()
File_transport_internet_finalmask_proxyprotocol_config_proto = out.File
file_transport_internet_finalmask_proxyprotocol_config_proto_goTypes = nil
file_transport_internet_finalmask_proxyprotocol_config_proto_depIdxs = nil
}
@@ -0,0 +1,11 @@
syntax = "proto3";
package xray.transport.internet.finalmask.proxyprotocol;
option csharp_namespace = "Xray.Transport.Internet.Finalmask.ProxyProtocol";
option go_package = "github.com/xtls/xray-core/transport/internet/finalmask/proxyprotocol";
option java_package = "com.xray.transport.internet.finalmask.proxyprotocol";
option java_multiple_files = true;
message Config {
uint32 version = 1;
}
@@ -0,0 +1,93 @@
package proxyprotocol
import (
"context"
"fmt"
"io"
"testing"
"time"
"github.com/pires/go-proxyproto"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/transport/internet/finalmask"
)
func TestClientHeader(t *testing.T) {
for _, version := range []uint32{0, 1, 2} {
for _, sourceIP := range []string{"", "198.51.100.7", "2001:db8::7"} {
t.Run(fmt.Sprintf("version=%d/source=%s", version, sourceIP), func(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
ctx := context.Background()
if sourceIP != "" {
ctx = session.ContextWithInbound(ctx, &session.Inbound{
Source: net.TCPDestination(net.ParseAddress(sourceIP), 12345),
})
}
fm := finalmask.NewFinalMask([]finalmask.TCPMask{&Config{Version: version}}, nil,
func(ctx context.Context, dest net.Destination) (net.Conn, error) {
return net.Dial("tcp", dest.NetAddr())
}, func(ctx context.Context, addr net.Addr) (net.Listener, error) {
return listener, nil
}, nil, nil)
maskedListener, err := fm.Listen(context.Background(), listener.Addr())
if err != nil {
t.Fatal(err)
}
client, err := fm.DialTCP(ctx, net.DestinationFromAddr(listener.Addr()))
if err != nil {
t.Fatal(err)
}
defer client.Close()
server, err := maskedListener.Accept()
if err != nil {
t.Fatal(err)
}
defer server.Close()
deadline := time.Now().Add(5 * time.Second)
if err := client.SetDeadline(deadline); err != nil {
t.Fatal(err)
}
if err := server.SetDeadline(deadline); err != nil {
t.Fatal(err)
}
proxyConn, ok := server.(*proxyproto.Conn)
if !ok {
t.Fatalf("server connection type = %T, want *proxyproto.Conn", server)
}
header := proxyConn.ProxyHeader()
wantVersion := byte(version)
if wantVersion == 0 {
wantVersion = 2
}
if header == nil || header.Version != wantVersion || header.Command != proxyproto.PROXY {
t.Fatalf("unexpected PROXY header: %v", header)
}
wantSource := client.LocalAddr()
if sourceIP != "" {
wantSource = &net.TCPAddr{IP: net.ParseIP(sourceIP), Port: 12345}
}
if server.RemoteAddr().String() != wantSource.String() || server.LocalAddr().String() != listener.Addr().String() {
t.Fatalf("addresses = %v -> %v, want %v -> %v", server.RemoteAddr(), server.LocalAddr(), wantSource, listener.Addr())
}
for _, pair := range [][2]net.Conn{{client, server}, {client, server}, {server, client}} {
const payload = "application payload"
if _, err := io.WriteString(pair[0], payload); err != nil {
t.Fatal(err)
}
data := make([]byte, len(payload))
if _, err := io.ReadFull(pair[1], data); err != nil {
t.Fatal(err)
}
if string(data) != payload {
t.Fatalf("payload = %q", data)
}
}
})
}
}
}
@@ -279,7 +279,7 @@ func runVLESSRealityCase(t *testing.T, bin string, mode trafficMode, payloadSize
}, },
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ProxySettings: serial.ToTypedMessage(&freedom.Config{ {ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
})}, })},
}, },
}) })
@@ -398,7 +398,7 @@ func runHysteria2Case(t *testing.T, bin string, mode trafficMode, payloadSize in
}, },
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ProxySettings: serial.ToTypedMessage(&freedom.Config{ {ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
})}, })},
}, },
}) })
@@ -514,7 +514,7 @@ func runVLesseEncCase(t *testing.T, bin string, mode trafficMode, payloadSize in
}, },
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ProxySettings: serial.ToTypedMessage(&freedom.Config{ {ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
})}, })},
}, },
}) })
@@ -614,7 +614,7 @@ func runVLESSXHTTPCase(t *testing.T, bin string, mode trafficMode, payloadSize i
}, },
Outbound: []*core.OutboundHandlerConfig{ Outbound: []*core.OutboundHandlerConfig{
{ProxySettings: serial.ToTypedMessage(&freedom.Config{ {ProxySettings: serial.ToTypedMessage(&freedom.Config{
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}, Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Allow}},
})}, })},
}, },
}) })
+34 -5
View File
@@ -32,6 +32,9 @@ type clientConn struct {
paddingSchedule []paddingTurn paddingSchedule []paddingTurn
packet *packetStream packet *packetStream
deadlines *connectionDeadlines deadlines *connectionDeadlines
done chan struct{}
closeOnce sync.Once
} }
type clientState int type clientState int
@@ -41,16 +44,15 @@ var (
clientStateProxy clientState = 2 clientStateProxy clientState = 2
) )
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string) (*clientConn, error) { func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn) (*clientConn, error) {
if len(rsaPublicKey) == 0 { if len(rsaPublicKey) == 0 {
return nil, fmt.Errorf("empty rsa public key") return nil, fmt.Errorf("empty rsa public key")
} }
if len(profiles) == 0 { if len(profiles) == 0 {
return nil, fmt.Errorf("empty profiles") return nil, fmt.Errorf("empty profiles")
} }
paddingSchedule, err := newClientPaddingSchedule2612() if len(password) > MaxLegacyPasswordLength {
if err != nil { return nil, fmt.Errorf("password is longer than %d bytes", MaxLegacyPasswordLength)
return nil, fmt.Errorf("select padding profile: %w", err)
} }
return &clientConn{ return &clientConn{
reader: bufio.NewReader(c), reader: bufio.NewReader(c),
@@ -64,9 +66,15 @@ func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPubl
hostname: hostname, hostname: hostname,
paddingSchedule: paddingSchedule, paddingSchedule: paddingSchedule,
deadlines: newConnectionDeadlines(c), deadlines: newConnectionDeadlines(c),
done: make(chan struct{}),
}, nil }, 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 { func (c *clientConn) handshake() error {
c.handshakeLock.Lock() c.handshakeLock.Lock()
defer c.handshakeLock.Unlock() defer c.handshakeLock.Unlock()
@@ -195,6 +203,24 @@ func (c *clientConn) handshake() error {
if err != nil { if err != nil {
return fmt.Errorf("read login finished: %w", err) 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.
if pkt.packetID == 0x03 {
var threshold Varint
if thresholdErr := pkt.readFields(&threshold); thresholdErr != nil {
return fmt.Errorf("read login compression threshold: %w", thresholdErr)
}
if threshold >= 0 {
c.reader = newCompressionReader(c.reader)
c.writer = newCompressionWriter(c.writer)
}
pkt, err = readPacket(c.reader)
if err != nil {
return fmt.Errorf("read login finished: %w", err)
}
}
if pkt.packetID == 0x00 { if pkt.packetID == 0x00 {
var reason String var reason String
if readErr := pkt.readFields(&reason); readErr != nil { if readErr := pkt.readFields(&reason); readErr != nil {
@@ -217,7 +243,9 @@ func (c *clientConn) handshake() error {
if err != nil { if err != nil {
return fmt.Errorf("write login acknowledged: %w", err) return fmt.Errorf("write login acknowledged: %w", err)
} }
if err = runPaddingSchedule(c.reader, c.writer, true, loginAcknowledgedLength, c.paddingSchedule); err != nil { 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.
return fmt.Errorf("run startup padding: %w", err) return fmt.Errorf("run startup padding: %w", err)
} }
@@ -260,6 +288,7 @@ func (c *clientConn) Close() error {
c.closed = true c.closed = true
packet := c.packet packet := c.packet
c.lifecycleMu.Unlock() c.lifecycleMu.Unlock()
c.closeOnce.Do(func() { close(c.done) })
if packet != nil { if packet != nil {
packet.Stop() packet.Stop()
} }
@@ -0,0 +1,180 @@
// 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 (
"bytes"
"compress/zlib"
"fmt"
"io"
)
const (
// Packet Length is a VarInt, so one frame cannot exceed 2^21-1 bytes.
maxCompressedFrameLength = (1 << 21) - 1
// Vanilla caps serverbound uncompressed packet bodies at 2^23 bytes.
maxUncompressedFrameBody = 1 << 23
)
// compressionReader converts the post-Set Compression framing
// (Packet Length, Data Length, optional zlib body) back into the plain
// (VarInt body length, body) frame that readPacket expects.
//
// A zero Data Length means the body was sent uncompressed, which vanilla
// servers accept even when the body exceeds the negotiated threshold.
type compressionReader struct {
r io.Reader
frame bytes.Buffer
}
func newCompressionReader(r io.Reader) io.Reader {
return &compressionReader{r: r}
}
func (c *compressionReader) Read(p []byte) (int, error) {
if c.frame.Len() == 0 {
if err := c.readFrame(); err != nil {
return 0, err
}
}
return c.frame.Read(p)
}
func (c *compressionReader) readFrame() error {
packetLength, _, err := readVarintWithLength(c.r)
if err != nil {
return fmt.Errorf("read compressed packet length: %w", err)
}
if packetLength < 1 || int(packetLength) > maxCompressedFrameLength {
return fmt.Errorf("read compressed packet: bad length: %d", packetLength)
}
dataLength, dataLengthSize, err := readVarintWithLength(c.r)
if err != nil {
return fmt.Errorf("read compressed data length: %w", err)
}
if dataLength < 0 || int(dataLength) > maxUncompressedFrameBody {
return fmt.Errorf("read compressed packet: bad uncompressed length: %d", dataLength)
}
payloadLength := int(packetLength) - dataLengthSize
if payloadLength < 0 {
return fmt.Errorf("read compressed packet: bad length: %d", packetLength)
}
payload := make([]byte, payloadLength)
if _, err := io.ReadFull(c.r, payload); err != nil {
return fmt.Errorf("read compressed packet data: %w", err)
}
body := payload
if dataLength > 0 {
zr, err := zlib.NewReader(bytes.NewReader(payload))
if err != nil {
return fmt.Errorf("open compressed packet: %w", err)
}
body = make([]byte, int(dataLength))
_, readErr := io.ReadFull(zr, body)
closeErr := zr.Close()
if readErr != nil {
return fmt.Errorf("decompress packet: %w", readErr)
}
if closeErr != nil {
return fmt.Errorf("close decompressor: %w", closeErr)
}
}
if len(body) < 1 {
return fmt.Errorf("read compressed packet: empty body")
}
var frame bytes.Buffer
frame.Grow(varintSize(Varint(len(body))) + len(body))
bodyLength := Varint(len(body))
if err := bodyLength.writeTo(&frame); err != nil {
return err
}
frame.Write(body)
c.frame = frame
return nil
}
// 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
}
func newCompressionWriter(w io.Writer) io.Writer {
return &compressionWriter{w: w}
}
func (c *compressionWriter) Write(p []byte) (int, error) {
c.pending = append(c.pending, p...)
for {
body, ok, err := c.nextFrame()
if err != nil {
return 0, err
}
if !ok {
return len(p), nil
}
if err := c.writeFrame(body); err != nil {
return 0, err
}
}
}
// nextFrame returns one complete frame body from the pending bytes. It only
// waits for more bytes while the length prefix or the body is still
// incomplete; a complete but invalid prefix is an error.
func (c *compressionWriter) nextFrame() ([]byte, bool, error) {
limit := len(c.pending)
if limit > 5 {
limit = 5
}
bodyLength, prefixLength, err := readVarintWithLength(bytes.NewReader(c.pending[:limit]))
if err != nil {
if len(c.pending) < 5 {
return nil, false, nil
}
return nil, false, fmt.Errorf("read frame length: %w", err)
}
if bodyLength < 1 {
return nil, false, fmt.Errorf("read frame: bad length: %d", bodyLength)
}
end := prefixLength + int(bodyLength)
if end > len(c.pending) {
return nil, false, nil
}
// The body stays valid after the reslice: appends only write past the
// remaining pending length and writeFrame consumes it immediately.
body := c.pending[prefixLength:end]
c.pending = c.pending[end:]
return body, true, nil
}
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)
var frame bytes.Buffer
frame.Grow(varintSize(Varint(packetLength)) + packetLength)
packetLengthVarint := Varint(packetLength)
if err := packetLengthVarint.writeTo(&frame); err != nil {
return err
}
frame.WriteByte(0)
frame.Write(body)
return writeFull(c.w, frame.Bytes())
}
@@ -0,0 +1,253 @@
package xmc
import (
"bytes"
"compress/zlib"
"crypto/rand"
"errors"
"io"
"testing"
)
func plainFrame(body []byte) []byte {
frame := make([]byte, 0, 5+len(body))
length := Varint(len(body))
var buf bytes.Buffer
_ = length.writeTo(&buf)
frame = append(frame, buf.Bytes()...)
return append(frame, body...)
}
type wireFrame struct {
packetLength int
dataLength int
payload []byte
}
func readWireFrame(t *testing.T, r *bytes.Reader) wireFrame {
t.Helper()
packetLength, _, err := readVarintWithLength(r)
if err != nil {
t.Fatalf("read packet length: %v", err)
}
dataLength, dataLengthSize, err := readVarintWithLength(r)
if err != nil {
t.Fatalf("read data length: %v", err)
}
payload := make([]byte, int(packetLength)-dataLengthSize)
if _, err := io.ReadFull(r, payload); err != nil {
t.Fatalf("read payload: %v", err)
}
return wireFrame{packetLength: int(packetLength), dataLength: int(dataLength), payload: payload}
}
func randomBody(t *testing.T, size int) []byte {
t.Helper()
body := make([]byte, size)
if _, err := rand.Read(body); err != nil {
t.Fatalf("random body: %v", err)
}
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)} {
var wire bytes.Buffer
w := newCompressionWriter(&wire)
if _, err := w.Write(plainFrame(body)); err != nil {
t.Fatalf("size %d: write: %v", 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)
}
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)
}
decoded, _, err := readFrame(newCompressionReader(bytes.NewReader(wire.Bytes())), maxUncompressedFrameBody)
if err != nil {
t.Fatalf("size %d: decode: %v", size, err)
}
if !bytes.Equal(decoded, body) {
t.Fatalf("size %d: round trip mismatch", size)
}
}
}
}
func TestCompressionRoundTripChunked(t *testing.T) {
cases := [][]byte{
[]byte("hello"),
randomBody(t, 255),
randomBody(t, 24*1024),
randomBody(t, 64*1024),
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)
}
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)
}
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("expected EOF after the last frame, got %v", err)
}
}
func TestCompressionMultipleFramesOneWrite(t *testing.T) {
var plain []byte
bodies := [][]byte{[]byte("a"), randomBody(t, 1024), randomBody(t, 300)}
for _, body := range bodies {
plain = append(plain, plainFrame(body)...)
}
var wire bytes.Buffer
w := newCompressionWriter(&wire)
if _, err := w.Write(plain); err != nil {
t.Fatalf("write: %v", err)
}
r := newCompressionReader(bytes.NewReader(wire.Bytes()))
for i, want := range bodies {
got, _, err := readFrame(r, maxUncompressedFrameBody)
if err != nil {
t.Fatalf("frame %d: decode: %v", i, err)
}
if !bytes.Equal(got, want) {
t.Fatalf("frame %d: mismatch", i)
}
}
}
// Vanilla servers accept uncompressed packets even when the body exceeds the
// negotiated threshold, which is what lets padding frames keep their wire size.
func TestCompressionReaderUncompressedOverThreshold(t *testing.T) {
body := randomBody(t, 64*1024)
var wire bytes.Buffer
length := Varint(1 + len(body))
if err := length.writeTo(&wire); err != nil {
t.Fatal(err)
}
wire.WriteByte(0)
wire.Write(body)
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")
}
}
// 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
length := Varint(1 + 10)
_ = length.writeTo(&badZlib)
dataLength := Varint(64)
_ = dataLength.writeTo(&badZlib)
badZlib.Write(bytes.Repeat([]byte{0xff}, 10))
if _, _, err := readFrame(newCompressionReader(bytes.NewReader(badZlib.Bytes())), maxUncompressedFrameBody); err == nil {
t.Fatal("expected an error for an invalid zlib body")
}
// Uncompressed length beyond the vanilla limit.
var tooLong bytes.Buffer
length = Varint(1 + 4)
_ = length.writeTo(&tooLong)
dataLength = Varint(maxUncompressedFrameBody + 1)
_ = dataLength.writeTo(&tooLong)
tooLong.Write([]byte{1, 2, 3, 4})
if _, _, err := readFrame(newCompressionReader(bytes.NewReader(tooLong.Bytes())), maxUncompressedFrameBody); err == nil {
t.Fatal("expected an error for an oversized uncompressed length")
}
// Truncated payload.
var truncated bytes.Buffer
length = Varint(1 + 100)
_ = length.writeTo(&truncated)
var zero Varint
_ = zero.writeTo(&truncated)
truncated.Write([]byte{1, 2, 3})
if _, _, err := readFrame(newCompressionReader(bytes.NewReader(truncated.Bytes())), maxUncompressedFrameBody); err == nil {
t.Fatal("expected an error for a truncated payload")
}
}
func TestCompressionWriterInvalidFrameLength(t *testing.T) {
var wire bytes.Buffer
w := newCompressionWriter(&wire)
if _, err := w.Write([]byte{0xff, 0xff, 0xff, 0xff, 0xff}); err == nil {
t.Fatal("expected an error for an invalid frame length prefix")
}
}
+113 -2
View File
@@ -2,17 +2,32 @@ package xmc
import ( import (
"fmt" "fmt"
"math"
"time"
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/transport/internet/finalmask" "github.com/xtls/xray-core/transport/internet/finalmask"
) )
// maxPaddingDelayMilliseconds keeps the millisecond value convertible to a
// time.Duration on every platform.
const maxPaddingDelayMilliseconds = int64(math.MaxInt64 / int64(time.Millisecond))
// MaxLegacyPasswordLength is the longest pre-shared password the login can
// carry. The verify token (4 random bytes) and the password travel together in
// one RSA-1024 PKCS#1 v1.5 block, which holds at most 128-11 bytes.
const MaxLegacyPasswordLength = 128 - 11 - 4
func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *finalmask.Dialer) (net.Conn, error) { func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *finalmask.Dialer) (net.Conn, error) {
profiles, err := profilesFromConfig(c.Profiles) profiles, err := profilesFromConfig(c.Profiles)
if err != nil { if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err) return nil, fmt.Errorf("minecraft finalmask: %w", err)
} }
cc, err := newClientConn(conn, profiles, c.Password, c.RsaPublicKey, c.Hostname) 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)
if err != nil { if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err) return nil, fmt.Errorf("minecraft finalmask: %w", err)
} }
@@ -25,10 +40,106 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err) return nil, fmt.Errorf("minecraft finalmask: %w", err)
} }
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey) 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)
if err != nil { if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err) return nil, fmt.Errorf("minecraft finalmask: %w", err)
} }
return cc, nil return cc, nil
} }
// ValidatePadding checks the configured startup turns (including their bounds)
// 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 {
return nil, fmt.Errorf("invalid padding length range at turn %d", i)
}
if turn.DelayMin < 0 || turn.DelayMax < turn.DelayMin {
return nil, fmt.Errorf("invalid padding delay range %d-%d at turn %d (must be non-negative and ordered)", turn.DelayMin, turn.DelayMax, i)
}
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:
direction = paddingClientToServer
case 2:
direction = paddingServerToClient
default:
return nil, fmt.Errorf("invalid padding direction %d at turn %d (1=client-to-server, 2=server-to-client)", turn.Direction, i)
}
schedule[i] = paddingTurn{
direction: direction,
minLength: int(turn.LengthMin),
maxLength: int(turn.LengthMax),
delay: paddingDelayRange{
min: time.Duration(turn.DelayMin) * time.Millisecond,
max: time.Duration(turn.DelayMax) * time.Millisecond,
},
}
}
// The first turn includes the two-byte Login Acknowledged packet.
if err := validatePaddingSchedule(schedule, 2); err != nil {
return nil, err
}
return schedule, nil
}
+128 -9
View File
@@ -99,6 +99,13 @@ type Config struct {
RsaPublicKey []byte `protobuf:"bytes,9,opt,name=rsa_public_key,json=rsaPublicKey,proto3" json:"rsa_public_key,omitempty"` 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"` Hostname string `protobuf:"bytes,10,opt,name=hostname,proto3" json:"hostname,omitempty"`
Profiles []*Profile `protobuf:"bytes,11,rep,name=profiles,proto3" json:"profiles,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"`
unknownFields protoimpl.UnknownFields unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache sizeCache protoimpl.SizeCache
} }
@@ -168,6 +175,105 @@ func (x *Config) GetProfiles() []*Profile {
return nil return nil
} }
func (x *Config) GetPaddings() []*Padding {
if x != nil {
return x.Paddings
}
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.
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
sizeCache protoimpl.SizeCache
}
func (x *Padding) Reset() {
*x = Padding{}
mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Padding) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Padding) ProtoMessage() {}
func (x *Padding) ProtoReflect() protoreflect.Message {
mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[2]
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 Padding.ProtoReflect.Descriptor instead.
func (*Padding) Descriptor() ([]byte, []int) {
return file_transport_internet_finalmask_xmc_config_proto_rawDescGZIP(), []int{2}
}
func (x *Padding) GetLengthMin() int64 {
if x != nil {
return x.LengthMin
}
return 0
}
func (x *Padding) GetLengthMax() int64 {
if x != nil {
return x.LengthMax
}
return 0
}
func (x *Padding) GetDirection() int32 {
if x != nil {
return x.Direction
}
return 0
}
func (x *Padding) GetDelayMin() int64 {
if x != nil {
return x.DelayMin
}
return 0
}
func (x *Padding) GetDelayMax() int64 {
if x != nil {
return x.DelayMax
}
return 0
}
var File_transport_internet_finalmask_xmc_config_proto protoreflect.FileDescriptor var File_transport_internet_finalmask_xmc_config_proto protoreflect.FileDescriptor
const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" + const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
@@ -177,14 +283,25 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
"\busername\x18\x01 \x01(\tR\busername\x12\x12\n" + "\busername\x18\x01 \x01(\tR\busername\x12\x12\n" +
"\x04uuid\x18\x02 \x01(\fR\x04uuid\x12%\n" + "\x04uuid\x18\x02 \x01(\fR\x04uuid\x12%\n" +
"\x0etextures_value\x18\x03 \x01(\tR\rtexturesValue\x12-\n" + "\x0etextures_value\x18\x03 \x01(\tR\rtexturesValue\x12-\n" +
"\x12textures_signature\x18\x04 \x01(\tR\x11texturesSignature\"\xe0\x01\n" + "\x12textures_signature\x18\x04 \x01(\tR\x11texturesSignature\"\xcb\x02\n" +
"\x06Config\x12\x1a\n" + "\x06Config\x12\x1a\n" +
"\bpassword\x18\x01 \x01(\tR\bpassword\x12&\n" + "\bpassword\x18\x01 \x01(\tR\bpassword\x12&\n" +
"\x0frsa_private_key\x18\b \x01(\fR\rrsaPrivateKey\x12$\n" + "\x0frsa_private_key\x18\b \x01(\fR\rrsaPrivateKey\x12$\n" +
"\x0ersa_public_key\x18\t \x01(\fR\frsaPublicKey\x12\x1a\n" + "\x0ersa_public_key\x18\t \x01(\fR\frsaPublicKey\x12\x1a\n" +
"\bhostname\x18\n" + "\bhostname\x18\n" +
" \x01(\tR\bhostname\x12J\n" + " \x01(\tR\bhostname\x12J\n" +
"\bprofiles\x18\v \x03(\v2..xray.transport.internet.finalmask.xmc.ProfileR\bprofilesJ\x04\b\x02\x10\x03B\x91\x01\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" +
"\aPadding\x12\x1d\n" +
"\n" +
"length_min\x18\x01 \x01(\x03R\tlengthMin\x12\x1d\n" +
"\n" +
"length_max\x18\x02 \x01(\x03R\tlengthMax\x12\x1c\n" +
"\tdirection\x18\x03 \x01(\x05R\tdirection\x12\x1b\n" +
"\tdelay_min\x18\x04 \x01(\x03R\bdelayMin\x12\x1b\n" +
"\tdelay_max\x18\x05 \x01(\x03R\bdelayMaxB\x91\x01\n" +
")com.xray.transport.internet.finalmask.xmcP\x01Z:github.com/xtls/xray-core/transport/internet/finalmask/xmc\xaa\x02%Xray.Transport.Internet.Finalmask.XMCb\x06proto3" ")com.xray.transport.internet.finalmask.xmcP\x01Z:github.com/xtls/xray-core/transport/internet/finalmask/xmc\xaa\x02%Xray.Transport.Internet.Finalmask.XMCb\x06proto3"
var ( var (
@@ -199,18 +316,20 @@ func file_transport_internet_finalmask_xmc_config_proto_rawDescGZIP() []byte {
return file_transport_internet_finalmask_xmc_config_proto_rawDescData return file_transport_internet_finalmask_xmc_config_proto_rawDescData
} }
var file_transport_internet_finalmask_xmc_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_transport_internet_finalmask_xmc_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
var file_transport_internet_finalmask_xmc_config_proto_goTypes = []any{ var file_transport_internet_finalmask_xmc_config_proto_goTypes = []any{
(*Profile)(nil), // 0: xray.transport.internet.finalmask.xmc.Profile (*Profile)(nil), // 0: xray.transport.internet.finalmask.xmc.Profile
(*Config)(nil), // 1: xray.transport.internet.finalmask.xmc.Config (*Config)(nil), // 1: xray.transport.internet.finalmask.xmc.Config
(*Padding)(nil), // 2: xray.transport.internet.finalmask.xmc.Padding
} }
var file_transport_internet_finalmask_xmc_config_proto_depIdxs = []int32{ var file_transport_internet_finalmask_xmc_config_proto_depIdxs = []int32{
0, // 0: xray.transport.internet.finalmask.xmc.Config.profiles:type_name -> xray.transport.internet.finalmask.xmc.Profile 0, // 0: xray.transport.internet.finalmask.xmc.Config.profiles:type_name -> xray.transport.internet.finalmask.xmc.Profile
1, // [1:1] is the sub-list for method output_type 2, // 1: xray.transport.internet.finalmask.xmc.Config.paddings:type_name -> xray.transport.internet.finalmask.xmc.Padding
1, // [1:1] is the sub-list for method input_type 2, // [2:2] is the sub-list for method output_type
1, // [1:1] is the sub-list for extension type_name 2, // [2:2] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension extendee 2, // [2:2] is the sub-list for extension type_name
0, // [0:1] is the sub-list for field type_name 2, // [2:2] is the sub-list for extension extendee
0, // [0:2] is the sub-list for field type_name
} }
func init() { file_transport_internet_finalmask_xmc_config_proto_init() } func init() { file_transport_internet_finalmask_xmc_config_proto_init() }
@@ -224,7 +343,7 @@ func file_transport_internet_finalmask_xmc_config_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(), GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_transport_internet_finalmask_xmc_config_proto_rawDesc), len(file_transport_internet_finalmask_xmc_config_proto_rawDesc)), RawDescriptor: unsafe.Slice(unsafe.StringData(file_transport_internet_finalmask_xmc_config_proto_rawDesc), len(file_transport_internet_finalmask_xmc_config_proto_rawDesc)),
NumEnums: 0, NumEnums: 0,
NumMessages: 2, NumMessages: 3,
NumExtensions: 0, NumExtensions: 0,
NumServices: 0, NumServices: 0,
}, },
@@ -23,4 +23,28 @@ message Config {
bytes rsa_public_key = 9; bytes rsa_public_key = 9;
string hostname = 10; string hostname = 10;
repeated Profile profiles = 11; 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.
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 {
int64 length_min = 1;
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.
int64 delay_min = 4;
int64 delay_max = 5;
} }
@@ -0,0 +1,148 @@
package xmc
import (
"errors"
"net"
"strings"
"testing"
"time"
)
func TestClientRejectsLongLegacyPassword(t *testing.T) {
client, server := net.Pipe()
defer client.Close()
defer server.Close()
profiles := []loginProfile{{Username: "TestUser"}}
publicKey := []byte{0x01}
if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength), publicKey, "localhost", nil); err != nil {
t.Fatalf("password of %d bytes was rejected: %v", MaxLegacyPasswordLength, err)
}
if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength+1), publicKey, "localhost", nil); err == nil {
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,81 +0,0 @@
package xmc
import (
"net"
"sync"
"testing"
"time"
)
func TestConnectionDeadlinesRestoreCallerValues(t *testing.T) {
client, server := net.Pipe()
defer client.Close()
defer server.Close()
recording := &deadlineRecordingConn{Conn: client}
deadlines := newConnectionDeadlines(recording)
callerDeadline := time.Now().Add(10 * time.Minute)
if err := deadlines.setDeadline(callerDeadline); err != nil {
t.Fatal(err)
}
if err := deadlines.beginHandshake(); err != nil {
t.Fatal(err)
}
read, write := recording.currentDeadlines()
if !read.Before(callerDeadline) || !write.Before(callerDeadline) {
t.Fatalf("handshake deadlines = %s/%s, caller = %s", read, write, callerDeadline)
}
shortReadDeadline := time.Now().Add(time.Second)
if err := deadlines.setReadDeadline(shortReadDeadline); err != nil {
t.Fatal(err)
}
read, _ = recording.currentDeadlines()
if !read.Equal(shortReadDeadline) {
t.Fatalf("read deadline = %s, want %s", read, shortReadDeadline)
}
if err := deadlines.endHandshake(); err != nil {
t.Fatal(err)
}
read, write = recording.currentDeadlines()
if !read.Equal(shortReadDeadline) || !write.Equal(callerDeadline) {
t.Fatalf("restored deadlines = %s/%s, want %s/%s", read, write, shortReadDeadline, callerDeadline)
}
}
type deadlineRecordingConn struct {
net.Conn
mu sync.Mutex
read time.Time
write time.Time
}
func (c *deadlineRecordingConn) SetDeadline(t time.Time) error {
c.mu.Lock()
c.read = t
c.write = t
c.mu.Unlock()
return c.Conn.SetDeadline(t)
}
func (c *deadlineRecordingConn) SetReadDeadline(t time.Time) error {
c.mu.Lock()
c.read = t
c.mu.Unlock()
return c.Conn.SetReadDeadline(t)
}
func (c *deadlineRecordingConn) SetWriteDeadline(t time.Time) error {
c.mu.Lock()
c.write = t
c.mu.Unlock()
return c.Conn.SetWriteDeadline(t)
}
func (c *deadlineRecordingConn) currentDeadlines() (time.Time, time.Time) {
c.mu.Lock()
defer c.mu.Unlock()
return c.read, c.write
}
@@ -1,58 +0,0 @@
package xmc
import (
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"testing"
)
func TestDeriveRSAKey(t *testing.T) {
password := "my-very-secret-password-12345"
key1, err := DeriveRSAKey(password)
if err != nil {
t.Fatalf("failed to derive key: %v", err)
}
err = key1.Validate()
if err != nil {
t.Fatalf("key is not valid RSA key: %v", err)
}
key2, err := DeriveRSAKey(password)
if err != nil {
t.Fatalf("failed to derive key second time: %v", err)
}
// Verify determinism
if key1.D.Cmp(key2.D) != 0 || key1.N.Cmp(key2.N) != 0 {
t.Errorf("derived keys are not identical for the same password")
}
// Verify different passwords yield different keys
keyDifferent, err := DeriveRSAKey(password + "-different")
if err != nil {
t.Fatalf("failed to derive different key: %v", err)
}
if key1.D.Cmp(keyDifferent.D) == 0 || key1.N.Cmp(keyDifferent.N) == 0 {
t.Errorf("derived keys are identical for different passwords")
}
}
func TestDeriveRSAKeyGoldenPrivateKey(t *testing.T) {
const password = "deterministic-rsa-key-golden"
const wantPKCS1DERHash = "3a8c4ad56a6fb42dab73c4d5fc3af754460a2db1441edc0970cbc7f4e0798d2f"
key, err := DeriveRSAKey(password)
if err != nil {
t.Fatalf("failed to derive key: %v", err)
}
gotHash := sha256.Sum256(x509.MarshalPKCS1PrivateKey(key))
got := hex.EncodeToString(gotHash[:])
if got != wantPKCS1DERHash {
t.Fatalf("derived private key changed\nwant sha256: %s\n got sha256: %s", wantPKCS1DERHash, got)
}
}
@@ -2,389 +2,113 @@ package xmc
import ( import (
"bytes" "bytes"
"crypto/sha256"
"crypto/x509" "crypto/x509"
"errors"
"fmt"
"io" "io"
"net" "net"
"strings"
"sync"
"testing" "testing"
"time" "time"
) )
func deriveTestRSAKey(t *testing.T, password string) ([]byte, []byte) { func TestHandshakeWithBidirectionalPadding(t *testing.T) {
t.Helper() t.Run("pipe", func(t *testing.T) {
client, server := net.Pipe()
key, err := DeriveRSAKey(password) testHandshakeWithPadding(t, client, server, 64*1024)
if err != nil { })
t.Fatalf("failed to derive rsa key: %v", err) t.Run("tcp", func(t *testing.T) {
} listener, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
t.Fatalf("failed to marshal public key: %v", err)
}
return x509.MarshalPKCS1PrivateKey(key), publicKey
}
func testLoginProfile(username string) loginProfile {
profile := loginProfile{
Username: username,
TexturesValue: strings.Repeat("texture-value-", 40),
TexturesSignature: strings.Repeat("texture-signature-", 24),
}
digest := sha256.Sum256([]byte(username))
copy(profile.UUID[:], digest[:16])
profile.UUID[6] = (profile.UUID[6] & 0x0f) | 0x40
profile.UUID[8] = (profile.UUID[8] & 0x3f) | 0x80
return profile
}
func TestHandshakeSuccess(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer ln.Close()
password := "super-secure-shared-key-12345"
profiles := []loginProfile{testLoginProfile("test_user")}
privateKey, publicKey := deriveTestRSAKey(t, password)
go func() {
rawConn, err := ln.Accept()
if err != nil {
return
}
defer rawConn.Close()
server, err := wrapConnServer(rawConn, profiles, password, privateKey, publicKey)
if err != nil {
t.Errorf("failed to wrap server: %v", err)
return
}
buf := make([]byte, 1024)
n, err := server.Read(buf)
if err != nil {
t.Errorf("server read error: %v", err)
return
}
if !bytes.Equal(buf[:n], []byte("hello server")) {
t.Errorf("unexpected payload from client: %s", string(buf[:n]))
return
}
_, err = server.Write([]byte("hello client"))
if err != nil {
t.Errorf("server write error: %v", err)
return
}
}()
clientRaw, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
t.Fatalf("failed to dial: %v", err)
}
defer clientRaw.Close()
client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost")
if err != nil {
t.Fatalf("failed to create client: %v", err)
}
_, err = client.Write([]byte("hello server"))
if err != nil {
t.Fatalf("client write error: %v", err)
}
buf := make([]byte, 1024)
n, err := client.Read(buf)
if err != nil {
t.Fatalf("client read error: %v", err)
}
if !bytes.Equal(buf[:n], []byte("hello client")) {
t.Errorf("unexpected payload from server: %s", string(buf[:n]))
}
}
func TestHandshakePasswordMismatch(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer ln.Close()
clientPassword := "client-secret-123"
serverPassword := "server-secret-456"
profiles := []loginProfile{testLoginProfile("test_user")}
serverPrivateKey, serverPublicKey := deriveTestRSAKey(t, serverPassword)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
rawConn, err := ln.Accept()
if err != nil {
return
}
defer rawConn.Close()
server, err := wrapConnServer(rawConn, profiles, serverPassword, serverPrivateKey, serverPublicKey)
if err != nil {
// Wrapping is synchronous and shouldn't fail initially simply because key derivation works with any string
t.Logf("wrapped server: %v", err)
}
// When client sends data, handshake happens and should fail
buf := make([]byte, 1024)
_, err = server.Read(buf)
if err == nil {
t.Errorf("expected handshake to fail due to password mismatch, but it succeeded")
} else {
t.Logf("server read failed as expected: %v", err)
}
}()
clientRaw, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
t.Fatalf("failed to dial: %v", err)
}
defer clientRaw.Close()
client, err := newClientConn(clientRaw, profiles, clientPassword, serverPublicKey, "localhost")
if err != nil {
t.Fatalf("failed to create client: %v", err)
}
err = client.handshake()
if err == nil {
t.Fatal("expected client handshake to fail due to password mismatch")
}
wg.Wait()
// Check if we lost connection or received error
t.Log("Handshake mismatch tested")
}
func TestHandshakeNetPipeWithKeepAlive(t *testing.T) {
clientRaw, serverRaw := net.Pipe()
defer clientRaw.Close()
defer serverRaw.Close()
const password = "net-pipe-shared-key"
profiles := []loginProfile{testLoginProfile("pipe_user")}
privateKey, publicKey := deriveTestRSAKey(t, password)
serverDone := make(chan error, 1)
go func() {
server, err := wrapConnServer(serverRaw, profiles, password, privateKey, publicKey)
if err != nil {
serverDone <- err
return
}
request := make([]byte, len("hello server"))
if _, err = io.ReadFull(server, request); err != nil {
serverDone <- fmt.Errorf("read request: %w", err)
return
}
if string(request) != "hello server" {
serverDone <- fmt.Errorf("unexpected request: %q", request)
return
}
followupDone := make(chan error, 1)
go func() {
followup := make([]byte, len("after keepalive"))
_, readErr := io.ReadFull(server, followup)
if readErr == nil && string(followup) != "after keepalive" {
readErr = fmt.Errorf("unexpected followup: %q", followup)
}
followupDone <- readErr
}()
if err = server.packet.writeKeepAlive(Long(42)); err != nil {
serverDone <- fmt.Errorf("write keep-alive: %w", err)
return
}
if _, err = server.Write([]byte("hello client")); err != nil {
serverDone <- fmt.Errorf("write response: %w", err)
return
}
serverDone <- <-followupDone
}()
client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost")
if err != nil {
t.Fatal(err)
}
if _, err = client.Write([]byte("hello server")); err != nil {
t.Fatalf("write request: %v", err)
}
response := make([]byte, len("hello client"))
if _, err = io.ReadFull(client, response); err != nil {
t.Fatalf("read response: %v", err)
}
if string(response) != "hello client" {
t.Fatalf("unexpected response: %q", response)
}
if _, err = client.Write([]byte("after keepalive")); err != nil {
t.Fatalf("write followup: %v", err)
}
select {
case err = <-serverDone:
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
case <-time.After(5 * time.Second): defer listener.Close()
t.Fatal("net.Pipe handshake timed out") 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 TestStatusQueryUnaffected(t *testing.T) { func testHandshakeWithPadding(t *testing.T, clientRaw, serverRaw net.Conn, length int64) {
clientRaw, serverRaw := net.Pipe() t.Helper()
defer clientRaw.Close() defer clientRaw.Close()
defer serverRaw.Close() defer serverRaw.Close()
const password = "status-shared-key" key, err := DeriveRSAKey("padding-regression")
profiles := []loginProfile{testLoginProfile("status_user")} if err != nil {
privateKey, publicKey := deriveTestRSAKey(t, password) t.Fatal(err)
serverDone := make(chan error, 1) }
go func() { publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
server, err := wrapConnServer(serverRaw, profiles, password, privateKey, publicKey) if err != nil {
if err == nil { t.Fatal(err)
err = server.handshake() }
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)
} }
serverDone <- err
}()
protocolVersion := Varint(775)
serverAddress := String("localhost")
serverPort := UnsignedShort(25565)
nextState := Varint(1)
if err := writePacket(clientRaw, 0x00, &protocolVersion, &serverAddress, &serverPort, &nextState); err != nil {
t.Fatal(err)
}
if err := writePacket(clientRaw, 0x00); err != nil {
t.Fatal(err)
}
response, err := readPacket(clientRaw)
if err != nil {
t.Fatal(err)
}
if response.packetID != 0x00 {
t.Fatalf("status packet id = %d", response.packetID)
}
var responseJSON String
if err = response.readFields(&responseJSON); err != nil {
t.Fatal(err)
}
if string(responseJSON) != statusResponse {
t.Fatalf("status response = %q", responseJSON)
} }
payload := Long(0x0102030405060708) results := make(chan error, 2)
if err = writePacket(clientRaw, 0x01, &payload); err != nil { go func() { results <- client.handshake() }()
t.Fatal(err) go func() { results <- server.handshake() }()
} for range 2 {
pong, err := readPacket(clientRaw) if err := <-results; err != nil {
if err != nil { t.Errorf("handshake: %v", err)
t.Fatal(err)
}
var receivedPayload Long
if pong.packetID != 0x01 {
t.Fatalf("pong packet id = %d", pong.packetID)
}
if err = pong.readFields(&receivedPayload); err != nil {
t.Fatal(err)
}
if receivedPayload != payload {
t.Fatalf("pong payload = %x", receivedPayload)
}
select {
case err = <-serverDone:
if err == nil || !strings.Contains(err.Error(), "ping") {
t.Fatalf("server error = %v", err)
} }
case <-time.After(time.Second):
t.Fatal("status handshake timed out")
} }
} if t.Failed() {
return
func TestClientHandshakeHonorsCallerDeadline(t *testing.T) {
clientRaw, serverRaw := net.Pipe()
defer clientRaw.Close()
defer serverRaw.Close()
const password = "deadline-shared-key"
profiles := []loginProfile{testLoginProfile("deadline_user")}
_, publicKey := deriveTestRSAKey(t, password)
client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost")
if err != nil {
t.Fatal(err)
}
if err = client.SetDeadline(time.Now().Add(30 * time.Millisecond)); err != nil {
t.Fatal(err)
} }
started := time.Now() // Both startup readers can already be waiting for the next packet. The
_, err = client.Write([]byte("blocked")) // first proxy payload in either direction must survive the handoff.
var netErr net.Error for _, pair := range [][2]net.Conn{{client, server}, {server, client}} {
if !errors.As(err, &netErr) || !netErr.Timeout() { want := bytes.Repeat([]byte("proxy payload"), 4096)
t.Fatalf("error = %v, want network timeout", err) go func() {
} _, err := pair[0].Write(want)
if elapsed := time.Since(started); elapsed > 500*time.Millisecond { results <- err
t.Fatalf("caller deadline took %s", elapsed) }()
} got := make([]byte, len(want))
} if _, err := io.ReadFull(pair[1], got); err != nil {
t.Fatal(err)
func TestClientCloseInterruptsHandshake(t *testing.T) { }
clientRaw, serverRaw := net.Pipe() if err := <-results; err != nil {
defer serverRaw.Close() t.Fatal(err)
}
const password = "close-shared-key" if !bytes.Equal(got, want) {
profiles := []loginProfile{testLoginProfile("close_user")} t.Fatal("proxy payload changed after startup padding")
_, publicKey := deriveTestRSAKey(t, password)
client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost")
if err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() {
_, writeErr := client.Write([]byte("blocked"))
done <- writeErr
}()
time.Sleep(20 * time.Millisecond)
if err = client.Close(); err != nil {
t.Fatal(err)
}
select {
case err = <-done:
if err == nil {
t.Fatal("handshake unexpectedly succeeded after close")
} }
case <-time.After(time.Second):
t.Fatal("close did not interrupt handshake")
}
}
func TestValidateLoginAcknowledgedPacketRejectsData(t *testing.T) {
if err := validateLoginAcknowledgedPacket(&mcPacket{packetID: 0x03}); err != nil {
t.Fatalf("valid login acknowledged packet: %v", err)
}
if err := validateLoginAcknowledgedPacket(&mcPacket{packetID: 0x03, data: []byte{0x00}}); err == nil {
t.Fatal("login acknowledged packet with trailing data was accepted")
} }
} }
@@ -1,102 +0,0 @@
package xmc
import (
"bytes"
"io"
"net"
"testing"
)
func TestPacketStreamUsesPlainFraming(t *testing.T) {
payload := []byte("hello")
var wire bytes.Buffer
stream := newPacketStream(bytes.NewReader(nil), &wire, true)
written, err := stream.Write(payload)
if err != nil {
t.Fatalf("write payload: %v", err)
}
if written != len(payload) {
t.Fatalf("written = %d, want %d", written, len(payload))
}
wantOutbound := []byte{0x0f, 0x02, 0x08, 'x', 'm', 'c', ':', 'd', 'a', 't', 'a', 'h', 'e', 'l', 'l', 'o'}
if !bytes.Equal(wire.Bytes(), wantOutbound) {
t.Fatalf("wire frame = %x, want %x", wire.Bytes(), wantOutbound)
}
wantInbound := append([]byte(nil), wantOutbound...)
wantInbound[1] = configurationClientboundCustomPayload
reader := newPacketStream(bytes.NewReader(wantInbound), io.Discard, true)
got := make([]byte, len(payload))
if _, err = io.ReadFull(reader, got); err != nil {
t.Fatalf("read payload: %v", err)
}
if !bytes.Equal(got, payload) {
t.Fatalf("payload = %q, want %q", got, payload)
}
}
func TestPacketStreamRoundTrip(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
const password = "packet-stream-shared-key"
privateKey, publicKey := deriveTestRSAKey(t, password)
profiles := []loginProfile{testLoginProfile("packet_user")}
clientPayload := bytes.Repeat([]byte("client-payload-"), 5000)
serverPayload := bytes.Repeat([]byte("server-payload-"), 5000)
serverDone := make(chan error, 1)
go func() {
rawConn, acceptErr := ln.Accept()
if acceptErr != nil {
serverDone <- acceptErr
return
}
defer rawConn.Close()
server, wrapErr := wrapConnServer(rawConn, profiles, password, privateKey, publicKey)
if wrapErr != nil {
serverDone <- wrapErr
return
}
got := make([]byte, len(clientPayload))
if _, readErr := io.ReadFull(server, got); readErr != nil {
serverDone <- readErr
return
}
if !bytes.Equal(got, clientPayload) {
serverDone <- io.ErrUnexpectedEOF
return
}
_, writeErr := server.Write(serverPayload)
serverDone <- writeErr
}()
rawClient, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
t.Fatal(err)
}
defer rawClient.Close()
client, err := newClientConn(rawClient, profiles, password, publicKey, "localhost")
if err != nil {
t.Fatal(err)
}
if _, err = client.Write(clientPayload); err != nil {
t.Fatalf("write payload: %v", err)
}
got := make([]byte, len(serverPayload))
if _, err = io.ReadFull(client, got); err != nil {
t.Fatalf("read payload: %v", err)
}
if !bytes.Equal(got, serverPayload) {
t.Fatal("server payload mismatch")
}
if err = <-serverDone; err != nil {
t.Fatalf("server: %v", err)
}
}
+172 -94
View File
@@ -1,11 +1,11 @@
package xmc package xmc
import ( import (
"bytes"
"crypto/rand" "crypto/rand"
"fmt" "fmt"
"io" "io"
"math/big" "math/big"
"net"
"time" "time"
) )
@@ -18,8 +18,31 @@ const (
paddingBufferLength = 16 * 1024 paddingBufferLength = 16 * 1024
maxPaddingChunkLength = 48 * 1024 maxPaddingChunkLength = 48 * 1024
maxPaddingTurnLength = 8 * 1024 * 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
// from the packet stream channel: both ends drop unknown payloads.
paddingFrameChannel = "xmc:pad"
// Serverbound custom payload data is capped at 32767 bytes by
// ServerboundCustomPayloadPacket; keep the same budget in both directions.
maxPaddingFrameDataLength = 32767
// Length varint, packet id, channel length varint and the channel itself.
paddingFrameOverhead = 1 + 1 + 1 + len(paddingFrameChannel)
) )
var maxPaddingFrameLength = paddingFrameLength(maxPaddingFrameDataLength)
type paddingVariant struct { type paddingVariant struct {
chunks []int chunks []int
delays []paddingDelayRange delays []paddingDelayRange
@@ -31,9 +54,12 @@ type paddingDelayRange struct {
} }
type paddingTurn struct { type paddingTurn struct {
direction paddingDirection direction paddingDirection
minLength int minLength int
maxLength 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
variants []paddingVariant variants []paddingVariant
startDelay paddingDelayRange startDelay paddingDelayRange
chunkDelay paddingDelayRange chunkDelay paddingDelayRange
@@ -44,27 +70,66 @@ type paddingTurn struct {
sendVariants []int sendVariants []int
} }
func runPaddingSchedule(reader io.Reader, writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn) error { // 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
}
}
// 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
}
if err := validatePaddingSchedule(schedule, firstTurnPrefixLength); err != nil { if err := validatePaddingSchedule(schedule, firstTurnPrefixLength); err != nil {
return err return err
} }
var writeBuffer []byte
for i, turn := range schedule { for i, turn := range schedule {
prefixLength := 0 prefixLength := 0
if i == 0 { if i == 0 {
prefixLength = firstTurnPrefixLength prefixLength = firstTurnPrefixLength
} }
localSends := isClient == (turn.direction == paddingClientToServer) if isClient != (turn.direction == paddingClientToServer) {
if localSends { // The startup reader drains peer padding independently so writes
if err := writePaddingTurnWithBuffer(writer, turn, prefixLength, time.Sleep, &writeBuffer); err != nil { // cannot fill both connection buffers. The peer still spends the
return fmt.Errorf("write padding turn %d: %w", i, err) // 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
} }
continue continue
} }
if err := readPaddingTurn(reader, turn, prefixLength); err != nil { delay, err := randomPaddingDelay(turn.delay)
return fmt.Errorf("read padding turn %d: %w", i, err) 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)
} }
} }
return nil return nil
@@ -91,6 +156,9 @@ func validatePaddingSchedule(schedule []paddingTurn, firstTurnPrefixLength int)
if err := validatePaddingDelayRange(turn.chunkDelay); err != nil { if err := validatePaddingDelayRange(turn.chunkDelay); err != nil {
return fmt.Errorf("padding turn %d has an invalid chunk delay: %w", i, err) return fmt.Errorf("padding turn %d has an invalid chunk delay: %w", i, err)
} }
if err := validatePaddingDelayRange(turn.delay); err != nil {
return fmt.Errorf("padding turn %d has an invalid inter-turn delay: %w", i, err)
}
if turn.writeChunkMinLength < 0 || turn.writeChunkLength < turn.writeChunkMinLength || turn.writeChunkLength > maxPaddingChunkLength { if turn.writeChunkMinLength < 0 || turn.writeChunkLength < turn.writeChunkMinLength || turn.writeChunkLength > maxPaddingChunkLength {
return fmt.Errorf("padding turn %d has an invalid write chunk range: %d-%d", i, turn.writeChunkMinLength, turn.writeChunkLength) return fmt.Errorf("padding turn %d has an invalid write chunk range: %d-%d", i, turn.writeChunkMinLength, turn.writeChunkLength)
} }
@@ -121,43 +189,39 @@ func validatePaddingSchedule(schedule []paddingTurn, firstTurnPrefixLength int)
} }
} }
} }
if i > 0 && turn.direction == schedule[i-1].direction {
return fmt.Errorf("padding turns %d and %d have the same direction", i-1, i)
}
} }
return nil return nil
} }
func writePaddingTurn(w io.Writer, turn paddingTurn, prefixLength int) error { // paddingFramePacketID returns the configuration-state custom payload packet id
return writePaddingTurnWithSleep(w, turn, prefixLength, time.Sleep) // used by the side that sends the padding bytes; both values come from the
// vanilla configuration protocol, so no proxy-specific id ever reaches the wire.
func paddingFramePacketID(isClient bool) int {
if isClient {
return configurationServerboundCustomPayload
}
return configurationClientboundCustomPayload
} }
func writePaddingTurnWithSleep(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration)) error { // writePaddingTurnFrames writes one padding turn as a sequence of valid
return writePaddingTurnWithBuffer(w, turn, prefixLength, sleep, nil) // 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 writePaddingTurnWithBuffer(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration), reusableBuffer *[]byte) error {
startDelay, err := randomPaddingDelay(turn.startDelay) startDelay, err := randomPaddingDelay(turn.startDelay)
if err != nil { if err != nil {
return fmt.Errorf("select padding start delay: %w", err) return 0, fmt.Errorf("select padding start delay: %w", err)
} }
if startDelay > 0 { if err := sleep(startDelay); err != nil {
sleep(startDelay) return 0, err
} }
targetLength, chunks, delays, err := selectPaddingVariant(turn, prefixLength) targetLength, chunks, delays, err := selectPaddingVariant(turn, prefixLength)
if err != nil { if err != nil {
return err return 0, err
} }
recordLength := targetLength - prefixLength payloadLength := targetLength - prefixLength
if recordLength < 1 { if payloadLength < 1 {
return fmt.Errorf("target length %d leaves an invalid record length %d", targetLength, recordLength) return 0, fmt.Errorf("target length %d leaves an invalid padding payload of %d bytes", targetLength, payloadLength)
}
encodedLength := Varint(recordLength)
var header bytes.Buffer
if err = encodedLength.writeTo(&header); err != nil {
return fmt.Errorf("write padding header: %w", err)
} }
if len(chunks) == 0 { if len(chunks) == 0 {
writeChunkLength := turn.writeChunkLength writeChunkLength := turn.writeChunkLength
@@ -166,89 +230,103 @@ func writePaddingTurnWithBuffer(w io.Writer, turn paddingTurn, prefixLength int,
} else if turn.writeChunkMinLength > 0 { } else if turn.writeChunkMinLength > 0 {
writeChunkLength, err = randomPaddingTarget(turn.writeChunkMinLength, writeChunkLength) writeChunkLength, err = randomPaddingTarget(turn.writeChunkMinLength, writeChunkLength)
if err != nil { if err != nil {
return fmt.Errorf("select padding write chunk length: %w", err) return 0, fmt.Errorf("select padding write chunk length: %w", err)
} }
} }
chunks = defaultPaddingChunks(recordLength, writeChunkLength) chunks = defaultPaddingChunks(payloadLength, writeChunkLength)
delays = make([]paddingDelayRange, len(chunks)) delays = make([]paddingDelayRange, len(chunks))
for i := 1; i < len(delays); i++ { for i := 1; i < len(delays); i++ {
delays[i] = turn.chunkDelay delays[i] = turn.chunkDelay
} }
} }
if chunks[0] < header.Len() {
return fmt.Errorf("first padding chunk %d is shorter than header %d", chunks[0], header.Len())
}
maxChunkLength := 0 zeros := make([]byte, maxPaddingFrameDataLength)
for _, chunkLength := range chunks { channel := String(paddingFrameChannel)
if chunkLength < 1 || chunkLength > maxPaddingChunkLength {
return fmt.Errorf("invalid padding chunk length: %d", chunkLength)
}
maxChunkLength = max(maxChunkLength, chunkLength)
}
var buffer []byte
if reusableBuffer == nil {
buffer = make([]byte, maxChunkLength)
} else {
if cap(*reusableBuffer) < maxChunkLength {
*reusableBuffer = make([]byte, maxChunkLength)
}
buffer = (*reusableBuffer)[:maxChunkLength]
clear(buffer)
}
copy(buffer, header.Bytes())
written := 0 written := 0
for i, chunkLength := range chunks { for i, chunkLength := range chunks {
if i < len(delays) { if i < len(delays) {
delay, delayErr := randomPaddingDelay(delays[i]) delay, delayErr := randomPaddingDelay(delays[i])
if delayErr != nil { if delayErr != nil {
return fmt.Errorf("select padding chunk %d delay: %w", i, delayErr) return written, fmt.Errorf("select padding chunk %d delay: %w", i, delayErr)
} }
if delay > 0 { if delayErr = sleep(delay); delayErr != nil {
sleep(delay) return written, delayErr
} }
} }
if err = writeFull(w, buffer[:chunkLength]); err != nil { frameLengths, planErr := paddingFramePlan(chunkLength)
return fmt.Errorf("write padding chunk %d: %w", i, err) if planErr != nil {
return written, planErr
} }
written += chunkLength for _, frameLength := range frameLengths {
if i == 0 { dataLength, ok := paddingFrameDataLength(frameLength)
clear(buffer[:header.Len()]) if !ok {
return written, fmt.Errorf("unframed padding length %d", frameLength)
}
payload := RestBytes(zeros[:dataLength])
if err = writePacket(w, packetID, &channel, &payload); err != nil {
return written, fmt.Errorf("write padding frame: %w", err)
}
written += frameLength
} }
} }
if written != recordLength { return written, nil
return fmt.Errorf("padding chunks total %d, want %d", written, recordLength)
}
return nil
} }
func readPaddingTurn(r io.Reader, turn paddingTurn, prefixLength int) error { // paddingFrameLength is the wire size of a custom payload frame whose payload
encodedLength, headerLength, err := readVarintWithLength(r) // body is dataLength bytes long.
if err != nil { func paddingFrameLength(dataLength int) int {
return fmt.Errorf("read padding header: %w", err) bodyLength := 1 + 1 + len(paddingFrameChannel) + dataLength
} return varintSize(Varint(bodyLength)) + bodyLength
recordLength := int(encodedLength) }
if recordLength < headerLength || recordLength > maxPaddingTurnLength {
return fmt.Errorf("invalid padding record length: %d", recordLength)
}
totalLength := prefixLength + recordLength
if !paddingTurnAcceptsLength(turn, totalLength) {
if len(turn.variants) > 0 {
return fmt.Errorf("padding turn length %d is not an allowed variant", totalLength)
}
return fmt.Errorf("padding turn length %d is outside %d-%d", totalLength, turn.minLength, turn.maxLength)
}
var buffer [paddingBufferLength]byte // paddingFrameDataLength is the payload body that makes a frame exactly
remaining := recordLength - headerLength // frameLength bytes long. Some lengths are unreachable because the length
for remaining > 0 { // varint grows in steps.
chunkLength := min(remaining, len(buffer)) func paddingFrameDataLength(frameLength int) (int, bool) {
if _, err := io.ReadFull(r, buffer[:chunkLength]); err != nil { for overhead := paddingFrameOverhead; overhead <= paddingFrameOverhead+2; overhead++ {
return fmt.Errorf("read padding body: %w", err) dataLength := frameLength - overhead
if dataLength < 0 || dataLength > maxPaddingFrameDataLength {
continue
}
if paddingFrameLength(dataLength) == frameLength {
return dataLength, true
} }
remaining -= chunkLength
} }
return nil return 0, false
}
// paddingFramePlan splits length bytes into reachable frame sizes. The result is
// exact whenever a partition exists; a length below the smallest frame (the
// captured 2-byte turns) is rounded up to that frame.
func paddingFramePlan(length int) ([]int, error) {
if length <= 0 {
return nil, nil
}
if length < paddingFrameOverhead {
return []int{paddingFrameOverhead}, nil
}
frameLengths := make([]int, 0, length/paddingBufferLength+1)
for remaining := length; remaining > 0; {
candidate := min(remaining, maxPaddingFrameLength)
picked := 0
for ; candidate >= paddingFrameOverhead; candidate-- {
if _, ok := paddingFrameDataLength(candidate); !ok {
continue
}
rest := remaining - candidate
if rest > 0 && rest < paddingFrameOverhead {
continue
}
picked = candidate
break
}
if picked == 0 {
return nil, fmt.Errorf("cannot frame %d padding bytes", length)
}
frameLengths = append(frameLengths, picked)
remaining -= picked
}
return frameLengths, nil
} }
func selectPaddingVariant(turn paddingTurn, prefixLength int) (int, []int, []paddingDelayRange, error) { func selectPaddingVariant(turn paddingTurn, prefixLength int) (int, []int, []paddingDelayRange, error) {
@@ -0,0 +1,288 @@
package xmc
import (
"bytes"
"errors"
"io"
"net"
"strings"
"testing"
"time"
)
func TestPaddingFrameDataLengthRoundTrip(t *testing.T) {
for dataLength := 0; dataLength <= maxPaddingFrameDataLength; dataLength++ {
frameLength := paddingFrameLength(dataLength)
got, ok := paddingFrameDataLength(frameLength)
if !ok || got != dataLength {
t.Fatalf("data length %d -> frame %d -> data %d (ok=%v)", dataLength, frameLength, got, ok)
}
}
}
func TestPaddingFramePlanTotals(t *testing.T) {
lengths := []int{paddingFrameOverhead, paddingFrameOverhead + 1, 128, 129, 130, 131, 140, 1024, 48 * 1024, maxPaddingFrameLength - 1, maxPaddingFrameLength, maxPaddingFrameLength + 1, 3 * maxPaddingFrameLength, 1024 * 1024}
for _, length := range lengths {
plan, err := paddingFramePlan(length)
if err != nil {
t.Fatalf("plan %d: %v", length, err)
}
total := 0
for _, frameLength := range plan {
if _, ok := paddingFrameDataLength(frameLength); !ok {
t.Fatalf("plan %d contains unreachable frame %d", length, frameLength)
}
if frameLength > maxPaddingFrameLength {
t.Fatalf("plan %d contains oversized frame %d", length, frameLength)
}
total += frameLength
}
if total != length {
t.Fatalf("plan %d totals %d", length, total)
}
}
}
func TestPaddingFramePlanRoundsUpShortTurn(t *testing.T) {
plan, err := paddingFramePlan(2)
if err != nil {
t.Fatal(err)
}
if len(plan) != 1 || plan[0] != paddingFrameOverhead {
t.Fatalf("short turn plan = %v", plan)
}
}
func TestWritePaddingTurnFramesIsMinecraftTraffic(t *testing.T) {
turns := []paddingTurn{
{direction: paddingClientToServer, minLength: 44, maxLength: 44},
{direction: paddingClientToServer, minLength: 2, maxLength: 2},
{direction: paddingClientToServer, minLength: maxPaddingFrameLength, maxLength: maxPaddingFrameLength},
{direction: paddingClientToServer, minLength: 3*maxPaddingFrameLength + 7, maxLength: 3*maxPaddingFrameLength + 7},
}
for i, turn := range turns {
var buffer bytes.Buffer
written, err := writePaddingTurnFrames(&buffer, turn, 0, noPaddingPause, configurationServerboundCustomPayload)
if err != nil {
t.Fatalf("turn %d: %v", i, err)
}
if written != buffer.Len() {
t.Fatalf("turn %d wrote %d bytes, buffer has %d", i, written, buffer.Len())
}
target := turn.minLength
if written < target {
t.Fatalf("turn %d wrote %d bytes, want at least %d", i, written, target)
}
reader := bytes.NewReader(buffer.Bytes())
frames := 0
for reader.Len() > 0 {
packet, err := readPacket(reader)
if err != nil {
t.Fatalf("turn %d frame %d is not a valid packet: %v", i, frames, err)
}
if packet.packetID != configurationServerboundCustomPayload {
t.Fatalf("turn %d frame %d has packet id %d", i, frames, packet.packetID)
}
_, ok, err := parseCustomPayload(packet)
if err != nil {
t.Fatalf("turn %d frame %d: %v", i, frames, err)
}
if ok {
t.Fatalf("turn %d frame %d uses the packet stream channel", i, frames)
}
if len(packet.data) == 0 {
t.Fatalf("turn %d frame %d has no channel", i, frames)
}
frames++
}
}
}
func TestRunPaddingScheduleLeavesPeerTurnsAlone(t *testing.T) {
schedule := []paddingTurn{
{direction: paddingClientToServer, minLength: 44, maxLength: 44},
{direction: paddingServerToClient, minLength: 64, maxLength: 64},
{direction: paddingClientToServer, minLength: 25, maxLength: 25},
}
var out bytes.Buffer
if err := runPaddingSchedule(&out, true, 2, schedule, noPaddingPause); err != nil {
t.Fatal(err)
}
reader := bytes.NewReader(out.Bytes())
total := 0
for reader.Len() > 0 {
before := reader.Len()
packet, err := readPacket(reader)
if err != nil {
t.Fatalf("padding stream is not a valid packet stream: %v", err)
}
if packet.packetID != configurationServerboundCustomPayload {
t.Fatalf("unexpected packet id %d in padding stream", packet.packetID)
}
total += before - reader.Len()
}
// Turn 0 carries the 2 byte Login Acknowledged prefix, turn 1 is the peer's.
want := 44 - 2 + 25
if total != want {
t.Fatalf("padding stream carries %d payload bytes, want %d", total, want)
}
}
func TestRunPaddingScheduleRejectsInvalidSchedule(t *testing.T) {
schedule := []paddingTurn{
{direction: paddingServerToClient, minLength: 10, maxLength: 10},
}
if err := runPaddingSchedule(&bytes.Buffer{}, true, 2, schedule, noPaddingPause); 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")
}
}
@@ -0,0 +1,61 @@
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)
}
@@ -0,0 +1,76 @@
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)
}
}
@@ -1,618 +0,0 @@
package xmc
import (
"bytes"
"errors"
"io"
"net"
"strconv"
"strings"
"testing"
"time"
)
func TestPaddingTurnReachesFinalTargetLength(t *testing.T) {
turn := paddingTurn{direction: paddingClientToServer, minLength: 128, maxLength: 128}
const prefixLength = 3
var encoded bytes.Buffer
if err := writePaddingTurn(&encoded, turn, prefixLength); err != nil {
t.Fatal(err)
}
if got := prefixLength + encoded.Len(); got != turn.minLength {
t.Fatalf("total turn length = %d, want %d", got, turn.minLength)
}
encodedReader := bytes.NewReader(encoded.Bytes())
var recordLength Varint
if err := recordLength.readFrom(encodedReader); err != nil {
t.Fatal(err)
}
if got := int(recordLength); got != encoded.Len() {
t.Fatalf("record length = %d, encoded = %d", got, encoded.Len())
}
if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, prefixLength); err != nil {
t.Fatal(err)
}
}
func TestPaddingTurnSupportsThreeByteTarget(t *testing.T) {
turn := paddingTurn{direction: paddingClientToServer, minLength: 3, maxLength: 3}
var encoded bytes.Buffer
if err := writePaddingTurn(&encoded, turn, 0); err != nil {
t.Fatal(err)
}
if got := encoded.Len(); got != 3 {
t.Fatalf("padding length = %d, want 3", got)
}
if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, 0); err != nil {
t.Fatal(err)
}
}
func TestPaddingTurnVarintBoundaries(t *testing.T) {
for _, targetLength := range []int{127, 128, 16383, 16384} {
t.Run(strconv.Itoa(targetLength), func(t *testing.T) {
turn := paddingTurn{direction: paddingClientToServer, minLength: targetLength, maxLength: targetLength}
var encoded bytes.Buffer
if err := writePaddingTurn(&encoded, turn, 0); err != nil {
t.Fatal(err)
}
if encoded.Len() != targetLength {
t.Fatalf("padding length = %d, want %d", encoded.Len(), targetLength)
}
if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, 0); err != nil {
t.Fatal(err)
}
})
}
}
func TestPaddingTurnRandomRange(t *testing.T) {
turn := paddingTurn{direction: paddingServerToClient, minLength: 127, maxLength: 129}
seen := make(map[int]bool)
for range 100 {
var encoded bytes.Buffer
if err := writePaddingTurn(&encoded, turn, 0); err != nil {
t.Fatal(err)
}
if encoded.Len() < turn.minLength || encoded.Len() > turn.maxLength {
t.Fatalf("padding length = %d", encoded.Len())
}
seen[encoded.Len()] = true
}
if len(seen) < 2 {
t.Fatalf("padding range did not vary: %v", seen)
}
}
func TestPaddingTurnUsesRestrictedSendRange(t *testing.T) {
turn := paddingTurn{
direction: paddingServerToClient,
minLength: 3,
maxLength: 100,
sendMinLength: 90,
sendMaxLength: 100,
}
seen := make(map[int]bool)
for range 100 {
var encoded bytes.Buffer
if err := writePaddingTurn(&encoded, turn, 0); err != nil {
t.Fatal(err)
}
if encoded.Len() < turn.sendMinLength || encoded.Len() > turn.sendMaxLength {
t.Fatalf("padding length = %d", encoded.Len())
}
seen[encoded.Len()] = true
if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, 0); err != nil {
t.Fatal(err)
}
}
if len(seen) < 2 {
t.Fatalf("restricted send range did not vary: %v", seen)
}
}
func TestPaddingScheduleSynchronizesDirections(t *testing.T) {
client, server := net.Pipe()
defer client.Close()
defer server.Close()
schedule := []paddingTurn{
{direction: paddingClientToServer, minLength: 33, maxLength: 33},
{direction: paddingServerToClient, minLength: 4097, maxLength: 4097},
{direction: paddingClientToServer, minLength: 16385, maxLength: 16385},
}
serverDone := make(chan error, 1)
go func() {
serverDone <- runPaddingSchedule(server, server, false, 3, schedule)
}()
if err := runPaddingSchedule(client, client, true, 3, schedule); err != nil {
t.Fatal(err)
}
select {
case err := <-serverDone:
if err != nil {
t.Fatal(err)
}
case <-time.After(time.Second):
t.Fatal("server padding schedule did not complete")
}
}
func TestReadPaddingTurnHandlesFragmentedInput(t *testing.T) {
turn := paddingTurn{direction: paddingClientToServer, minLength: 1024, maxLength: 1024}
var encoded bytes.Buffer
if err := writePaddingTurn(&encoded, turn, 0); err != nil {
t.Fatal(err)
}
if err := readPaddingTurn(&oneByteReader{reader: bytes.NewReader(encoded.Bytes())}, turn, 0); err != nil {
t.Fatal(err)
}
}
func TestReadPaddingTurnRejectsInvalidLength(t *testing.T) {
turn := paddingTurn{direction: paddingClientToServer, minLength: 64, maxLength: 96}
data := encodePaddingLength(t, 63)
if err := readPaddingTurn(bytes.NewReader(data), turn, 0); err == nil || !strings.Contains(err.Error(), "outside") {
t.Fatalf("error = %v", err)
}
}
func TestReadPaddingTurnRejectsNonCanonicalHeader(t *testing.T) {
turn := paddingTurn{direction: paddingClientToServer, minLength: 3, maxLength: 3}
err := readPaddingTurn(bytes.NewReader([]byte{0x83, 0x00, 0x00}), turn, 0)
if err == nil || !strings.Contains(err.Error(), "non-canonical") {
t.Fatalf("error = %v", err)
}
}
func TestReadPaddingTurnRejectsTruncatedBody(t *testing.T) {
turn := paddingTurn{direction: paddingClientToServer, minLength: 64, maxLength: 64}
data := encodePaddingLength(t, 64)
if err := readPaddingTurn(bytes.NewReader(data), turn, 0); err == nil || !strings.Contains(err.Error(), "body") {
t.Fatalf("error = %v", err)
}
}
func TestReadPaddingTurnHonorsConnectionTimeout(t *testing.T) {
client, server := net.Pipe()
defer client.Close()
defer server.Close()
if err := server.SetReadDeadline(time.Now().Add(20 * time.Millisecond)); err != nil {
t.Fatal(err)
}
turn := paddingTurn{direction: paddingClientToServer, minLength: 64, maxLength: 64}
err := readPaddingTurn(server, turn, 0)
var netErr net.Error
if !errors.As(err, &netErr) || !netErr.Timeout() {
t.Fatalf("error = %v, want network timeout", err)
}
}
func TestValidatePaddingSchedule(t *testing.T) {
tests := []struct {
name string
schedule []paddingTurn
prefix int
}{
{name: "empty"},
{name: "bad direction", schedule: []paddingTurn{{direction: 99, minLength: 4, maxLength: 4}}},
{name: "too small", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 0, maxLength: 4}}},
{name: "reversed range", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 7}}},
{name: "wrong first direction", prefix: 3, schedule: []paddingTurn{{direction: paddingServerToClient, minLength: 8, maxLength: 8}}},
{name: "prefix leaves no header", prefix: 8, schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8}}},
{name: "same direction", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8}, {direction: paddingClientToServer, minLength: 8, maxLength: 8}}},
{name: "range with variants", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, variants: []paddingVariant{paddingVariantFromChunks(8)}}}},
{name: "empty variant", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{{}}}}},
{name: "bad chunk", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(maxPaddingChunkLength + 1)}}}},
{
name: "delay mismatch",
schedule: []paddingTurn{{
direction: paddingClientToServer,
variants: []paddingVariant{{
chunks: []int{4, 4},
delays: []paddingDelayRange{{min: time.Millisecond, max: time.Millisecond}},
}},
}},
},
{name: "reversed start delay", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, startDelay: paddingDelayRange{min: 2 * time.Millisecond, max: time.Millisecond}}}},
{name: "reversed generated chunk delay", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, chunkDelay: paddingDelayRange{min: 2 * time.Millisecond, max: time.Millisecond}}}},
{name: "oversized generated chunk", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, writeChunkLength: maxPaddingChunkLength + 1}}},
{name: "reversed generated chunk range", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, writeChunkMinLength: 9, writeChunkLength: 8}}},
{name: "variant with generated chunks", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8)}, writeChunkLength: 8}}},
{name: "send range outside accepted range", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 16, sendMinLength: 7, sendMaxLength: 12}}},
{name: "variant with send range", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8)}, sendMinLength: 8, sendMaxLength: 8}}},
{name: "negative chunk delay", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{{chunks: []int{8}, delays: []paddingDelayRange{{min: -time.Millisecond}}}}}}},
{name: "bad send variant", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8)}, sendVariants: []int{1}}}},
{name: "prefix splits chunk", prefix: 3, schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8, 4)}}}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if err := validatePaddingSchedule(test.schedule, test.prefix); err == nil {
t.Fatal("expected invalid padding schedule")
}
})
}
}
func TestPaddingSchedule2612MatchesCapturedTemplates(t *testing.T) {
wantDirections := []paddingDirection{
paddingClientToServer,
paddingServerToClient,
paddingClientToServer,
paddingServerToClient,
paddingClientToServer,
paddingServerToClient,
}
wantLengths := [][]int{
{44},
{72},
{25},
{41172},
{2},
{7464, 8267, 8790, 8153, 7375, 7347, 8184, 6633, 7670, 8241, 7857, 7254, 8407, 8283, 6804, 8177, 8177, 7929, 8296, 8177},
}
if len(paddingSchedule2612) != len(wantDirections)+33 {
t.Fatalf("padding schedule has %d turns, want %d", len(paddingSchedule2612), len(wantDirections)+33)
}
for i, turn := range paddingSchedule2612[:len(wantDirections)] {
if turn.direction != wantDirections[i] {
t.Fatalf("padding turn %d direction = %d, want %d", i, turn.direction, wantDirections[i])
}
if len(turn.variants) != len(wantLengths[i]) {
t.Fatalf("padding turn %d has %d variants, want %d", i, len(turn.variants), len(wantLengths[i]))
}
for j, variant := range turn.variants {
if got := paddingVariantLength(variant); got != wantLengths[i][j] {
t.Fatalf("padding turn %d variant %d length = %d, want %d", i, j, got, wantLengths[i][j])
}
}
}
wantPlayBounds := [][2]int{
{6, 883},
{346, 58638},
{6, 887},
{388, 61077},
{2, 50},
{575, 65584},
{6, 45},
{86, 63563},
{2, 44},
{42, 51983},
{2, 851},
{309, 25083},
{2, 19},
{74, 63885},
{8, 24},
{30, 66128},
{2, 19},
{26, 35818},
{6, 19},
{35, 59407},
{6, 19},
{37, 65328},
{2, 19},
{26, 60622},
{6, 19},
{11, 60808},
{8, 43},
{55, 62027},
{2, 19},
{427, 65622},
{5, 19},
{35, 59401},
{6, 19},
}
for i, want := range wantPlayBounds {
turn := paddingSchedule2612[len(wantDirections)+i]
wantDirection := paddingClientToServer
if i%2 == 1 {
wantDirection = paddingServerToClient
}
if turn.direction != wantDirection {
t.Fatalf("play turn %d direction = %d, want %d", i, turn.direction, wantDirection)
}
if turn.minLength != want[0] || turn.maxLength != want[1] {
t.Fatalf("play turn %d bounds = %d-%d, want %d-%d", i, turn.minLength, turn.maxLength, want[0], want[1])
}
if len(turn.variants) != 0 {
t.Fatalf("play turn %d unexpectedly has captured variants", i)
}
}
if got := len(paddingSchedule2612[3].variants[0].chunks); got != 30 {
t.Fatalf("registry turn chunks = %d, want 30", got)
}
minimumPlayStart := maxPaddingTurnLength
maximumPlayStart := 0
for _, variant := range paddingSchedule2612[5].variants {
length := paddingVariantLength(variant)
minimumPlayStart = min(minimumPlayStart, length)
maximumPlayStart = max(maximumPlayStart, length)
if variant.chunks[0] != 4941 {
t.Fatalf("play start first chunk = %d, want 4941", variant.chunks[0])
}
}
if minimumPlayStart != 6633 || maximumPlayStart != 8790 {
t.Fatalf("play start bounds = %d-%d, want 6633-8790", minimumPlayStart, maximumPlayStart)
}
if err := validatePaddingSchedule(paddingSchedule2612, 2); err != nil {
t.Fatalf("captured schedule is invalid: %v", err)
}
serverSchedule, err := newServerPaddingSchedule2612()
if err != nil {
t.Fatal(err)
}
if err = validatePaddingSchedule(serverSchedule, 2); err != nil {
t.Fatalf("server schedule is invalid: %v", err)
}
for i, branches := range serverPlayBranches2612 {
turn := serverSchedule[len(startupPaddingSchedule2612)+1+i*2]
got := paddingLengthRange2612{turn.sendMinLength, turn.sendMaxLength}
if got != branches.small && got != branches.large {
t.Fatalf("server play turn %d send range = %v, want %v or %v", i, got, branches.small, branches.large)
}
}
for range 20 {
clientSchedule, clientErr := newClientPaddingSchedule2612()
if clientErr != nil {
t.Fatal(clientErr)
}
if clientErr = validatePaddingSchedule(clientSchedule, 2); clientErr != nil {
t.Fatalf("client schedule is invalid: %v", clientErr)
}
burstCount := 0
for _, burst := range clientPlayBursts2612 {
turn := clientSchedule[len(startupPaddingSchedule2612)+burst.playIndex]
got := paddingLengthRange2612{turn.sendMinLength, turn.sendMaxLength}
switch got {
case burst.regular:
case burst.burst:
burstCount++
default:
t.Fatalf("client play turn %d send range = %v", burst.playIndex, got)
}
}
if burstCount != 1 {
t.Fatalf("client schedule has %d initialization bursts, want 1", burstCount)
}
}
for variantIndex := range paddingSchedule2612[3].variants {
turn := paddingSchedule2612[3]
turn.sendVariants = []int{variantIndex}
var encoded bytes.Buffer
if err = writePaddingTurnWithSleep(&encoded, turn, 0, func(time.Duration) {}); err != nil {
t.Fatal(err)
}
if err = readPaddingTurn(bytes.NewReader(encoded.Bytes()), paddingSchedule2612[3], 0); err != nil {
t.Fatalf("registry variant %d was rejected: %v", variantIndex, err)
}
}
}
func TestPaddingVariantPreservesWriteBoundaries(t *testing.T) {
tests := []struct {
name string
turn paddingTurn
prefix int
want []int
}{
{name: "login acknowledged turn", turn: paddingSchedule2612[0], prefix: 2, want: []int{26, 16}},
{name: "server response turn", turn: paddingSchedule2612[1], want: []int{26, 21, 25}},
{name: "single packet turn", turn: paddingSchedule2612[2], want: []int{25}},
{name: "fixed registry profile", turn: paddingSchedule2612[3], want: paddingSchedule2612[3].variants[0].chunks},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var writer recordingWriter
if err := writePaddingTurnWithSleep(&writer, test.turn, test.prefix, func(time.Duration) {}); err != nil {
t.Fatal(err)
}
if len(writer.writes) != len(test.want) {
t.Fatalf("writes = %v, want %v", writer.writes, test.want)
}
for i := range test.want {
if writer.writes[i] != test.want[i] {
t.Fatalf("writes = %v, want %v", writer.writes, test.want)
}
}
if err := readPaddingTurn(bytes.NewReader(writer.Bytes()), test.turn, test.prefix); err != nil {
t.Fatal(err)
}
})
}
}
func TestPaddingVariantAppliesPacing(t *testing.T) {
turn := paddingTurn{
direction: paddingClientToServer,
startDelay: paddingDelayRange{min: 3 * time.Millisecond, max: 3 * time.Millisecond},
variants: []paddingVariant{{
chunks: []int{3, 5, 7},
delays: []paddingDelayRange{
{},
{min: 2 * time.Millisecond, max: 2 * time.Millisecond},
{min: 4 * time.Millisecond, max: 4 * time.Millisecond},
},
}},
}
var slept []time.Duration
var writer recordingWriter
if err := writePaddingTurnWithSleep(&writer, turn, 3, func(delay time.Duration) {
slept = append(slept, delay)
}); err != nil {
t.Fatal(err)
}
want := []time.Duration{3 * time.Millisecond, 2 * time.Millisecond, 4 * time.Millisecond}
if len(slept) != len(want) {
t.Fatalf("delays = %v, want %v", slept, want)
}
for i := range want {
if slept[i] != want[i] {
t.Fatalf("delays = %v, want %v", slept, want)
}
}
}
func TestGeneratedPaddingChunksApplyPacing(t *testing.T) {
turn := paddingTurn{
direction: paddingServerToClient,
minLength: 100,
maxLength: 100,
writeChunkLength: 32,
chunkDelay: paddingDelayRange{min: 2 * time.Millisecond, max: 2 * time.Millisecond},
}
var slept []time.Duration
var writer recordingWriter
if err := writePaddingTurnWithSleep(&writer, turn, 0, func(delay time.Duration) {
slept = append(slept, delay)
}); err != nil {
t.Fatal(err)
}
wantWrites := []int{32, 32, 32, 4}
if !slicesEqual(writer.writes, wantWrites) {
t.Fatalf("writes = %v, want %v", writer.writes, wantWrites)
}
wantSleeps := []time.Duration{2 * time.Millisecond, 2 * time.Millisecond, 2 * time.Millisecond}
if !slicesEqual(slept, wantSleeps) {
t.Fatalf("delays = %v, want %v", slept, wantSleeps)
}
if err := readPaddingTurn(bytes.NewReader(writer.Bytes()), turn, 0); err != nil {
t.Fatal(err)
}
}
func TestGeneratedPaddingChunkLengthIsRandomized(t *testing.T) {
turn := paddingTurn{
direction: paddingServerToClient,
minLength: 100,
maxLength: 100,
writeChunkMinLength: 16,
writeChunkLength: 32,
}
seen := make(map[int]bool)
for range 100 {
var writer recordingWriter
if err := writePaddingTurnWithSleep(&writer, turn, 0, func(time.Duration) {}); err != nil {
t.Fatal(err)
}
firstWrite := writer.writes[0]
if firstWrite < turn.writeChunkMinLength || firstWrite > turn.writeChunkLength {
t.Fatalf("first write = %d", firstWrite)
}
seen[firstWrite] = true
}
if len(seen) < 2 {
t.Fatalf("generated write chunk length did not vary: %v", seen)
}
}
func TestPaddingDelayRangeIsRandomized(t *testing.T) {
delayRange := millisecondRange(25, 40)
seen := make(map[time.Duration]bool)
for range 100 {
delay, err := randomPaddingDelay(delayRange)
if err != nil {
t.Fatal(err)
}
if delay < delayRange.min || delay > delayRange.max {
t.Fatalf("delay = %s, want %s-%s", delay, delayRange.min, delayRange.max)
}
seen[delay] = true
}
if len(seen) < 2 {
t.Fatalf("padding delay did not vary: %v", seen)
}
}
func TestPaddingSchedule2612UsesCoarseTimingBands(t *testing.T) {
assertDelayRange(t, "turn 3 to 4", paddingSchedule2612[3].startDelay, 20*time.Millisecond, 50*time.Millisecond)
assertDelayRange(t, "turn 5 to 6", paddingSchedule2612[5].startDelay, 35*time.Millisecond, 50*time.Millisecond)
assertDelayRange(t, "first play client turn", paddingSchedule2612[6].startDelay, time.Millisecond, 30*time.Millisecond)
assertDelayRange(t, "first play server turn", paddingSchedule2612[7].startDelay, time.Millisecond, 45*time.Millisecond)
assertDelayRange(t, "play server chunk pacing", paddingSchedule2612[7].chunkDelay, time.Millisecond, 4*time.Millisecond)
if paddingSchedule2612[6].writeChunkLength != 1024 {
t.Fatalf("play client write chunk = %d, want 1024", paddingSchedule2612[6].writeChunkLength)
}
if paddingSchedule2612[7].writeChunkLength != maxPaddingChunkLength {
t.Fatalf("play server write chunk = %d, want %d", paddingSchedule2612[7].writeChunkLength, maxPaddingChunkLength)
}
if paddingSchedule2612[7].writeChunkMinLength != 32*1024 {
t.Fatalf("play server minimum write chunk = %d, want %d", paddingSchedule2612[7].writeChunkMinLength, 32*1024)
}
for i, variant := range paddingSchedule2612[3].variants {
minimum, maximum := paddingVariantDelayBounds(variant)
if minimum != 45*time.Millisecond || maximum != 65*time.Millisecond {
t.Fatalf("turn 4 variant %d duration = %s-%s, want 45ms-65ms", i, minimum, maximum)
}
}
for i, variant := range paddingSchedule2612[5].variants {
minimum, maximum := paddingVariantDelayBounds(variant)
if minimum != 10*time.Millisecond || maximum != 25*time.Millisecond {
t.Fatalf("turn 6 variant %d duration = %s-%s, want 10ms-25ms", i, minimum, maximum)
}
}
}
func assertDelayRange(t *testing.T, name string, got paddingDelayRange, minimum, maximum time.Duration) {
t.Helper()
if got.min != minimum || got.max != maximum {
t.Fatalf("%s delay = %s-%s, want %s-%s", name, got.min, got.max, minimum, maximum)
}
}
func paddingVariantDelayBounds(variant paddingVariant) (time.Duration, time.Duration) {
var minimum time.Duration
var maximum time.Duration
for _, delay := range variant.delays {
minimum += delay.min
maximum += delay.max
}
return minimum, maximum
}
func slicesEqual[T comparable](left, right []T) bool {
if len(left) != len(right) {
return false
}
for i := range left {
if left[i] != right[i] {
return false
}
}
return true
}
func encodePaddingLength(t *testing.T, length int) []byte {
t.Helper()
var encoded bytes.Buffer
value := Varint(length)
if err := value.writeTo(&encoded); err != nil {
t.Fatal(err)
}
return encoded.Bytes()
}
type oneByteReader struct {
reader io.Reader
}
func (r *oneByteReader) Read(p []byte) (int, error) {
if len(p) > 1 {
p = p[:1]
}
return r.reader.Read(p)
}
type recordingWriter struct {
bytes.Buffer
writes []int
}
func (w *recordingWriter) Write(p []byte) (int, error) {
w.writes = append(w.writes, len(p))
return w.Buffer.Write(p)
}
@@ -1,33 +0,0 @@
package xmc
import (
"bytes"
"testing"
)
func TestProfilesFromConfigRejectsEmpty(t *testing.T) {
if _, err := profilesFromConfig(nil); err == nil {
t.Fatal("expected empty profiles error")
}
}
func TestProfilesFromConfig(t *testing.T) {
uuid := bytes.Repeat([]byte{0x2a}, 16)
profiles, err := profilesFromConfig([]*Profile{
{
Username: "SignedUser",
Uuid: uuid,
TexturesValue: "textures-value",
TexturesSignature: "textures-signature",
},
})
if err != nil {
t.Fatalf("build explicit profile: %v", err)
}
if len(profiles) != 1 || profiles[0].Username != "SignedUser" {
t.Fatalf("unexpected profile: %+v", profiles)
}
if profiles[0].TexturesValue != "textures-value" || profiles[0].TexturesSignature != "textures-signature" {
t.Fatalf("textures were not preserved: %+v", profiles[0])
}
}
+5 -1
View File
@@ -8,7 +8,11 @@ import (
) )
const ( const (
maxPacketDataLength = 32 * 1024 // Clientbound custom payloads are allowed up to 1 MiB by vanilla, and a
// vanilla configuration state can send large registry data packets. This is
// only an upper bound for decoding; the XMC payload stream keeps its own,
// much smaller, chunk size.
maxPacketDataLength = 1024 * 1024
maxPacketBodyLength = maxPacketDataLength + 5 maxPacketBodyLength = maxPacketDataLength + 5
) )
@@ -1,56 +0,0 @@
package xmc
import (
"bytes"
"strings"
"testing"
)
func TestReadPacketDoesNotConsumeFollowingPacket(t *testing.T) {
data := []byte{0x01, 0x80, 0x01, 0x00}
r := bytes.NewReader(data)
if _, err := readPacket(r); err == nil {
t.Fatal("expected truncated packet ID to fail")
}
pkt, err := readPacket(r)
if err != nil {
t.Fatalf("read following packet: %v", err)
}
if pkt.packetID != 0 {
t.Fatalf("packet ID = %d", pkt.packetID)
}
}
func TestPacketWithLengthReportsWireBytes(t *testing.T) {
var wire bytes.Buffer
written, err := writePacketWithLength(&wire, 0x03)
if err != nil {
t.Fatal(err)
}
if written != 2 || !bytes.Equal(wire.Bytes(), []byte{0x01, 0x03}) {
t.Fatalf("wire = %x, length = %d", wire.Bytes(), written)
}
packet, read, err := readPacketWithLength(bytes.NewReader(wire.Bytes()))
if err != nil {
t.Fatal(err)
}
if packet.packetID != 0x03 || read != written {
t.Fatalf("packet ID = %d, read = %d, written = %d", packet.packetID, read, written)
}
}
func TestReadPacketRejectsNonCanonicalLengthVarint(t *testing.T) {
_, _, err := readPacketWithLength(bytes.NewReader([]byte{0x81, 0x00, 0x03}))
if err == nil || !strings.Contains(err.Error(), "non-canonical") {
t.Fatalf("error = %v", err)
}
}
func TestVarintRejectsOversizedFifthByte(t *testing.T) {
var value Varint
err := value.readFrom(bytes.NewReader([]byte{0xff, 0xff, 0xff, 0xff, 0x1f}))
if err == nil || !strings.Contains(err.Error(), "too large") {
t.Fatalf("error = %v", err)
}
}
+14 -6
View File
@@ -41,6 +41,9 @@ type serverConn struct {
paddingSchedule []paddingTurn paddingSchedule []paddingTurn
packet *packetStream packet *packetStream
deadlines *connectionDeadlines deadlines *connectionDeadlines
done chan struct{}
closeOnce sync.Once
} }
func (c *serverConn) handshake() error { func (c *serverConn) handshake() error {
@@ -245,7 +248,9 @@ func (c *serverConn) handshake() error {
if err = validateLoginAcknowledgedPacket(pkt); err != nil { if err = validateLoginAcknowledgedPacket(pkt); err != nil {
return err return err
} }
if err = runPaddingSchedule(c.reader, c.writer, false, loginAcknowledgedLength, c.paddingSchedule); err != nil { 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.
return fmt.Errorf("run startup padding: %w", err) return fmt.Errorf("run startup padding: %w", err)
} }
@@ -302,12 +307,18 @@ func (c *serverConn) Close() error {
c.closed = true c.closed = true
packet := c.packet packet := c.packet
c.lifecycleMu.Unlock() c.lifecycleMu.Unlock()
c.closeOnce.Do(func() { close(c.done) })
if packet != nil { if packet != nil {
packet.Stop() packet.Stop()
} }
return c.c.Close() 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 { func (c *serverConn) LocalAddr() net.Addr {
return c.c.LocalAddr() return c.c.LocalAddr()
} }
@@ -328,7 +339,7 @@ func (c *serverConn) SetWriteDeadline(t time.Time) error {
return c.deadlines.setWriteDeadline(t) return c.deadlines.setWriteDeadline(t)
} }
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte) (*serverConn, error) { func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, paddingSchedule []paddingTurn) (*serverConn, error) {
if len(profiles) == 0 { if len(profiles) == 0 {
return nil, fmt.Errorf("empty profiles") return nil, fmt.Errorf("empty profiles")
} }
@@ -342,10 +353,6 @@ func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPri
if err != nil { if err != nil {
return nil, fmt.Errorf("parse rsa private key: %w", err) return nil, fmt.Errorf("parse rsa private key: %w", err)
} }
paddingSchedule, err := newServerPaddingSchedule2612()
if err != nil {
return nil, fmt.Errorf("select padding profile: %w", err)
}
s := &serverConn{ s := &serverConn{
reader: bufio.NewReader(c), reader: bufio.NewReader(c),
@@ -358,6 +365,7 @@ func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPri
rsaPublicKey: rsaPublicKey, rsaPublicKey: rsaPublicKey,
paddingSchedule: paddingSchedule, paddingSchedule: paddingSchedule,
deadlines: newConnectionDeadlines(c), deadlines: newConnectionDeadlines(c),
done: make(chan struct{}),
} }
return s, nil return s, nil
@@ -1,81 +0,0 @@
package xmc
import (
"bytes"
"io"
"testing"
)
type dataAndEOFReader struct {
data []byte
}
func (r *dataAndEOFReader) Read(p []byte) (int, error) {
if len(r.data) == 0 {
return 0, io.EOF
}
n := copy(p, r.data)
r.data = r.data[n:]
return n, io.EOF
}
type shortWriter struct {
bytes.Buffer
}
func (w *shortWriter) Write(p []byte) (int, error) {
if len(p) > 1 {
p = p[:len(p)/2]
}
return w.Buffer.Write(p)
}
func TestCryptoReaderPreservesDataReturnedWithEOF(t *testing.T) {
secret := []byte("0123456789abcdef")
plaintext := []byte("payload returned with EOF")
var encrypted bytes.Buffer
writer, err := newCryptoWriter(&encrypted, secret)
if err != nil {
t.Fatal(err)
}
if _, err = writer.Write(plaintext); err != nil {
t.Fatal(err)
}
reader, err := newCryptoReader(&dataAndEOFReader{data: encrypted.Bytes()}, secret)
if err != nil {
t.Fatal(err)
}
got := make([]byte, len(plaintext))
n, err := reader.Read(got)
if err == nil || n != len(plaintext) {
t.Fatalf("Read = %d, %v", n, err)
}
if !bytes.Equal(got[:n], plaintext) {
t.Fatalf("plaintext = %q", got[:n])
}
}
func TestCryptoWriterHandlesShortWrites(t *testing.T) {
secret := []byte("0123456789abcdef")
plaintext := bytes.Repeat([]byte("short-write"), 100)
var dst shortWriter
writer, err := newCryptoWriter(&dst, secret)
if err != nil {
t.Fatal(err)
}
if n, err := writer.Write(plaintext); err != nil || n != len(plaintext) {
t.Fatalf("Write = %d, %v", n, err)
}
reader, err := newCryptoReader(bytes.NewReader(dst.Bytes()), secret)
if err != nil {
t.Fatal(err)
}
got, err := io.ReadAll(reader)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, plaintext) {
t.Fatal("decrypted payload mismatch")
}
}
+1 -1
View File
@@ -91,7 +91,7 @@ func (h *HunkReaderWriter) ReadMultiBuffer() (buf.MultiBuffer, error) {
} }
} }
if cap(h.buf) >= buf.Size { if len(h.buf) == buf.Size {
b := h.buf b := h.buf
h.index = len(h.buf) h.index = len(h.buf)
return buf.MultiBuffer{buf.NewExisted(b)}, nil return buf.MultiBuffer{buf.NewExisted(b)}, nil
@@ -74,14 +74,10 @@ func (h *MultiHunkReaderWriter) ReadMultiBuffer() (buf.MultiBuffer, error) {
continue continue
} }
if cap(b) >= buf.Size { if len(b) == buf.Size {
mb = append(mb, buf.NewExisted(b)) mb = append(mb, buf.NewExisted(b))
} else { } else {
nb := buf.New() mb = buf.MergeBytes(mb, b)
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.sxport[0], nl.sxport[1] = byte(raPort>>8), byte(raPort)
nl.dxport[0], nl.dxport[1] = byte(laPort>>8), byte(laPort) 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 { if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, fd, DIOCNATLOOK, uintptr(unsafe.Pointer(&nl))); errno != 0 {
return net.IP{}, -1, os.NewSyscallError("ioctl", err) return net.IP{}, -1, os.NewSyscallError("ioctl", errno)
} }
odPort := nl.rdxport odPort := nl.rdxport
+3
View File
@@ -227,6 +227,9 @@ func createHTTPClient(dest net.Destination, streamSettings *internet.MemoryStrea
conn, err := tr.DialEarly(ctx, udpAddr, tlsCfg, cfg) conn, err := tr.DialEarly(ctx, udpAddr, tlsCfg, cfg)
if err != nil { 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 return nil, err
} }
context.AfterFunc(conn.Context(), func() { tr.Close(); pktConn.Close() }) context.AfterFunc(conn.Context(), func() { tr.Close(); pktConn.Close() })
+8 -7
View File
@@ -270,18 +270,12 @@ var PresetFingerprints = map[string]*utls.ClientHelloID{
var ModernFingerprints = map[string]*utls.ClientHelloID{ var ModernFingerprints = map[string]*utls.ClientHelloID{
// One of these will be chosen as `random` at startup // One of these will be chosen as `random` at startup
"hellofirefox_120": &utls.HelloFirefox_120, // All of them must have X25519MLKEM768 before optional X25519, otherwise REALITY servers (since v26.9.9) will reject them
"hellofirefox_148": &utls.HelloFirefox_148, "hellofirefox_148": &utls.HelloFirefox_148,
"hellochrome_120": &utls.HelloChrome_120,
"hellochrome_131": &utls.HelloChrome_131, "hellochrome_131": &utls.HelloChrome_131,
"hellochrome_133": &utls.HelloChrome_133, "hellochrome_133": &utls.HelloChrome_133,
"hellochrome_155": &utls.HelloChrome_155, "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, "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{ var OtherFingerprints = map[string]*utls.ClientHelloID{
@@ -298,6 +292,7 @@ var OtherFingerprints = map[string]*utls.ClientHelloID{
"hellofirefox_99": &utls.HelloFirefox_99, "hellofirefox_99": &utls.HelloFirefox_99,
"hellofirefox_102": &utls.HelloFirefox_102, "hellofirefox_102": &utls.HelloFirefox_102,
"hellofirefox_105": &utls.HelloFirefox_105, "hellofirefox_105": &utls.HelloFirefox_105,
"hellofirefox_120": &utls.HelloFirefox_120,
"hellochrome_auto": &utls.HelloChrome_Auto, "hellochrome_auto": &utls.HelloChrome_Auto,
"hellochrome_58": &utls.HelloChrome_58, "hellochrome_58": &utls.HelloChrome_58,
"hellochrome_62": &utls.HelloChrome_62, "hellochrome_62": &utls.HelloChrome_62,
@@ -309,17 +304,23 @@ var OtherFingerprints = map[string]*utls.ClientHelloID{
"hellochrome_100": &utls.HelloChrome_100, "hellochrome_100": &utls.HelloChrome_100,
"hellochrome_102": &utls.HelloChrome_102, "hellochrome_102": &utls.HelloChrome_102,
"hellochrome_106_shuffle": &utls.HelloChrome_106_Shuffle, "hellochrome_106_shuffle": &utls.HelloChrome_106_Shuffle,
"hellochrome_120": &utls.HelloChrome_120,
"helloios_auto": &utls.HelloIOS_Auto, "helloios_auto": &utls.HelloIOS_Auto,
"helloios_11_1": &utls.HelloIOS_11_1, "helloios_11_1": &utls.HelloIOS_11_1,
"helloios_12_1": &utls.HelloIOS_12_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, "helloandroid_11_okhttp": &utls.HelloAndroid_11_OkHttp,
"helloedge_85": &utls.HelloEdge_85, "helloedge_85": &utls.HelloEdge_85,
"helloedge_106": &utls.HelloEdge_106,
"helloedge_auto": &utls.HelloEdge_Auto, "helloedge_auto": &utls.HelloEdge_Auto,
"hellosafari_16_0": &utls.HelloSafari_16_0, "hellosafari_16_0": &utls.HelloSafari_16_0,
"hellosafari_auto": &utls.HelloSafari_Auto, "hellosafari_auto": &utls.HelloSafari_Auto,
"hello360_auto": &utls.Hello360_Auto, "hello360_auto": &utls.Hello360_Auto,
"hello360_7_5": &utls.Hello360_7_5, "hello360_7_5": &utls.Hello360_7_5,
"hello360_11_0": &utls.Hello360_11_0,
"helloqq_auto": &utls.HelloQQ_Auto, "helloqq_auto": &utls.HelloQQ_Auto,
"helloqq_11_1": &utls.HelloQQ_11_1,
// Chrome betas // Chrome betas
"hellochrome_100_psk": &utls.HelloChrome_100_PSK, "hellochrome_100_psk": &utls.HelloChrome_100_PSK,
+7 -5
View File
@@ -5,6 +5,7 @@ import (
goerrors "errors" goerrors "errors"
"io" "io"
"sync" "sync"
"sync/atomic"
"time" "time"
"github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common"
@@ -24,7 +25,7 @@ type connEntry struct {
link *transport.Link link *transport.Link
timer *signal.ActivityTimer timer *signal.ActivityTimer
cancel context.CancelFunc cancel context.CancelFunc
closed bool closed atomic.Bool
} }
func (c *connEntry) Close() error { func (c *connEntry) Close() error {
@@ -33,10 +34,9 @@ func (c *connEntry) Close() error {
} }
func (c *connEntry) terminate() { func (c *connEntry) terminate() {
if c.closed { if c.closed.Swap(true) {
panic("terminate called more than once") panic("terminate called more than once")
} }
c.closed = true
c.cancel() c.cancel()
common.Interrupt(c.link.Reader) common.Interrupt(c.link.Reader)
common.Interrupt(c.link.Writer) 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 != nil {
if v.conn.closed { if v.conn.closed.Load() {
v.conn = nil v.conn = nil
} else { } else {
return v.conn, nil return v.conn, nil
@@ -144,7 +144,9 @@ func handleInput(ctx context.Context, conn *connEntry, dest net.Destination, cal
mb, err := input.ReadMultiBuffer() mb, err := input.ReadMultiBuffer()
if err != nil { if err != nil {
if !goerrors.Is(err, io.EOF) { if conn.closed.Load() {
errors.LogDebugInner(ctx, err, "UDP input closed locally")
} else if !goerrors.Is(err, io.EOF) {
errors.LogInfoInner(ctx, err, "failed to handle UDP input") errors.LogInfoInner(ctx, err, "failed to handle UDP input")
} }
return return