diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b199184..f5d70e7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -79,7 +79,13 @@ jobs: run: go test -count=1 -timeout=3m -shuffle=on -coverprofile=coverage.out ./... - name: Native capability report shell: bash - run: go test -count=1 -timeout=2m -run 'Capabilities|ProbeConn|SplitAck|TCPInfo|Getsockopt' -v . + run: go test -count=1 -timeout=2m -run 'Capabilities|ProbeConn|SplitAck|TCPInfo|Getsockopt|SocketMethod|OOB|Disorder|LinuxFake|LowHop|UDPFake' -v . + # The drop filter that makes the server discard low-hop segments needs + # root on the runners; without root the test skips itself. + - name: Low-hop drop test (root) + if: runner.os == 'Linux' + shell: bash + run: sudo env "PATH=$PATH" GOTOOLCHAIN="$GOTOOLCHAIN" GOWORK="$GOWORK" GOFLAGS="$GOFLAGS" DESYNC_REQUIRE_LOWHOP=1 go test -count=1 -timeout=2m -run '^TestLinuxLowHopDropRetransmitsOriginal$' -v . - name: Coverage summary if: always() && hashFiles('coverage.out') != '' shell: bash diff --git a/README.md b/README.md index ed4ed2c..a7d46c9 100644 --- a/README.md +++ b/README.md @@ -26,10 +26,12 @@ A filter on the path and the destination server can read the same bytes differen | TLS record fragmentation (`TLSRec`) | Splits the ClientHello into several valid TLS records | ✓ | ✓ | ✓ | | TCP write splitting (`Split`, `SplitDelay`) | Sends the ClientHello in separate writes, optionally with a pause | ✓ | ✓ | ✓ | | Split wait (`SplitWait`) | Before each further piece, waits until the kernel reports the previous bytes as sent or acknowledged | sent, acked¹ | sent, acked | acked | -| Low-TTL fake prefix (`Fake`) | First transmission of a prefix carries other bytes with a short hop limit; a retransmission carries the original | ✓ | — | — | -| Low-TTL UDP burst (`WrapPacketConn`) | Bounded low-TTL datagrams before the first datagrams to each peer; originals are unchanged | ✓ | — | — | +| Disorder (`Disorder`) | The first TCP piece goes out with hop limit 1 and expires; TCP retransmits it after the later pieces | ✓¹ | ✓ | ✓² | +| Out-of-band byte (`OOB`) | One urgent byte follows the first TCP piece; the server's TCP removes it from the stream | ✓ | ✓ | ✓ | +| Low-TTL fake prefix (`Fake`) | First transmission of a prefix carries other bytes with a short hop limit; a retransmission carries the original | ✓ | ✓ | —³ | +| Low-TTL UDP burst (`WrapPacketConn`) | Bounded low-TTL datagrams before the first datagrams to each peer; originals are unchanged | ✓ | ✓ | ✓ | -¹ Inferred from counters, not reliable; see [platform capabilities](#platform-capabilities-and-split-wait). +Linux includes Android. ¹ Inferred from counters, not reliable; see [platform capabilities](#platform-capabilities-and-split-wait). ² The transmission before the hop limit is restored is inferred, not observed; see [disorder](#disorder-and-out-of-band-byte). ³ Not implementable: macOS cannot make a retransmission carry other bytes than the first transmission; see [connection I/O](docs/connection-io.md#macos-tcp-fake). Only a connection that starts with a TLS ClientHello is transformed. Any other traffic, and everything after the ClientHello, passes through untouched. Unsupported methods return an explicit error, never a silent fallback to another method. `PlatformCapabilities()` reports what this build implements on the current OS, and `ProbeConn` checks an actual socket. @@ -102,9 +104,14 @@ A ClientHello may arrive across several records and `Write` calls. Assembly is b ```go caps := desync.PlatformCapabilities() -// windows: {FakeTCP:true FakeUDP:true TTLControl:true Ack:{Mechanism:SIO_TCP_INFO Sent:true Acked:true Reliable:false}} -// linux: {Ack:{Mechanism:SIOCOUTQ/SIOCOUTQNSD Sent:true Acked:true Reliable:true}} -// darwin: {Ack:{Mechanism:SO_NWRITE Acked:true Reliable:true}} +// windows: {FakeTCP:true FakeUDP:true TTLControl:true OOB:true +// Disorder:{Supported:true Mechanism:SIO_TCP_INFO Observed:true Reliable:false} +// Ack:{Mechanism:SIO_TCP_INFO Sent:true Acked:true Reliable:false}} +// linux: {FakeTCP:true FakeUDP:true TTLControl:true OOB:true +// Disorder:{Supported:true Mechanism:SIOCOUTQNSD Observed:true Reliable:true} +// Ack:{Mechanism:SIOCOUTQ/SIOCOUTQNSD Sent:true Acked:true Reliable:true}} +// darwin: {FakeUDP:true TTLControl:true OOB:true Disorder:{Supported:true Mechanism:SO_NWRITE} +// Ack:{Mechanism:SO_NWRITE Acked:true Reliable:true} Unsupported:map[fake-tcp:no splice: ...]} opts := desync.Options{ Split: []desync.Pos{{Offset: 1, FromSNI: true}}, @@ -126,7 +133,21 @@ if err := opts.Validate(); errors.Is(err, desync.ErrSplitWaitUnsupported) { Reliable means the kernel's own queue state is read. Windows has no unsent-bytes value, so the wait compares counter growth with the bytes written; on loopback `BytesOut` exceeded the written bytes for large writes, so the wait can end early. Close, write deadlines (including changes to them) and `SplitWaitTimeout` bound every wait; a timeout returns `ErrSplitWaitTimeout` and closes the connection. Where the observation is reliable, `SplitWaitAcked` writes a piece only after every earlier byte was transmitted and acknowledged, so no segment carries bytes of two pieces; with `SplitWaitSent` a retransmission can still combine them. The OS still divides a piece into segments. Details and measurements: [connection I/O](docs/connection-io.md#split-wait), [validation](docs/validation.md#split-wait-latency-2026-10-29). -### Low-TTL fake prefix (Windows) +### Disorder and out-of-band byte + +```go +opts := desync.Options{ + Split: []desync.Pos{{Offset: 1, FromSNI: true}}, + Disorder: true, // ByeDPI --disorder + OOB: &desync.OOBOptions{}, // ByeDPI --oob; both together: --disoob +} +``` + +- Both act on the first TCP piece, so they need `Split` or `Random.Split` positions; a ClientHello where no split position resolves is written in one piece, as with `Split` alone. `TLSRec`, `SplitDelay` and `SplitWaitSent` combine with them; `Fake` does not, and `Disorder` rejects `SplitWaitAcked` (the dropped piece is acknowledged only after its retransmission). +- `Disorder` sets hop limit 1 for the first piece, so it expires at the first router. The hop limit is restored before the next piece and on every error, and TCP retransmits the piece with the normal limit after the server received the later pieces. On Linux and Windows the limit is restored only after the kernel reports the piece as transmitted (`SIOCOUTQNSD`, `SIO_TCP_INFO`), bounded by `SplitWaitTimeout` (`ErrSplitWaitTimeout`), the write deadline and `Close`. macOS cannot observe unsent bytes: the piece is written once `SO_NWRITE` reports an empty send buffer, so the kernel builds the segment inside the send call, and `Capabilities.Disorder.Observed` is false. +- `OOB` sends the first piece followed by one byte (`Byte`, default `'a'`) with `MSG_OOB`. The server's TCP takes that byte out of the stream as urgent data, so the application reads the original bytes; an inspecting device that ignores the urgent pointer sees one extra byte. A server using `SO_OOBINLINE`, or a middlebox that clears the URG flag, would put the byte into the stream and break the handshake. + +### Low-TTL fake prefix (Windows, Linux) ```go opts := desync.Options{ @@ -140,9 +161,9 @@ opts := desync.Options{ - `Payload` replaces the bytes of the first transmission; by default an embedded TLS template is used, padded or truncated to the prefix. - `Timeout` (default 3 s) bounds the native waits. Write deadlines on the wrapper bound normal writes; `Close` interrupts both. -The backend sends the prefix with `TransmitFile` from a delete-on-close temporary file, then puts the original bytes in the file cache for the retransmission and restores the socket's hop limits. Native resources are kept until the operation completes or is cancelled. An error after a transformed send is terminal for the connection. Fake can be combined with `TLSRec`, not with `Split`. +Windows sends the prefix with `TransmitFile` from a delete-on-close temporary file, then puts the original bytes in the file cache for the retransmission and restores the socket's hop limits; native resources are kept until the operation completes or is cancelled. Linux and Android `vmsplice` a shared page holding the fake bytes into a pipe and `splice` it to the socket, so the send queue references the page instead of a copy; once `SIOCOUTQNSD` reports the prefix transmitted, the page is overwritten with the original bytes, then the hop limit is restored. This needs a route whose device supports scatter-gather (loopback, Ethernet, Wi-Fi, tun and WireGuard do); otherwise the kernel copies the spliced bytes and the server receives the fake, which fails the handshake. An error after a transformed send is terminal for the connection. Fake can be combined with `TLSRec`, not with `Split`, `Disorder` or `OOB`. macOS reports it unsupported (`Capabilities.Unsupported["fake-tcp"]`). -### Low-TTL UDP burst (Windows) +### Low-TTL UDP burst (Windows, Linux, macOS) ```go pc, err := net.ListenPacket("udp", ":0") @@ -163,7 +184,7 @@ _, err = packets.WriteTo(datagram, peer) - `Repeats` (1–16, default 6) low-TTL datagrams go before each of the first `Packets` (1–8, default 3) datagrams to a peer. The default payload is 64 zero bytes. - Originals keep their content, order and source port. The hop limit is restored before every original; if it cannot be restored, the socket is closed. - Up to 64 peers per socket are tracked, with a 2-minute idle expiry; further peers pass through unchanged. -- TTL-expired ICMP replies are suppressed on the socket (`SIO_UDP_NETRESET`), so they do not surface as receive errors. +- TTL-expired ICMP replies do not surface as receive errors. Windows suppresses them on the socket (`SIO_UDP_NETRESET`); Linux reports them on an unconnected socket only with `IP_RECVERR`/`IPV6_RECVERR`, which the wrapper turns off if they were enabled; macOS never delivers them to an unconnected socket. - `Counters()` reports original and fake datagrams, errors and peers. A shared `*UDPCounters` aggregates several sockets. Counters show what was sent, not whether it helped. ## Strategy controller @@ -177,7 +198,9 @@ A minimal SOCKS5 CONNECT proxy for trying methods on a real network: ```sh go run ./cmd/desync-socks -listen 127.0.0.1:10802 -tlsrec 3+s go run ./cmd/desync-socks -listen 127.0.0.1:10802 -split 1+s -split-wait acked -go run ./cmd/desync-socks -listen 127.0.0.1:10802 -tlsrec 1+s -fake -1 -ttl 4 # Windows +go run ./cmd/desync-socks -listen 127.0.0.1:10802 -split 1+s -disorder +go run ./cmd/desync-socks -listen 127.0.0.1:10802 -split 3+s -oob -oob-byte a +go run ./cmd/desync-socks -listen 127.0.0.1:10802 -tlsrec 1+s -fake -1 -ttl 4 # Windows, Linux ``` Point the application under test at the SOCKS endpoint. It does not change system proxy settings, has no authentication and no UDP. @@ -198,4 +221,4 @@ Fuzz targets, benchmarks and what has been verified are listed in [validation](d ## License -MIT, see [LICENSE](LICENSE). The default fake TLS template comes from ByeDPI (MIT); its notice is in [third_party](third_party). +MIT, see [LICENSE](LICENSE). The default fake TLS template and the fake, disorder and out-of-band mechanisms come from ByeDPI (MIT); what was taken is listed in [third_party/NOTICE](third_party/NOTICE). diff --git a/capability.go b/capability.go index 4cda30b..cff9816 100644 --- a/capability.go +++ b/capability.go @@ -80,10 +80,17 @@ type Capabilities struct { // FakeUDP reports WrapPacketConn support (same as SupportsUDPFake). FakeUDP bool // TTLControl reports that the package changes and restores a socket's - // TTL or hop limit on this OS (used by the fake methods). + // TTL or hop limit on this OS (used by Fake, Disorder and the UDP burst). TTLControl bool + // Disorder describes Options.Disorder support. + Disorder DisorderCapability + // OOB reports Options.OOB support. + OOB bool // Ack describes send-queue / acknowledgement observation for SplitWait. Ack AckCapability + // Unsupported explains, keyed by method ("fake-tcp", "fake-udp", + // "disorder", "oob"), why a method is not implemented on this OS. + Unsupported map[string]string } // AckCapability describes how SplitWait observes a socket on this OS. @@ -114,13 +121,29 @@ func (a AckCapability) Supports(mode SplitWait) bool { // PlatformCapabilities reports what the package implements on this OS. func PlatformCapabilities() Capabilities { - return Capabilities{ - OS: runtime.GOOS, - FakeTCP: supportsFake, - FakeUDP: supportsUDPFake, - TTLControl: supportsFake || supportsUDPFake, - Ack: platformAck, + c := Capabilities{ + OS: runtime.GOOS, + FakeTCP: supportsFake, + FakeUDP: supportsUDPFake, + TTLControl: supportsFake || supportsUDPFake || platformDisorder.Supported, + Disorder: platformDisorder, + OOB: supportsOOB, + Ack: platformAck, + Unsupported: map[string]string{}, } + if !supportsFake { + c.Unsupported["fake-tcp"] = fakeUnsupportedReason + } + if !supportsUDPFake { + c.Unsupported["fake-udp"] = "not implemented on " + runtime.GOOS + } + if !platformDisorder.Supported { + c.Unsupported["disorder"] = "not implemented on " + runtime.GOOS + } + if !supportsOOB { + c.Unsupported["oob"] = "not implemented on " + runtime.GOOS + } + return c } // AckState is a snapshot of a socket's send queue. Values that the platform @@ -263,14 +286,22 @@ const ( ) // waitSplit polls obs until the configured condition holds for the written -// bytes. The poll interval starts with a few scheduler yields, then grows from -// 50 microseconds to 1 ms. Close, the write deadline (including changes to it) and -// SplitWaitTimeout bound the wait. +// bytes, bounded by SplitWaitTimeout. func (c *Conn) waitSplit(obs ackObserver, written int64) error { timeout := c.opts.SplitWaitTimeout if timeout == 0 { timeout = defaultSplitWaitTimeout } + return c.poll(timeout, ErrSplitWaitTimeout, "split wait", func() (bool, error) { + return obs.reached(c.opts.SplitWait, written) + }) +} + +// poll calls cond until it reports true. The poll interval starts with a few +// scheduler yields, then grows from 50 microseconds to 1 ms. Close, the write +// deadline (including changes to it) and timeout bound the wait; timeoutErr is +// returned when timeout expires. A cond error is wrapped with what. +func (c *Conn) poll(timeout time.Duration, timeoutErr error, what string, cond func() (bool, error)) error { end := time.Now().Add(timeout) interval := time.Duration(0) for polls := 0; ; polls++ { @@ -278,21 +309,21 @@ func (c *Conn) waitSplit(obs ackObserver, written int64) error { if err != nil { return err } - ok, err := obs.reached(c.opts.SplitWait, written) + ok, err := cond() if err != nil { select { case <-c.closed: return net.ErrClosed default: } - return fmt.Errorf("desync: split wait: %w", err) + return fmt.Errorf("desync: %s: %w", what, err) } if ok { return nil } now := time.Now() if !now.Before(end) { - return ErrSplitWaitTimeout + return timeoutErr } if polls < splitWaitSpins { runtime.Gosched() diff --git a/capability_test.go b/capability_test.go index caa8482..6bf6c97 100644 --- a/capability_test.go +++ b/capability_test.go @@ -19,19 +19,32 @@ func TestPlatformCapabilitiesPerOS(t *testing.T) { t.Fatalf("inconsistent capabilities: %+v", c) } var want AckCapability - ttl := false + var disorder DisorderCapability + ttl, oob, fakeTCP, fakeUDP := false, false, false, false switch runtime.GOOS { case "windows": want = AckCapability{Mechanism: "SIO_TCP_INFO", Sent: true, Acked: true} - ttl = true + disorder = DisorderCapability{Supported: true, Mechanism: "SIO_TCP_INFO", Observed: true} + ttl, oob, fakeTCP, fakeUDP = true, true, true, true case "linux", "android": want = AckCapability{Mechanism: "SIOCOUTQ/SIOCOUTQNSD", Sent: true, Acked: true, Reliable: true} + disorder = DisorderCapability{Supported: true, Mechanism: "SIOCOUTQNSD", Observed: true, Reliable: true} + ttl, oob, fakeTCP, fakeUDP = true, true, true, true case "darwin", "ios": want = AckCapability{Mechanism: "SO_NWRITE", Acked: true, Reliable: true} + disorder = DisorderCapability{Supported: true, Mechanism: "SO_NWRITE"} + ttl, oob, fakeUDP = true, true, true } - if c.Ack != want || c.TTLControl != ttl { - t.Fatalf("%s capabilities: %+v, want ack %+v ttl %v", runtime.GOOS, c, want, ttl) + if c.Ack != want || c.TTLControl != ttl || c.Disorder != disorder || c.OOB != oob || c.FakeTCP != fakeTCP || c.FakeUDP != fakeUDP { + t.Fatalf("%s capabilities: %+v, want ack %+v disorder %+v ttl %v oob %v fake %v/%v", runtime.GOOS, c, want, disorder, ttl, oob, fakeTCP, fakeUDP) } + // Every method this OS lacks is explained, and nothing it implements is. + for name, missing := range map[string]bool{"fake-tcp": !c.FakeTCP, "fake-udp": !c.FakeUDP, "disorder": !c.Disorder.Supported, "oob": !c.OOB} { + if reason, ok := c.Unsupported[name]; ok != missing || ok && reason == "" { + t.Fatalf("%s: unsupported reason %q (present %v), want present %v", name, reason, ok, missing) + } + } + t.Logf("%s capabilities: %+v", runtime.GOOS, c) if !c.Ack.Supports(SplitWaitNone) || c.Ack.Supports(SplitWait(9)) { t.Fatal("Supports: wrong result for none/unknown") } diff --git a/cmd/desync-socks/main.go b/cmd/desync-socks/main.go index 184904a..b35197c 100644 --- a/cmd/desync-socks/main.go +++ b/cmd/desync-socks/main.go @@ -6,6 +6,9 @@ // desync-socks -listen 127.0.0.1:10802 -tlsrec 1+s // desync-socks -tlsrec 1+s,3+s -split 1+s // desync-socks -split 1+s -split-wait acked +// desync-socks -split 1+s -disorder +// desync-socks -split 3+s -oob +// desync-socks -tlsrec 1+s -fake -1 -ttl 4 package main import ( @@ -30,13 +33,23 @@ func main() { delay := flag.Duration("split-delay", 0, "pause between TCP pieces") wait := flag.String("split-wait", "none", "before each further TCP piece, wait until the previous bytes are sent or acked: none, sent, acked") waitTimeout := flag.Duration("split-wait-timeout", 0, "bound for each split wait (0: library default)") - fake := flag.Int("fake", 0, "Windows TCP fake prefix: 0 disables, -1 means all but the last byte") + fake := flag.Int("fake", 0, "TCP fake prefix (Windows, Linux): 0 disables, -1 means all but the last byte") ttl := flag.Int("ttl", 4, "TTL for a fake initial transmission") + disorder := flag.Bool("disorder", false, "send the first TCP piece with hop limit 1 (needs -split)") + oob := flag.Bool("oob", false, "send one out-of-band byte after the first TCP piece (needs -split; with -disorder: disoob)") + oobByte := flag.String("oob-byte", "a", "the out-of-band byte: one character or a 0x-prefixed hex value (0x00 selects the default a)") fakeTimeout := flag.Duration("fake-timeout", 3*time.Second, "maximum duration of a native fake operation") verbose := flag.Bool("v", false, "log every connection") flag.Parse() - opts := desync.Options{SplitDelay: *delay, SplitWaitTimeout: *waitTimeout} + opts := desync.Options{SplitDelay: *delay, SplitWaitTimeout: *waitTimeout, Disorder: *disorder} + if *oob { + b, err := parseByte(*oobByte) + if err != nil { + log.Fatal(err) + } + opts.OOB = &desync.OOBOptions{Byte: b} + } if *fake != 0 { opts.Fake = &desync.FakeOptions{TTL: *ttl, Prefix: *fake, Timeout: *fakeTimeout} } @@ -58,7 +71,7 @@ func main() { if err != nil { log.Fatal(err) } - log.Printf("desync-socks on %s (tlsrec=%v split=%v delay=%v wait=%v fake=%d ttl=%d)", ln.Addr(), opts.TLSRec, opts.Split, *delay, opts.SplitWait, *fake, *ttl) + log.Printf("desync-socks on %s (tlsrec=%v split=%v delay=%v wait=%v disorder=%v oob=%v fake=%d ttl=%d)", ln.Addr(), opts.TLSRec, opts.Split, *delay, opts.SplitWait, *disorder, *oob, *fake, *ttl) for { c, err := ln.Accept() if err != nil { @@ -83,6 +96,21 @@ func parseList(s string) ([]desync.Pos, error) { return out, nil } +// parseByte parses one character or a 0x-prefixed hex byte. +func parseByte(s string) (byte, error) { + if strings.HasPrefix(s, "0x") { + v, err := strconv.ParseUint(s[2:], 16, 8) + if err != nil { + return 0, fmt.Errorf("bad byte %q", s) + } + return byte(v), nil + } + if len(s) != 1 { + return 0, fmt.Errorf("bad byte %q: want one character or 0xNN", s) + } + return s[0], nil +} + func handle(c net.Conn, opts desync.Options, verbose bool) { defer c.Close() _ = c.SetDeadline(time.Now().Add(15 * time.Second)) diff --git a/cmd/desync-socks/main_test.go b/cmd/desync-socks/main_test.go index c8ee4c5..87190ae 100644 --- a/cmd/desync-socks/main_test.go +++ b/cmd/desync-socks/main_test.go @@ -42,6 +42,18 @@ func socksDial(t *testing.T, proxy, host string, port int) net.Conn { } func TestSocksTunnelWithTLSRec(t *testing.T) { + socksTunnel(t, desync.Options{TLSRec: []desync.Pos{{Offset: 1, FromSNI: true}}, Split: []desync.Pos{{Offset: 1, FromSNI: true}}}) +} + +func TestSocksTunnelWithDisorderAndOOB(t *testing.T) { + opts := desync.Options{Split: []desync.Pos{{Offset: 1, FromSNI: true}}, Disorder: true, OOB: &desync.OOBOptions{}} + if err := opts.Validate(); err != nil { + t.Skip(err) + } + socksTunnel(t, opts) +} + +func socksTunnel(t *testing.T, opts desync.Options) { srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("through")) })) @@ -54,7 +66,6 @@ func TestSocksTunnelWithTLSRec(t *testing.T) { t.Fatal(err) } defer ln.Close() - opts := desync.Options{TLSRec: []desync.Pos{{Offset: 1, FromSNI: true}}, Split: []desync.Pos{{Offset: 1, FromSNI: true}}} go func() { for { c, err := ln.Accept() @@ -81,6 +92,19 @@ func contains(b []byte, s string) bool { return len(b) >= len(s) && string(b[len(b)-len(s):]) == s } +func TestParseByte(t *testing.T) { + for in, want := range map[string]byte{"a": 'a', "0xff": 0xff, "0x00": 0} { + if got, err := parseByte(in); err != nil || got != want { + t.Errorf("parseByte(%q) = %d, %v", in, got, err) + } + } + for _, bad := range []string{"", "ab", "0x100", "0xzz"} { + if _, err := parseByte(bad); err == nil { + t.Errorf("parseByte(%q) accepted", bad) + } + } +} + func TestParseList(t *testing.T) { ps, err := parseList("1+s, 3+s,,7") if err != nil || len(ps) != 3 || ps[2] != (desync.Pos{Offset: 7}) { diff --git a/conn.go b/conn.go index 5322b12..7bafabc 100644 --- a/conn.go +++ b/conn.go @@ -34,11 +34,23 @@ type Options struct { // deterministic. Include Key() in a strategy ID so it is never reused for // a different randomization policy or seed. Random *RandomOptions + // Disorder sends the first TCP piece with hop limit 1, so it expires at + // the first router, then restores the hop limit and sends the rest; TCP + // retransmits the first piece with the normal hop limit (ByeDPI + // --disorder). It needs Split or Random.Split positions. The hop limit is + // restored once the kernel reports the piece as transmitted (bounded by + // SplitWaitTimeout); see PlatformCapabilities().Disorder. + Disorder bool + // OOB sends one urgent (MSG_OOB) byte right after the first TCP piece + // (ByeDPI --oob; with Disorder, --disoob). It needs Split or Random.Split + // positions. + OOB *OOBOptions } // Enabled reports whether the options change anything. func (o Options) Enabled() bool { - return o.Fake != nil || len(o.TLSRec) > 0 || len(o.Split) > 0 || o.Random.enabled() + return o.Fake != nil || len(o.TLSRec) > 0 || len(o.Split) > 0 || o.Random.enabled() || + o.Disorder || o.OOB != nil } // splits reports whether the hello can be sent in more than one TCP write. @@ -81,8 +93,12 @@ func WrapConn(c net.Conn, opts Options) net.Conn { fake.Payload = append([]byte(nil), fake.Payload...) opts.Fake = &fake } + if opts.OOB != nil { + oob := *opts.OOB + opts.OOB = &oob + } w := &Conn{Conn: c, opts: opts, closed: make(chan struct{}), err: opts.Validate()} - if opts.splits() && (opts.SplitDelay > 0 || opts.SplitWait != SplitWaitNone) { + if opts.Fake != nil || opts.splits() && (opts.SplitDelay > 0 || opts.SplitWait != SplitWaitNone || opts.Disorder) { w.deadlineChanged = make(chan struct{}) } return w @@ -300,19 +316,25 @@ func (c *Conn) sendHello(rec []byte, frame helloFrame) (int, error) { } tcpCuts := mapCuts(splitCuts, recCuts) var ack ackObserver + var first *firstPiece if len(tcpCuts) > 0 { var err error if ack, err = c.splitObserver(); err != nil { return 0, err } + if first, err = c.prepareFirstPiece(ack); err != nil { + return 0, err + } } - written := 0 + // written counts bytes of out; extra counts urgent bytes, which are on + // the socket but not part of the stream the server reads. + written, extra := 0, 0 for i, end := range append(tcpCuts, len(out)) { if end <= start || end > len(out) { continue } if i > 0 && ack != nil { - if err := c.waitSplit(ack, int64(written)); err != nil { + if err := c.waitSplit(ack, int64(written+extra)); err != nil { return originalWriteCount(written, recCuts), err } } @@ -321,8 +343,15 @@ func (c *Conn) sendHello(rec []byte, frame helloFrame) (int, error) { return originalWriteCount(written, recCuts), err } } - n, err := writeAllCount(c.Conn, out[start:end]) + var n, urgent int + var err error + if i == 0 && first != nil { + n, urgent, err = first.send(c, out[start:end]) + } else { + n, err = writeAllCount(c.Conn, out[start:end]) + } written += n + extra += urgent if err != nil { return originalWriteCount(written, recCuts), err } diff --git a/disorder.go b/disorder.go new file mode 100644 index 0000000..0ce7c30 --- /dev/null +++ b/disorder.go @@ -0,0 +1,174 @@ +package desync + +import ( + "errors" + "fmt" + "io" + "runtime" + "syscall" +) + +var ( + // ErrDisorderUnsupported reports that Options.Disorder is not implemented + // on this platform. + ErrDisorderUnsupported = errors.New("desync: disorder is not implemented on this platform") + // ErrOOBUnsupported reports that Options.OOB is not implemented on this + // platform. + ErrOOBUnsupported = errors.New("desync: out-of-band data is not implemented on this platform") + // ErrSocketMethodRequiresTCP reports that Disorder or OOB was requested on + // a connection that does not expose a TCP socket through SyscallConn. + ErrSocketMethodRequiresTCP = errors.New("desync: disorder and OOB require a TCP connection exposing SyscallConn") +) + +// disorderHopLimit makes the first transmission of the piece expire at the +// first router (ByeDPI --disorder uses the same value). +const disorderHopLimit = 1 + +// DefaultOOBByte is the out-of-band byte sent when OOBOptions.Byte is zero. +const DefaultOOBByte = 'a' + +// OOBOptions sends one byte of TCP urgent data (MSG_OOB) right after the +// first TCP piece (ByeDPI --oob). A receiver without SO_OOBINLINE removes the +// urgent byte from the stream, so the server reads the original bytes; an +// inspecting device that ignores the urgent pointer sees one extra byte. +type OOBOptions struct { + // Byte is the urgent byte; zero selects DefaultOOBByte ('a'). + Byte byte +} + +func (o *OOBOptions) urgentByte() byte { + if o.Byte == 0 { + return DefaultOOBByte + } + return o.Byte +} + +// DisorderCapability describes Options.Disorder on this OS. +type DisorderCapability struct { + // Supported reports that Options.Disorder is implemented. + Supported bool + // Mechanism names the socket query used around the low-hop piece. + Mechanism string + // Observed is true when the hop limit is restored only after the kernel + // reported the low-hop piece as transmitted. When false (macOS), the + // piece is written once the send buffer is empty, so the kernel builds + // its segment inside the send call; this is inferred, not observed. + Observed bool + // Reliable is true when the observation reads the kernel's queue state + // rather than counters (see AckCapability.Reliable). + Reliable bool +} + +func (o Options) validateSocketMethods() error { + if !o.Disorder && o.OOB == nil { + return nil + } + if !o.splits() { + return fmt.Errorf("desync: disorder and OOB require Split or Random.Split positions") + } + if o.Fake != nil { + return fmt.Errorf("desync: fake cannot be combined with disorder or OOB yet") + } + if o.Disorder && o.SplitWait == SplitWaitAcked { + // The low-hop piece is acknowledged only after its retransmission, + // so an acknowledged wait would undo the reordering. + return fmt.Errorf("desync: disorder cannot be combined with SplitWaitAcked") + } + if o.Disorder && !platformDisorder.Supported { + return fmt.Errorf("%w (%s)", ErrDisorderUnsupported, runtime.GOOS) + } + if o.OOB != nil && !supportsOOB { + return fmt.Errorf("%w (%s)", ErrOOBUnsupported, runtime.GOOS) + } + return nil +} + +// firstPiece sends the first TCP piece of a split ClientHello with the +// configured socket methods. It is prepared before anything is written, so +// a connection without a usable socket fails before transmission. +type firstPiece struct { + raw syscall.RawConn + obs ackObserver // disorder only +} + +func (c *Conn) prepareFirstPiece(splitObs ackObserver) (*firstPiece, error) { + if !c.opts.Disorder && c.opts.OOB == nil { + return nil, nil + } + raw, err := socketOf(c.Conn) + if err != nil { + return nil, ErrSocketMethodRequiresTCP + } + p := &firstPiece{raw: raw, obs: splitObs} + if c.opts.Disorder && p.obs == nil { + if p.obs, err = newAckObserver(raw); err != nil { + return nil, fmt.Errorf("%w: %v", ErrDisorderUnsupported, err) + } + } + return p, nil +} + +// send writes piece and returns how many of its bytes were written and how +// many extra (urgent) bytes went to the socket. With Disorder the piece goes +// out with hop limit 1; the limit is restored before send returns, also on +// every error, and the restore error is reported. +func (p *firstPiece) send(c *Conn, piece []byte) (n, extra int, err error) { + if !c.opts.Disorder { + return p.write(c, piece) + } + timeout := c.opts.SplitWaitTimeout + if timeout == 0 { + timeout = defaultSplitWaitTimeout + } + if !platformDisorder.Observed { + // Every earlier byte acknowledged: the send queue is empty, so the + // kernel transmits the piece within the send call. + if err := c.poll(timeout, ErrSplitWaitTimeout, "disorder", func() (bool, error) { + return p.obs.reached(SplitWaitAcked, 0) + }); err != nil { + return 0, 0, err + } + } + saved, err := lowerHop(p.raw, disorderHopLimit) + if err != nil { + return 0, 0, fmt.Errorf("desync: disorder: %w", err) + } + defer func() { + if restoreErr := restoreHop(p.raw, saved); restoreErr != nil { + err = errors.Join(err, restoreErr) + } + }() + if n, extra, err = p.write(c, piece); err != nil { + return n, extra, err + } + if platformDisorder.Observed { + // Restore only after the low-hop segment left the socket. A restore + // before it would send the piece with the normal hop limit. + written := int64(n + extra) + err = c.poll(timeout, ErrSplitWaitTimeout, "disorder", func() (bool, error) { + return p.obs.reached(SplitWaitSent, written) + }) + } + return n, extra, err +} + +func (p *firstPiece) write(c *Conn, piece []byte) (int, int, error) { + if c.opts.OOB == nil { + n, err := writeAllCount(c.Conn, piece) + return n, 0, err + } + buf := make([]byte, len(piece)+1) + copy(buf, piece) + buf[len(piece)] = c.opts.OOB.urgentByte() + n, err := sendOOBFunc(p.raw, buf) + if err == nil && n != len(buf) { + err = io.ErrShortWrite + } + if n >= len(buf) { + return len(piece), 1, err + } + return n, 0, err +} + +// sendOOBFunc is replaced by tests to observe the socket at the send. +var sendOOBFunc = sendOOB diff --git a/disorder_test.go b/disorder_test.go new file mode 100644 index 0000000..f11f3ef --- /dev/null +++ b/disorder_test.go @@ -0,0 +1,445 @@ +package desync + +import ( + "bytes" + "crypto/tls" + "errors" + "fmt" + "io" + "net" + "os" + "runtime" + "strings" + "sync" + "syscall" + "testing" + "time" +) + +func TestSocketMethodValidation(t *testing.T) { + split := []Pos{{Offset: 12}} + for name, o := range map[string]Options{ + "disorder without split": {Disorder: true}, + "oob without split": {OOB: &OOBOptions{}}, + "disorder records only": {TLSRec: split, Disorder: true}, + "disorder and fake": {Split: split, Disorder: true, Fake: &FakeOptions{TTL: 4}}, + "oob and fake": {Split: split, OOB: &OOBOptions{}, Fake: &FakeOptions{TTL: 4}}, + "disorder and acked": {Split: split, Disorder: true, SplitWait: SplitWaitAcked}, + } { + if err := o.Validate(); err == nil { + t.Errorf("%s: accepted", name) + } + if !o.Enabled() { + t.Errorf("%s: not enabled, so the error would never surface", name) + } + } + caps := PlatformCapabilities() + for _, o := range []Options{ + {Split: split, Disorder: true}, + {Random: &RandomOptions{Split: []RandomCut{{From: Pos{Offset: 1}, To: Pos{Offset: 40}}}}, Disorder: true}, + } { + err := o.Validate() + if caps.Disorder.Supported != (err == nil) || !caps.Disorder.Supported && !errors.Is(err, ErrDisorderUnsupported) { + t.Fatalf("disorder on %s: %v, capability %+v", runtime.GOOS, err, caps.Disorder) + } + } + err := Options{Split: split, OOB: &OOBOptions{}}.Validate() + if caps.OOB != (err == nil) || !caps.OOB && !errors.Is(err, ErrOOBUnsupported) { + t.Fatalf("oob on %s: %v", runtime.GOOS, err) + } + if caps.Disorder.Supported && caps.Ack.Sent { + if err := (Options{Split: split, Disorder: true, SplitWait: SplitWaitSent}).Validate(); err != nil { + t.Fatalf("disorder with SplitWaitSent: %v", err) + } + } +} + +func TestSocketMethodKey(t *testing.T) { + base := Options{Split: []Pos{{Offset: 12}}} + if k := base.Key(); strings.Contains(k, "disorder") || strings.Contains(k, "oob") { + t.Fatalf("key changed for options without the new methods: %s", k) + } + keys := map[string]bool{} + for _, o := range []Options{ + base, + {Split: base.Split, Disorder: true}, + {Split: base.Split, OOB: &OOBOptions{}}, + {Split: base.Split, OOB: &OOBOptions{Byte: 'b'}}, + {Split: base.Split, Disorder: true, OOB: &OOBOptions{}}, + } { + keys[o.Key()] = true + } + if len(keys) != 5 { + t.Fatalf("methods not part of the key: %v", keys) + } + if (Options{Split: base.Split, OOB: &OOBOptions{}}).Key() != (Options{Split: base.Split, OOB: &OOBOptions{Byte: 'a'}}).Key() { + t.Fatal("the default urgent byte has two keys") + } +} + +func TestSocketMethodOptionsAreCopied(t *testing.T) { + a, b := net.Pipe() + defer a.Close() + defer b.Close() + oob := &OOBOptions{Byte: 'x'} + w := WrapConn(a, Options{Split: []Pos{{Offset: 3}}, OOB: oob}).(*Conn) + oob.Byte = 'y' + if w.opts.OOB.Byte != 'x' { + t.Fatal("wrapper shares OOB options") + } +} + +// Without a socket nothing is written: no fallback to a plain split. +func TestSocketMethodRequiresSocket(t *testing.T) { + for name, opts := range map[string]Options{ + "disorder": {Split: []Pos{{Offset: 12}}, Disorder: true}, + "oob": {Split: []Pos{{Offset: 12}}, OOB: &OOBOptions{}}, + } { + t.Run(name, func(t *testing.T) { + if err := opts.Validate(); err != nil { + t.Skip(err) + } + a, b := net.Pipe() + defer b.Close() + got := make(chan []byte, 1) + go func() { data, _ := io.ReadAll(b); got <- data }() + w := WrapConn(a, opts) + if _, err := w.Write(captureHello(t, "example.test")); !errors.Is(err, ErrSocketMethodRequiresTCP) { + t.Fatalf("Write: %v", err) + } + if data := <-got; len(data) != 0 { + t.Fatalf("%d bytes reached the peer", len(data)) + } + }) + } +} + +// tcpHop reads the hop limit that applies to the connection's peer. +func tcpHop(t testing.TB, c *net.TCPConn) int { + t.Helper() + raw, err := c.SyscallConn() + if err != nil { + t.Fatal(err) + } + var v int + var opErr error + if err := raw.Control(func(fd uintptr) { + peer, e := socketPeer(fd) + if e != nil { + opErr = e + return + } + h, e := hopFor(fd, peer) + v, opErr = h.restore, e + }); err != nil { + t.Fatal(err) + } + if opErr != nil { + t.Fatal(opErr) + } + return v +} + +type hopWrite struct { + hop int + data []byte + oob bool +} + +// hopConn records the socket's hop limit at every write. Failing the write +// number fail (1-based) checks restoration on errors. +type hopConn struct { + *net.TCPConn + t testing.TB + mu sync.Mutex + writes []hopWrite + fail int +} + +var errInjected = errors.New("injected write failure") + +func (c *hopConn) record(p []byte, oob bool) error { + c.mu.Lock() + defer c.mu.Unlock() + c.writes = append(c.writes, hopWrite{hop: tcpHop(c.t, c.TCPConn), data: append([]byte(nil), p...), oob: oob}) + if len(c.writes) == c.fail { + return errInjected + } + return nil +} + +func (c *hopConn) Write(p []byte) (int, error) { + if err := c.record(p, false); err != nil { + return 0, err + } + return c.TCPConn.Write(p) +} + +// observeOOB routes the test's urgent sends through rec. +func observeOOB(t *testing.T, rec *hopConn) { + t.Helper() + sendOOBFunc = func(raw syscall.RawConn, p []byte) (int, error) { + if err := rec.record(p, true); err != nil { + return 0, err + } + return sendOOB(raw, p) + } + t.Cleanup(func() { sendOOBFunc = sendOOB }) +} + +func readUntil(c net.Conn, tail []byte) chan []byte { + out := make(chan []byte, 1) + go func() { + _ = c.SetReadDeadline(time.Now().Add(10 * time.Second)) + buf := make([]byte, 0, 4096) + chunk := make([]byte, 4096) + for !bytes.HasSuffix(buf, tail) { + n, err := c.Read(chunk) + buf = append(buf, chunk[:n]...) + if err != nil { + break + } + } + out <- buf + }() + return out +} + +type socketMethodCase struct { + name string + opts Options +} + +func socketMethodCases() []socketMethodCase { + split := []Pos{{Offset: 1, FromSNI: true}} + splits := []Pos{{Offset: 3}, {Offset: 1, FromSNI: true}, {Offset: 40, FromSNI: true}} + rec := []Pos{{Offset: 2, FromSNI: true}} + random := &RandomOptions{Split: []RandomCut{{From: Pos{Offset: -8, FromSNI: true}, To: Pos{Offset: 8, FromSNI: true}, Count: 2, MinPiece: 2}}, Seed: 7} + caps := PlatformCapabilities() + var out []socketMethodCase + for _, m := range []struct { + name string + disorder bool + oob *OOBOptions + }{{"disorder", true, nil}, {"oob", false, &OOBOptions{}}, {"disoob", true, &OOBOptions{Byte: 0xff}}} { + out = append(out, + socketMethodCase{m.name + "/split", Options{Split: split, Disorder: m.disorder, OOB: m.oob}}, + socketMethodCase{m.name + "/tlsrec-splits", Options{TLSRec: rec, Split: splits, Disorder: m.disorder, OOB: m.oob}}, + socketMethodCase{m.name + "/random", Options{TLSRec: rec, Random: random, Disorder: m.disorder, OOB: m.oob}}, + socketMethodCase{m.name + "/delay", Options{Split: splits, SplitDelay: time.Millisecond, Disorder: m.disorder, OOB: m.oob}}, + ) + if caps.Ack.Sent { + out = append(out, socketMethodCase{m.name + "/wait-sent", Options{TLSRec: rec, Split: splits, SplitWait: SplitWaitSent, Disorder: m.disorder, OOB: m.oob}}) + } + if !m.disorder && caps.Ack.Acked { + out = append(out, socketMethodCase{m.name + "/wait-acked", Options{Split: splits, SplitWait: SplitWaitAcked, OOB: m.oob}}) + } + } + return out +} + +// wantStream is what the server must read: the record-split hello and the +// tail, with the urgent byte only when the server reads urgent data inline. +func wantStream(t *testing.T, hello, tail []byte, opts Options, inline bool) []byte { + t.Helper() + want := FragmentRecord(hello, resolve(opts.TLSRec, mustParse(t, hello), recordHeaderLen, len(hello))) + if inline && opts.OOB != nil { + if opts.Random != nil { + t.Fatal("inline expectation supports fixed positions only") + } + var s helloScanner + frame, err := s.scan(hello, (*ClientHelloOptions)(nil).limits()) + if err != nil { + t.Fatal(err) + } + at := mapCuts(frame.cuts(opts.Split, false), frame.cuts(opts.TLSRec, true))[0] + want = append(append(append([]byte(nil), want[:at]...), opts.OOB.urgentByte()), want[at:]...) + } + return append(want, tail...) +} + +func socketMethodRoundTrip(t *testing.T, network string, opts Options, inline bool) { + client, server := loopbackPair(t, network) + if inline { + raw, err := server.SyscallConn() + if err != nil { + t.Fatal(err) + } + var opErr error + if err := raw.Control(func(fd uintptr) { opErr = setOOBInline(fd) }); err != nil || opErr != nil { + t.Fatal(err, opErr) + } + } + hello := captureHello(t, "example.test") + tail := []byte("after the hello") + before := tcpHop(t, client) + rec := &hopConn{TCPConn: client, t: t} + observeOOB(t, rec) + w := WrapConn(rec, opts) + _ = w.SetWriteDeadline(time.Now().Add(10 * time.Second)) + read := readUntil(server, tail) + input := append(append([]byte(nil), hello...), tail...) + if n, err := w.Write(input); err != nil || n != len(input) { + t.Fatalf("Write: %d %v", n, err) + } + got := <-read + if want := wantStream(t, hello, tail, opts, inline); !bytes.Equal(got, want) { + t.Fatalf("stream changed: got %d bytes, want %d\ngot %q\nwant %q", len(got), len(want), got, want) + } + if after := tcpHop(t, client); after != before { + t.Fatalf("hop limit not restored: %d -> %d", before, after) + } + // The first piece goes out at hop limit 1 with Disorder and at the + // original limit otherwise; only the first send carries urgent data. + if len(rec.writes) < 2 { + t.Fatalf("not split: %d writes", len(rec.writes)) + } + for i, wr := range rec.writes { + hop := before + if i == 0 && opts.Disorder { + hop = disorderHopLimit + } + if wr.hop != hop || wr.oob != (i == 0 && opts.OOB != nil) { + t.Fatalf("write %d (%d bytes): hop %d oob %v, want hop %d", i, len(wr.data), wr.hop, wr.oob, hop) + } + } + if opts.OOB != nil { + first := rec.writes[0].data + if first[len(first)-1] != opts.OOB.urgentByte() { + t.Fatalf("urgent send does not end with the OOB byte: %q", first) + } + } +} + +// Every method and combination delivers a byte-identical stream on a real +// socket and leaves the hop limit as it was. +func TestSocketMethodsNativeLoopback(t *testing.T) { + for _, tc := range socketMethodCases() { + if err := tc.opts.Validate(); err != nil { + t.Logf("%s: %v", tc.name, err) + continue + } + for _, network := range []string{"tcp4", "tcp6"} { + t.Run(tc.name+"/"+network, func(t *testing.T) { socketMethodRoundTrip(t, network, tc.opts, false) }) + } + } +} + +// With SO_OOBINLINE the server reads the urgent byte at the split point, so +// it was transmitted as urgent data; without that option it is consumed. +func TestOOBByteIsUrgentData(t *testing.T) { + opts := Options{TLSRec: []Pos{{Offset: 2, FromSNI: true}}, Split: []Pos{{Offset: 3}, {Offset: 1, FromSNI: true}}, OOB: &OOBOptions{}} + if err := opts.Validate(); err != nil { + t.Skip(err) + } + for _, network := range []string{"tcp4", "tcp6"} { + t.Run(network, func(t *testing.T) { socketMethodRoundTrip(t, network, opts, true) }) + } +} + +func TestSocketMethodsTLSHandshake(t *testing.T) { + opts := Options{TLSRec: []Pos{{Offset: 1, FromSNI: true}}, Split: []Pos{{Offset: 1, FromSNI: true}}, Disorder: true, OOB: &OOBOptions{}} + if err := opts.Validate(); err != nil { + t.Skip(err) + } + client, server := loopbackPair(t, "tcp4") + cert := selfSigned(t) + serverErr := make(chan error, 1) + go func() { + _ = server.SetDeadline(time.Now().Add(5 * time.Second)) + s := tls.Server(server, &tls.Config{Certificates: []tls.Certificate{cert}}) + err := s.Handshake() + if err == nil { + _, err = s.Write([]byte("ok")) + } + serverErr <- err + }() + w := WrapConn(client, opts) + _ = w.SetDeadline(time.Now().Add(5 * time.Second)) + c := tls.Client(w, &tls.Config{ServerName: "www.example.test", InsecureSkipVerify: true}) + var got [2]byte + if _, err := io.ReadFull(c, got[:]); err != nil || string(got[:]) != "ok" { + t.Fatalf("TLS: %q %v", got, err) + } + if err := <-serverErr; err != nil { + t.Fatal(err) + } +} + +func firstPieceFixture(t *testing.T, opts Options) (*Conn, *hopConn, *firstPiece, int) { + t.Helper() + if err := opts.Validate(); err != nil { + t.Skip(err) + } + client, server := loopbackPair(t, "tcp4") + go func() { _, _ = io.Copy(io.Discard, server) }() + rec := &hopConn{TCPConn: client, t: t} + w := WrapConn(rec, opts).(*Conn) + p, err := w.prepareFirstPiece(nil) + if err != nil { + t.Fatal(err) + } + return w, rec, p, tcpHop(t, client) +} + +// A failed low-hop send restores the hop limit and reports the failure. +func TestDisorderRestoresHopOnFailure(t *testing.T) { + for _, oob := range []bool{false, true} { + t.Run(fmt.Sprint("oob=", oob), func(t *testing.T) { + opts := Options{Split: []Pos{{Offset: 3}}, Disorder: true} + if oob { + opts.OOB = &OOBOptions{} + } + w, rec, p, before := firstPieceFixture(t, opts) + observeOOB(t, rec) + rec.fail = 1 + if _, _, err := p.send(w, []byte("abc")); !errors.Is(err, errInjected) { + t.Fatalf("send: %v", err) + } + if len(rec.writes) != 1 || rec.writes[0].hop != disorderHopLimit { + t.Fatalf("writes: %+v", rec.writes) + } + if after := tcpHop(t, rec.TCPConn); after != before { + t.Fatalf("hop limit leaked: %d -> %d", before, after) + } + }) + } +} + +// The wait around the low-hop piece is bounded by the deadline, Close and +// SplitWaitTimeout, and the hop limit is restored when it ends. +func TestDisorderWaitIsBounded(t *testing.T) { + for _, mode := range []string{"deadline", "timeout", "close"} { + t.Run(mode, func(t *testing.T) { + opts := Options{Split: []Pos{{Offset: 3}}, Disorder: true, SplitWaitTimeout: time.Minute} + if mode == "timeout" { + opts.SplitWaitTimeout = 30 * time.Millisecond + } + w, rec, p, before := firstPieceFixture(t, opts) + p.obs = &stubAck{after: -1} + want := os.ErrDeadlineExceeded + switch mode { + case "deadline": + _ = w.SetWriteDeadline(time.Now().Add(30 * time.Millisecond)) + case "timeout": + want = ErrSplitWaitTimeout + case "close": + want = net.ErrClosed + time.AfterFunc(30*time.Millisecond, func() { w.Close() }) + } + start := time.Now() + _, _, err := p.send(w, []byte("abc")) + if !errors.Is(err, want) { + t.Fatalf("send: %v, want %v", err, want) + } + if d := time.Since(start); d > 5*time.Second { + t.Fatalf("wait ended after %v", d) + } + if mode != "close" { + if after := tcpHop(t, rec.TCPConn); after != before { + t.Fatalf("hop limit leaked: %d -> %d", before, after) + } + } + }) + } +} diff --git a/docs/connection-io.md b/docs/connection-io.md index fb2a8d9..e34092d 100644 --- a/docs/connection-io.md +++ b/docs/connection-io.md @@ -57,6 +57,44 @@ Nil options and zero fields use these defaults. Maximum configurable bounds are The implementation follows [TLS record framing, RFC 8446 section 5.1](https://datatracker.ietf.org/doc/html/rfc8446#section-5.1). Local TLS/regression tests validate byte-stream correctness; they do not establish provider DPI effectiveness. +## Disorder and out-of-band byte + +`Options.Disorder` and `Options.OOB` change how the first TCP piece of a split ClientHello is sent; every later piece is an ordinary write. They need split positions (`Split` or `Random.Split`); when none resolves for a ClientHello, it is written in one piece, as with `Split` alone. Both are prepared before the first piece: a connection without a TCP `SyscallConn` returns `ErrSocketMethodRequiresTCP` before any byte is sent, and an OS without the method fails `Validate` with `ErrDisorderUnsupported` / `ErrOOBUnsupported`. Neither combines with `Fake`; `Disorder` rejects `SplitWaitAcked`, because the dropped piece is acknowledged only after its retransmission, so the wait would undo the reordering. `SplitWaitSent` and `SplitDelay` apply between the later pieces as usual. + +Disorder (ByeDPI `--disorder`): the hop limit of the connected peer's family is set to 1, the first piece is written, the hop limit is restored, then the remaining pieces follow. The piece expires at the first router; the server receives the later pieces first, acknowledges what it can (with SACK), and the client's TCP retransmits the first piece with the restored limit. The kernel stamps the hop limit when it builds a segment, not when `write` returns, so the restore must wait for the transmission: + +- **Linux and Android**: the wrapper waits until `SIOCOUTQNSD` is zero, so the piece left the send queue at hop limit 1. +- **Windows**: it waits until `SIO_TCP_INFO` counts the piece as sent (`BytesOut - BytesRetrans`), which is exact for writes of this size but counter-based (`Reliable: false`). +- **macOS**: no public interface reports unsent bytes. The wrapper writes the piece only once `SO_NWRITE` is zero, so the send buffer is empty; xnu's `tcp_usr_send` then calls `tcp_output`, which builds the segment within the send call, as nothing else is queued, the window is open and Nagle is off. The restore follows the send. This is inferred, not observed, and `PlatformCapabilities().Disorder.Observed` is false. + +The wait uses the split-wait poll, bounded by `SplitWaitTimeout` (`ErrSplitWaitTimeout`), the write deadline and `Close`. The hop limit is restored on every path, including a failed write and an interrupted wait; a failed restore is reported and, like every error after transformed transmission started, closes the connection. A connection whose write failed after the change is never left with hop limit 1. + +Out-of-band byte (ByeDPI `--oob`, with Disorder `--disoob`): the first piece and one more byte (`OOBOptions.Byte`, default `'a'`) are sent in one `send(MSG_OOB)` call (`WSASend` with `MSG_OOB` on Windows), which marks that last byte as urgent data. The byte takes one sequence number on the wire, so an inspecting device that ignores the urgent pointer reads one extra byte after the first piece. A receiver without `SO_OOBINLINE` (the default everywhere) removes the urgent byte from the stream and keeps it for `recv(MSG_OOB)`, so the application reads the original bytes. This is verified on Windows and Linux loopback with the server reading the stream byte-identically, and with `SO_OOBINLINE` set the server reads the urgent byte exactly at the split point. Two conditions break it: a server application that enables `SO_OOBINLINE`, and a middlebox that clears the URG flag (some firewalls do); both put the byte into the stream and fail the handshake. With Disorder the urgent byte is part of the low-hop segment and of its retransmission, which carries the URG flag again while the urgent pointer is ahead of the acknowledged data. + +## Linux native fake + +The Linux and Android fake follows ByeDPI's `send_fake`: the fake prefix is copied into a shared anonymous mapping, `vmsplice` puts references to its pages into a pipe, and `splice` moves them into the socket's send queue at the low hop limit. The queued segment refers to the page, not to a copy. Once `SIOCOUTQNSD` reports the prefix transmitted, the page is overwritten with the original bytes, and only then is the hop limit restored and the normal tail written. A retransmission reads the page and carries the original. The mapping is `MAP_SHARED`, so a `fork` cannot make it copy-on-write and leave the kernel's reference on a page that still holds the fake bytes. + +The page is rewritten before the hop limit is restored on every path, including errors and timeouts, so no normal-hop transmission can carry the fake. The splice runs non-blocking inside `RawConn.Control`; waiting for socket space and for the transmission polls under `Fake.Timeout` (default 3 s), the write deadline and `Close`. Afterwards the pipe is closed and the mapping unmapped; the kernel keeps its own page references, whose content is then the original. At most 64 operations hold resources at once (`ErrFakeBusy`). Prefixes larger than a pipe are moved in 64 KiB rounds. + +The kernel splices without copying only when the route's device supports scatter-gather (`NETIF_F_SG`); loopback, Ethernet, Wi-Fi, tun and WireGuard devices do. On a device without it the kernel copies the spliced data, a retransmission repeats the fake, and the server's TLS handshake fails rather than succeeding with altered bytes. + +A loopback test verifies the property directly: a classic BPF socket filter on the server's socket drops every segment with a TTL or hop limit below 8 before TCP processing, the client sends a fake prefix of different bytes with TTL 3, and the server still reads the exact original stream after the client's retransmission (`tcpi_total_retrans` 1). Disabling the page rewrite makes the server read the fake bytes. The same filter verifies disorder and disoob. + +## macOS TCP fake + +Not implemented, and reported in `PlatformCapabilities().Unsupported["fake-tcp"]`. The fake needs a first transmission whose bytes differ from what the socket later retransmits. Linux gets that from splice, which queues page references; Windows from `TransmitFile`, which reads the file cache at transmission time. xnu has no `splice` or `vmsplice`, and its `sendfile` allocates mbufs (`alloc_sendpkt`) and reads the file into them (`fo_read`) before `pru_send` appends them to the socket buffer (`bsd/kern/uipc_syscalls.c`, `sendfile`): the socket buffer holds a copy, so changing the file afterwards never reaches a retransmission, and the server would receive the fake bytes. There is no `MSG_ZEROCOPY` either. Writing the fake and later the original through ordinary writes would add bytes to the stream instead of replacing them. + +## UDP burst and ICMP errors + +The low-TTL datagrams can draw ICMP time-exceeded replies from the router where they expire. They must not fail the owned socket's `ReadFrom`: + +- **Windows**: `SIO_UDP_NETRESET` is disabled on the socket. +- **Linux and Android**: an unconnected UDP socket is told about ICMP errors only with `IP_RECVERR` / `IPV6_RECVERR` (`__udp4_lib_err`, `__udp6_lib_err`); without it a soft error such as time exceeded is dropped, and a hard error is reported only on a connected socket. Both options are off by default; if the caller enabled them, `WrapPacketConn` turns them off. A loopback test shows a port-unreachable reply failing `ReadFrom` with `ECONNREFUSED` when `IP_RECVERR` is on, and not after wrapping. +- **macOS**: `udp_ctlinput` notifies only a socket whose foreign address and port match exactly, so an unconnected socket never sees the replies. + +On a macOS dual-stack socket, `IPV6_UNICAST_HOPS` also sets the TTL of IPv4-mapped traffic, and `IPPROTO_IP` options are rejected. A default hop limit (-1) is therefore restored as its explicit value, and only when the IPv4 and IPv6 defaults (`net.inet.ip.ttl`, `net.inet6.ip6.hlim`) are equal; otherwise the burst fails with an error instead of changing the socket. + ## Windows native fake socket options The TCP fake backend selects the TTL/hop-limit option for its connected peer's address family and restores that same option. It does not try to set IPv4 TTL on an IPv6-only connection merely because reading that option succeeded. This also keeps option selection explicit for IPv4-mapped peers. Native overlapped resource lifetime, cancellation and transmit-slot limits remain in place. Socket options are read through `syscall.Getsockopt` (ws2_32 `getsockopt`), because `syscall.GetsockoptInt` returns `EWINDOWS` on Windows before Go 1.21; the module's minimum Go 1.20 is tested on Windows in CI. See [IPv4 socket options](https://learn.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options) and [IPv6 socket options](https://learn.microsoft.com/en-us/windows/win32/winsock/ipproto-ipv6-socket-options). diff --git a/docs/validation.md b/docs/validation.md index f51819f..3faa08a 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -29,7 +29,8 @@ go test ./controller -run '^$' -fuzz '^FuzzControllerTarget$' -fuzztime=15s -fuz The CI workflow (`.github/workflows/ci.yml`) runs gofmt, `go mod tidy -diff` and vet for Linux, Windows and macOS; tests with coverage on Windows, Linux and macOS with Go 1.26, each followed by a verbose run of the native capability tests -(ACK observation, `ProbeConn`, `SIO_TCP_INFO` layout; no root needed); Linux race +(capabilities, ACK observation, `ProbeConn`, `SIO_TCP_INFO` layout, disorder, +OOB, the Linux fake and the UDP burst; no root needed); Linux race tests; a 30-second smoke run of each fuzz target; Go 1.20.14 minimum-version checks on Linux and on Windows (the native fake TCP/UDP backends); and builds for Windows, Linux and macOS (amd64/arm64), Linux armv7 and Android arm64. The `CI` job passes only when every @@ -37,6 +38,29 @@ other job does, so it is the one check to require on `main`. This describes the workflow configuration; inspect the actual Actions result for a given revision. The module's declared minimum remains Go 1.20 and it uses only the standard library. +## Local verification, 2026-10-29 (cross-platform methods) + +- Windows 11 26200: `go test ./...` on Go 1.26.10 and Go 1.20.14, including + disorder, OOB and disoob over IPv4/IPv6 with every split combination, the + urgent byte read inline with `SO_OOBINLINE`, hop-limit recording per write + and restoration after failures, deadlines, timeouts and Close. +- Linux in Docker (WSL 2 kernel): tests on Go 1.26.9 and 1.20.14, `-race` for + all packages. The Linux fake, disorder and disoob were checked against a + server-side BPF filter dropping low-hop segments: the server read the + original stream after one retransmission, also with a fake of different + bytes; with the page rewrite disabled the server read the fake bytes. The + UDP burst and the `IP_RECVERR` suppression were checked with a loopback + port-unreachable reply. File descriptors and fake slots return to their + previous counts. +- `go vet ./...` for GOOS windows, linux and darwin on Go 1.26.10 and 1.20.14, + plus freebsd and linux/386, linux/arm; builds for linux/386, linux/arm, + linux/arm64, linux/riscv64, android/arm64, darwin/amd64, darwin/arm64, + freebsd/amd64, windows/386, windows/arm64 and js/wasm. +- Not verified locally: any macOS runtime behaviour (disorder, OOB, the UDP + burst, the dual-stack hop-limit restore; CI runs those tests), Android, + real networks and DPI effectiveness, and a route whose device lacks + scatter-gather. + ## Local verification, 2026-10-29 (platform ACK capabilities) - Windows: `go test ./...` on Go 1.26.10 (with `-shuffle=on`) and Go 1.20.14; on @@ -167,5 +191,8 @@ requires comparable connection p50/p95/p99 and real application outcomes. strategy including its policy and seed. Seeded draws are tied to the key version. - `Options.SplitWait` observes the socket's send queue; it is not a timing heuristic. Options without it keep their previous `Key()`. +- `Options.Disorder` and `Options.OOB` are appended to `Key()` only when set, + so existing keys are unchanged. `Capabilities` gained fields; compare its + fields rather than the whole struct (it now holds a map). - No new named Mihomo outbound, subscriber reserve implementation or client migration was added by these library stages. diff --git a/docs/vnext.md b/docs/vnext.md index 4b7c6e5..11224ff 100644 --- a/docs/vnext.md +++ b/docs/vnext.md @@ -34,6 +34,7 @@ application probe and real application tests; a successful TCP dial is insuffici | Controller lifecycle | Independent waiter cancellation, late-result rejection, generation invalidation, close/shutdown, bounded diagnostics and caller-owned versioned snapshots | | Platform ACK capabilities | `PlatformCapabilities`/`ProbeConn`; opt-in `Options.SplitWait` (sent/acked) read from the socket's send queue, bounded by Close, deadlines and a timeout; explicit errors where unsupported; Windows reported as counter-based, not reliable | | Bounded randomization | Opt-in `Options.Random` record/write cut ranges with count/minimum-piece bounds, optional reproducible seed (per-connection crypto/rand seed otherwise) and `Options.Key()` strategy identity; deterministic options unchanged | +| Cross-platform methods | `Options.Disorder` and `Options.OOB` (ByeDPI disorder, oob, disoob) on Windows, Linux/Android and macOS; TCP fake on Linux/Android via vmsplice/splice; UDP low-TTL burst on Linux/Android and macOS; macOS TCP fake reported unsupported with the reason; `Capabilities.Disorder`, `OOB` and `Unsupported` | | Examples and tests | Owned HTTPS application probe, fragmented/malformed TLS, concurrency, deadlines, IPv4/IPv6 and native Windows regressions | The controller is available as an API. It is **not yet connected to SlothClash or @@ -79,8 +80,8 @@ not reliable because `BytesOut` was observed to exceed the bytes written. Waits poll (yields, then 50 µs to 1 ms) and honor Close, deadline changes and a per-wait timeout; no delay substitutes for an unsupported mode. Loopback latency is recorded in [validation](validation.md#split-wait-latency-2026-10-29). -Not yet done: macOS runtime evidence beyond CI, real-network measurements, and -applying the wait to a future disorder method. The same change fixed native +Not yet done: macOS runtime evidence beyond CI and real-network measurements. +The disorder method reuses the same observation to restore its hop limit. The same change fixed native Windows fake TCP/UDP on Go 1.20 and added a Windows Go 1.20 CI job. - Determine which Windows, Linux and macOS kernel interfaces can observe useful @@ -124,6 +125,21 @@ Consumer wiring (Mihomo/SlothClash) is not part of this milestone. Done means regression/fuzz tests, deterministic reproduction and no unexplained first-write or warm-path allocation regression. +### Cross-platform transmission methods + +Status: implemented in the library. `Options.Disorder` sends the first TCP +piece with hop limit 1 and restores it once the kernel reports the piece +transmitted (Linux `SIOCOUTQNSD`, Windows `SIO_TCP_INFO`; on macOS after an +empty `SO_NWRITE`, reported as `Observed: false`). `Options.OOB` sends one +urgent byte after the first piece; together they are disoob. The Linux/Android +TCP fake ports ByeDPI's vmsplice/splice page rewrite, verified on loopback +with a BPF filter that drops the low-hop segments. The UDP burst runs on +Linux/Android and macOS with ICMP errors kept off the owned socket. The macOS +TCP fake is not implementable (sendfile copies into the socket buffer) and is +reported in `Capabilities.Unsupported`. Not yet done: macOS runtime evidence +beyond CI, real-network effectiveness, and combining Fake with Split, +Disorder or OOB. + ### 3. First-class Mihomo outbound as a maintained patch - Add an optional `type: desync` adapter in the maintained Mihomo patch set, diff --git a/fake.go b/fake.go index 1f52211..c9b40c8 100644 --- a/fake.go +++ b/fake.go @@ -16,7 +16,8 @@ var ( // FakeOptions changes a prefix's initial transmission to low-TTL bytes while // retaining the original prefix for TCP retransmission. It does not insert -// bytes into the application's stream. Currently implemented on Windows. +// bytes into the application's stream. Implemented on Windows and Linux +// (including Android); see PlatformCapabilities for the macOS reason. type FakeOptions struct { TTL int // Prefix is measured after TLS record fragmentation. Negative offsets @@ -47,6 +48,9 @@ func (o Options) Validate() error { if err := o.validateSplitWait(); err != nil { return err } + if err := o.validateSocketMethods(); err != nil { + return err + } if o.Fake == nil { return nil } diff --git a/fake_darwin.go b/fake_darwin.go new file mode 100644 index 0000000..50f7eb2 --- /dev/null +++ b/fake_darwin.go @@ -0,0 +1,13 @@ +//go:build darwin + +package desync + +// fakeUnsupportedReason: the fake prefix needs the kernel's retransmission to +// carry the original bytes although the first transmission carried others. +// Linux gets that from splice, which queues references to a user page that +// is overwritten afterwards; Windows from TransmitFile reading a file whose +// cache is rewritten. xnu has no splice/vmsplice, and its sendfile copies the +// file data into the socket buffer (mbufs) before returning, so a later file +// change never reaches a retransmission: the server would receive the fake +// bytes. See docs/connection-io.md. +const fakeUnsupportedReason = "no splice: sendfile copies the data into the socket buffer, so a retransmission cannot carry the original bytes" diff --git a/fake_linux.go b/fake_linux.go new file mode 100644 index 0000000..3221974 --- /dev/null +++ b/fake_linux.go @@ -0,0 +1,217 @@ +//go:build linux + +package desync + +import ( + "errors" + "fmt" + "os" + "syscall" + "time" + "unsafe" +) + +const supportsFake = true + +// fakeUnsupportedReason is unused on Linux, where the fake is implemented. +const fakeUnsupportedReason = "" + +// fakeSlots bounds the pages and pipes held by concurrent fake operations. +var fakeSlots = make(chan struct{}, 64) + +const ( + spliceFMove = 0x1 // linux/splice.h SPLICE_F_MOVE + spliceFNonblock = 0x2 // SPLICE_F_NONBLOCK + spliceFGift = 0x8 // SPLICE_F_GIFT + // spliceChunk stays within a default pipe (16 buffers of at least 4 KiB). + spliceChunk = 64 << 10 +) + +// spliceFake owns one shared anonymous mapping holding the prefix and a pipe. +// +// The mechanism follows ByeDPI v0.17.3 (desync.c send_fake, MIT; see +// third_party/BYEDPI-LICENSE): vmsplice puts references to the mapping's +// pages into the pipe, and splice moves those references into the socket's +// send queue without copying. The queued segment therefore reads the page +// whenever it is transmitted. The page holds the fake bytes during the first, +// low-hop transmission and the original bytes before the hop limit is +// restored, so a retransmission carries the original. Unlike ByeDPI the +// mapping is MAP_SHARED: a fork cannot make it copy-on-write, which would +// leave the kernel's reference on a page still holding the fake bytes. +type spliceFake struct { + page []byte + pipe [2]int + restored bool + unmapped bool + pipesOpen bool +} + +func newSpliceFake(payload []byte) (*spliceFake, error) { + size := len(payload) + pageSize := os.Getpagesize() + size = (size + pageSize - 1) / pageSize * pageSize + page, err := syscall.Mmap(-1, 0, size, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED|syscall.MAP_ANON) + if err != nil { + return nil, os.NewSyscallError("mmap(fake)", err) + } + o := &spliceFake{page: page} + copy(o.page, payload) + var p [2]int + if err := syscall.Pipe2(p[:], syscall.O_CLOEXEC|syscall.O_NONBLOCK); err != nil { + o.restored = true // nothing references the page yet + o.release() + return nil, os.NewSyscallError("pipe2(fake)", err) + } + o.pipe, o.pipesOpen = p, true + return o, nil +} + +// restore writes the original bytes over the page the kernel may reference. +func (o *spliceFake) restore(real []byte) { + copy(o.page, real) + o.restored = true +} + +// release closes the pipe (dropping references it still holds) and unmaps +// the page. The kernel keeps its own page references alive; their content is +// the original bytes written by restore. +func (o *spliceFake) release() { + if o.pipesOpen { + _ = syscall.Close(o.pipe[0]) + _ = syscall.Close(o.pipe[1]) + o.pipesOpen = false + } + if !o.unmapped && o.restored { + _ = syscall.Munmap(o.page) + o.unmapped = true + } +} + +func vmsplice(fd int, p []byte, flags int) (int, error) { + iov := syscall.Iovec{Base: &p[0]} + iov.SetLen(len(p)) + n, _, errno := syscall.Syscall6(syscall.SYS_VMSPLICE, uintptr(fd), uintptr(unsafe.Pointer(&iov)), 1, uintptr(flags), 0, 0) + if errno != 0 { + return 0, errno + } + return int(n), nil +} + +// step moves up to one chunk from the page through the pipe into the socket. +// It returns the bytes that reached the socket and whether it must wait for +// socket space. +func (o *spliceFake) step(fd uintptr, sent, inPipe, total int) (moved, piped int, again bool, err error) { + if inPipe == 0 { + end := sent + spliceChunk + if end > total { + end = total + } + n, err := vmsplice(o.pipe[1], o.page[sent:end], spliceFGift|spliceFNonblock) + if err != nil { + return 0, 0, false, os.NewSyscallError("vmsplice(fake)", err) + } + if n <= 0 { + return 0, 0, false, os.NewSyscallError("vmsplice(fake)", syscall.EIO) + } + inPipe, piped = n, n + } + n, err := syscall.Splice(o.pipe[0], nil, int(fd), nil, inPipe, spliceFMove|spliceFNonblock) + if err == syscall.EAGAIN || err == syscall.EINTR { + return 0, piped, true, nil + } + if err != nil { + return 0, piped, false, os.NewSyscallError("splice(fake)", err) + } + if n <= 0 { + return 0, piped, false, os.NewSyscallError("splice(fake)", syscall.EIO) + } + return int(n), piped, false, nil +} + +func (c *Conn) sendFake(real, payload, tail []byte) error { + start := time.Now() + if err := c.fakeAbort(start); err != nil { + return err + } + raw, err := socketOf(c.Conn) + if err != nil { + return ErrFakeRequiresTCP + } + obs, err := newAckObserver(raw) + if err != nil { + return fmt.Errorf("desync: TCP fake: %w", err) + } + select { + case fakeSlots <- struct{}{}: + default: + return ErrFakeBusy + } + defer func() { <-fakeSlots }() + op, err := newSpliceFake(payload) + if err != nil { + return err + } + if err := c.spliceFake(raw, obs, op, real, start); err != nil { + return fmt.Errorf("desync: TCP fake: %w", err) + } + // The original prefix is in place and the hop limit restored: the tail + // and every retransmission go out normally. + if err := writeAll(c.Conn, tail); err != nil { + return fmt.Errorf("desync: TCP fake: write original tail: %w", err) + } + return nil +} + +// spliceFake transmits the fake prefix with the low hop limit. Whatever +// happens, the page is rewritten with the original bytes, then the hop limit +// is restored, then the resources are released. +func (c *Conn) spliceFake(raw syscall.RawConn, obs ackObserver, op *spliceFake, real []byte, start time.Time) (err error) { + defer func() { + op.restore(real) + op.release() + }() + saved, err := lowerHop(raw, c.opts.Fake.TTL) + if err != nil { + return err + } + defer func() { + // The page must hold the original bytes before a normal hop limit + // lets a retransmission reach the server. + op.restore(real) + if restoreErr := restoreHop(raw, saved); restoreErr != nil { + err = errors.Join(err, restoreErr) + } + }() + timeout := c.opts.Fake.Timeout + if timeout == 0 { + timeout = 3 * time.Second + } + remaining := func() time.Duration { return timeout - time.Since(start) } + sent, inPipe := 0, 0 + err = c.poll(remaining(), os.ErrDeadlineExceeded, "splice", func() (bool, error) { + var opErr error + controlErr := raw.Control(func(fd uintptr) { + for sent < len(real) { + moved, piped, again, e := op.step(fd, sent, inPipe, len(real)) + inPipe += piped - moved + sent += moved + if e != nil || again { + opErr = e + return + } + } + }) + if controlErr != nil { + return false, controlErr + } + return sent == len(real), opErr + }) + if err != nil { + return err + } + // Keep the fake bytes and low hop limit until the kernel transmitted the + // whole prefix once (SIOCOUTQNSD is zero). + return c.poll(remaining(), os.ErrDeadlineExceeded, "fake transmission", func() (bool, error) { + return obs.reached(SplitWaitSent, int64(len(real))) + }) +} diff --git a/fake_linux_test.go b/fake_linux_test.go new file mode 100644 index 0000000..a08617d --- /dev/null +++ b/fake_linux_test.go @@ -0,0 +1,259 @@ +//go:build linux + +package desync + +import ( + "bytes" + "errors" + "fmt" + "io" + "net" + "os" + "syscall" + "testing" + "time" +) + +func openFDs(t testing.TB) int { + t.Helper() + entries, err := os.ReadDir("/proc/self/fd") + if err != nil { + t.Skip(err) + } + return len(entries) +} + +// dropLowHop makes the server's kernel discard every segment that arrives +// with a TTL or hop limit below 8, like a router on a real path would for a +// low-hop transmission. A classic BPF socket filter runs in tcp_v4_rcv / +// tcp_v6_rcv before TCP processing, so a dropped segment is never +// acknowledged and the client must retransmit it. +func dropLowHop(t *testing.T, server *net.TCPConn, ipv6 bool) { + t.Helper() + const skfNetOff = -0x100000 // linux/filter.h SKF_NET_OFF + offset := 8 // IPv4 TTL + if ipv6 { + offset = 7 // IPv6 hop limit + } + prog := []syscall.SockFilter{ + *syscall.LsfStmt(syscall.BPF_LD|syscall.BPF_B|syscall.BPF_ABS, skfNetOff+offset), + *syscall.LsfJump(syscall.BPF_JMP|syscall.BPF_JGE|syscall.BPF_K, 8, 0, 1), + *syscall.LsfStmt(syscall.BPF_RET|syscall.BPF_K, 0x40000), + *syscall.LsfStmt(syscall.BPF_RET|syscall.BPF_K, 0), + } + raw, err := server.SyscallConn() + if err != nil { + t.Fatal(err) + } + var opErr error + if err := raw.Control(func(fd uintptr) { opErr = syscall.AttachLsf(int(fd), prog) }); err != nil { + t.Fatal(err) + } + if errors.Is(opErr, syscall.EPERM) && os.Getenv("DESYNC_REQUIRE_LOWHOP") == "" { + // unprivileged users may not attach this filter on some kernels (the + // GitHub runners); CI runs the test again as root with the variable set + t.Skipf("attaching the drop filter: %v; run as root or set DESYNC_REQUIRE_LOWHOP=1 to fail instead", opErr) + } + if opErr != nil { + t.Fatal(opErr) + } +} + +func linuxFakeRoundTrip(t *testing.T, network string, opts Options, drop bool) { + client, server := loopbackPair(t, network) + if drop { + dropLowHop(t, server, network == "tcp6") + } + hello := captureHello(t, "example.test") + wire := FragmentRecord(hello, resolve(opts.TLSRec, mustParse(t, hello), recordHeaderLen, len(hello))) + if opts.Fake != nil && opts.Fake.Payload == nil { + // Without drops the first transmission reaches the server: a fake + // equal to the real bytes keeps that stream verifiable. + opts.Fake.Payload = wire + } + tail := []byte("after the hello") + want := append(append([]byte(nil), wire...), tail...) + before := tcpHop(t, client) + w := WrapConn(client, opts) + _ = w.SetWriteDeadline(time.Now().Add(10 * time.Second)) + read := readUntil(server, tail) + input := append(append([]byte(nil), hello...), tail...) + if n, err := w.Write(input); err != nil || n != len(input) { + t.Fatalf("Write: %d %v", n, err) + } + if got := <-read; !bytes.Equal(got, want) { + t.Fatalf("server stream changed: got %d bytes, want %d\ngot %q\nwant %q", len(got), len(want), got, want) + } + if after := tcpHop(t, client); after != before { + t.Fatalf("hop limit not restored: %d -> %d", before, after) + } + if drop { + if n, ok := tcpRetransmits(t, client); ok && n == 0 { + t.Fatal("the low-hop transmission was not dropped and retransmitted") + } else if ok { + t.Logf("retransmitted segments: %d", n) + } + } + if len(fakeSlots) != 0 { + t.Fatalf("pending fake resources: %d", len(fakeSlots)) + } +} + +func TestLinuxFakeNativeStream(t *testing.T) { + fds := openFDs(t) + for _, network := range []string{"tcp4", "tcp6"} { + for _, rec := range [][]Pos{nil, {{Offset: 1, FromSNI: true}}} { + for _, prefix := range []int{-1, 1, 40} { + t.Run(fmt.Sprintf("%s/tlsrec=%v/prefix=%d", network, rec, prefix), func(t *testing.T) { + linuxFakeRoundTrip(t, network, Options{TLSRec: rec, Fake: &FakeOptions{TTL: 64, Prefix: prefix}}, false) + }) + } + } + } + if after := openFDs(t); after > fds { + t.Fatalf("file descriptors leaked: %d -> %d", fds, after) + } +} + +// The low-hop transmissions are really dropped here, so the stream is +// byte-identical only if TCP retransmitted the original bytes with the +// restored hop limit. For Fake the first transmission carries different +// bytes: the server never sees them, because the kernel's retransmission +// reads the overwritten page. +func TestLinuxLowHopDropRetransmitsOriginal(t *testing.T) { + garbage := bytes.Repeat([]byte{'X'}, 600) + split := []Pos{{Offset: 1, FromSNI: true}} + rec := []Pos{{Offset: 3, FromSNI: true}} + for name, opts := range map[string]Options{ + "fake": {Fake: &FakeOptions{TTL: 3, Payload: garbage}}, + "fake-tlsrec": {TLSRec: rec, Fake: &FakeOptions{TTL: 3, Payload: garbage, Prefix: 20}}, + "fake-template": {Fake: &FakeOptions{TTL: 3, Payload: defaultFakeTLS()}}, + "disorder": {TLSRec: rec, Split: split, Disorder: true}, + "disoob": {TLSRec: rec, Split: split, Disorder: true, OOB: &OOBOptions{}}, + } { + for _, network := range []string{"tcp4", "tcp6"} { + opts := opts + if opts.Fake != nil { + fake := *opts.Fake + opts.Fake = &fake + } + t.Run(name+"/"+network, func(t *testing.T) { linuxFakeRoundTrip(t, network, opts, true) }) + } + } +} + +// fillSendQueue writes until the peer, which does not read, has a full +// receive window and the client's send buffer holds unsent bytes. +func fillSendQueue(t *testing.T, client, server *net.TCPConn) { + t.Helper() + _ = server.SetReadBuffer(4096) + _ = client.SetWriteBuffer(4096) + _ = client.SetWriteDeadline(time.Now().Add(300 * time.Millisecond)) + _, err := client.Write(make([]byte, 8<<20)) + if !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("filling the queue: %v", err) + } + _ = client.SetWriteDeadline(time.Time{}) +} + +// A blocked fake ends at the deadline, Fake.Timeout or Close, restores the +// hop limit and releases its page, pipe and slot. +func TestLinuxFakeBoundedWhenBlocked(t *testing.T) { + fds := openFDs(t) + for _, mode := range []string{"deadline", "timeout", "close"} { + t.Run(mode, func(t *testing.T) { + client, server := loopbackPair(t, "tcp4") + fillSendQueue(t, client, server) + before := tcpHop(t, client) + opts := Options{Fake: &FakeOptions{TTL: 3, Timeout: time.Minute}} + want := os.ErrDeadlineExceeded + switch mode { + case "timeout": + opts.Fake.Timeout = 50 * time.Millisecond + case "close": + want = net.ErrClosed + } + w := WrapConn(client, opts).(*Conn) + switch mode { + case "deadline": + _ = w.SetWriteDeadline(time.Now().Add(50 * time.Millisecond)) + case "close": + time.AfterFunc(50*time.Millisecond, func() { w.Close() }) + } + real := bytes.Repeat([]byte{'r'}, 300) + start := time.Now() + err := w.sendFake(real, bytes.Repeat([]byte{'f'}, 300), []byte("tail")) + if !errors.Is(err, want) { + t.Fatalf("sendFake: %v, want %v", err, want) + } + if d := time.Since(start); d > 5*time.Second { + t.Fatalf("ended after %v", d) + } + if mode != "close" { + if after := tcpHop(t, client); after != before { + t.Fatalf("hop limit leaked: %d -> %d", before, after) + } + } + if len(fakeSlots) != 0 { + t.Fatalf("pending fake resources: %d", len(fakeSlots)) + } + }) + } + if after := openFDs(t); after > fds { + t.Fatalf("file descriptors leaked: %d -> %d", fds, after) + } +} + +func TestLinuxFakeExpiredDeadlineAllocatesNothing(t *testing.T) { + client, _ := loopbackPair(t, "tcp4") + w := WrapConn(client, Options{Fake: &FakeOptions{TTL: 4}}) + _ = w.SetWriteDeadline(time.Now().Add(-time.Second)) + if _, err := w.Write(captureHello(t, "example.test")); !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("Write: %v", err) + } + if len(fakeSlots) != 0 { + t.Fatal("expired deadline allocated resources") + } +} + +func TestLinuxFakeBoundedResources(t *testing.T) { + client, server := loopbackPair(t, "tcp4") + go func() { _, _ = io.Copy(io.Discard, server) }() + for i := 0; i < cap(fakeSlots); i++ { + fakeSlots <- struct{}{} + } + defer func() { + for len(fakeSlots) > 0 { + <-fakeSlots + } + }() + w := WrapConn(client, Options{Fake: &FakeOptions{TTL: 4}}).(*Conn) + if err := w.sendFake([]byte("ab"), []byte("cd"), []byte("e")); !errors.Is(err, ErrFakeBusy) { + t.Fatalf("resource limit: %v", err) + } +} + +// A prefix larger than one pipe needs several vmsplice/splice rounds. +func TestLinuxFakeLargePrefix(t *testing.T) { + client, server := loopbackPair(t, "tcp4") + real := bytes.Repeat([]byte("0123456789abcdef"), 20<<10) // 320 KiB + tail := []byte("tail") + got := make(chan []byte, 1) + go func() { + _ = server.SetReadDeadline(time.Now().Add(10 * time.Second)) + b := make([]byte, len(real)+len(tail)) + n, _ := io.ReadFull(server, b) + got <- b[:n] + }() + before := tcpHop(t, client) + w := WrapConn(client, Options{Fake: &FakeOptions{TTL: 64, Timeout: 5 * time.Second}}).(*Conn) + if err := w.sendFake(real, real, tail); err != nil { + t.Fatal(err) + } + if b := <-got; !bytes.Equal(b, append(append([]byte(nil), real...), tail...)) { + t.Fatalf("stream changed: %d bytes", len(b)) + } + if after := tcpHop(t, client); after != before { + t.Fatalf("hop limit not restored: %d -> %d", before, after) + } +} diff --git a/fake_other.go b/fake_other.go index 68bd841..4c543b5 100644 --- a/fake_other.go +++ b/fake_other.go @@ -1,4 +1,4 @@ -//go:build !windows +//go:build !windows && !linux package desync diff --git a/fake_reason_other.go b/fake_reason_other.go new file mode 100644 index 0000000..927e1e1 --- /dev/null +++ b/fake_reason_other.go @@ -0,0 +1,5 @@ +//go:build !windows && !linux && !darwin + +package desync + +const fakeUnsupportedReason = "not implemented on this platform" diff --git a/fake_windows.go b/fake_windows.go index c5c54d0..77f5f4a 100644 --- a/fake_windows.go +++ b/fake_windows.go @@ -19,6 +19,9 @@ import ( ) const supportsFake = true + +// fakeUnsupportedReason is unused on Windows, where the fake is implemented. +const fakeUnsupportedReason = "" const wsaIOIncomplete = syscall.Errno(996) var fakeSlots = make(chan struct{}, 64) diff --git a/hop.go b/hop.go new file mode 100644 index 0000000..712d5ee --- /dev/null +++ b/hop.go @@ -0,0 +1,65 @@ +package desync + +import ( + "errors" + "fmt" + "net" + "syscall" +) + +var errNoPeerAddress = errors.New("desync: socket peer has an unsupported address family") + +// savedHop is the socket option that sets the TTL (IPv4) or unicast hop +// limit (IPv6) for one destination, with the value that restores it. +type savedHop struct{ level, option, restore int } + +func sockaddrIP(sa syscall.Sockaddr) (net.IP, error) { + switch a := sa.(type) { + case *syscall.SockaddrInet4: + return net.IP(append([]byte(nil), a.Addr[:]...)), nil + case *syscall.SockaddrInet6: + return net.IP(append([]byte(nil), a.Addr[:]...)), nil + } + return nil, errNoPeerAddress +} + +// lowerHop sets the hop limit for the connected peer of raw to value and +// returns what restores it. A failed change is undone before returning. +func lowerHop(raw syscall.RawConn, value int) (savedHop, error) { + var saved savedHop + var opErr error + err := raw.Control(func(fd uintptr) { + peer, e := socketPeer(fd) + if e != nil { + opErr = e + return + } + if saved, opErr = hopFor(fd, peer); opErr != nil { + return + } + if e := setHop(fd, saved, value); e != nil { + opErr = e + if r := setHop(fd, saved, saved.restore); r != nil { + opErr = fmt.Errorf("%v; restore: %w", e, r) + } + } + }) + if err == nil { + err = opErr + } + return saved, err +} + +// restoreHop restores what lowerHop changed. A closed socket has nothing left +// to restore; its error is returned so that the caller reports it. +func restoreHop(raw syscall.RawConn, saved savedHop) error { + var opErr error + err := raw.Control(func(fd uintptr) { opErr = setHop(fd, saved, saved.restore) }) + if err == nil { + err = opErr + } + if err != nil { + return fmt.Errorf("desync: restore hop limit: %w", err) + } + return nil +} diff --git a/hop_darwin.go b/hop_darwin.go new file mode 100644 index 0000000..efae5d2 --- /dev/null +++ b/hop_darwin.go @@ -0,0 +1,74 @@ +//go:build darwin + +package desync + +import ( + "fmt" + "net" + "os" + "syscall" +) + +// macOS/iOS: an AF_INET socket uses IP_TTL. An AF_INET6 socket rejects +// IPPROTO_IP options (xnu ip6_ctloutput), and IPV6_UNICAST_HOPS sets both its +// IPv6 hop limit and, on a dual-stack socket, the TTL of IPv4-mapped traffic +// (in6p_hops and inp_ip_ttl). Its value -1 means the system default; restoring +// -1 on a dual-stack socket would also set the IPv4 TTL to 255 (the kernel +// casts it to uint8), so there the default is restored as the explicit +// value, and only when both defaults (net.inet6.ip6.hlim, net.inet.ip.ttl) +// are equal. +func hopFor(fd uintptr, _ net.IP) (savedHop, error) { + sa, err := syscall.Getsockname(int(fd)) + if err != nil { + return savedHop{}, os.NewSyscallError("getsockname", err) + } + h := savedHop{level: syscall.IPPROTO_IP, option: syscall.IP_TTL} + if _, ok := sa.(*syscall.SockaddrInet6); ok { + h.level, h.option = syscall.IPPROTO_IPV6, syscall.IPV6_UNICAST_HOPS + } + v, err := syscall.GetsockoptInt(int(fd), h.level, h.option) + if err != nil { + return h, os.NewSyscallError("getsockopt hop limit", err) + } + h.restore = v + if v >= 0 || h.level != syscall.IPPROTO_IPV6 { + return h, nil + } + only, err := syscall.GetsockoptInt(int(fd), syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY) + if err != nil { + return h, os.NewSyscallError("getsockopt IPV6_V6ONLY", err) + } + if only != 0 { + return h, nil + } + hlim, err := syscall.SysctlUint32("net.inet6.ip6.hlim") + if err != nil { + return h, os.NewSyscallError("sysctl net.inet6.ip6.hlim", err) + } + ttl, err := syscall.SysctlUint32("net.inet.ip.ttl") + if err != nil { + return h, os.NewSyscallError("sysctl net.inet.ip.ttl", err) + } + if hlim != ttl || hlim < 1 || hlim > 255 { + return h, fmt.Errorf("desync: cannot restore the hop limits of a dual-stack socket: default IPv6 hop limit %d differs from default TTL %d", hlim, ttl) + } + h.restore = int(hlim) + return h, nil +} + +func setHop(fd uintptr, h savedHop, value int) error { + return os.NewSyscallError("setsockopt hop limit", syscall.SetsockoptInt(int(fd), h.level, h.option, value)) +} + +func socketPeer(fd uintptr) (net.IP, error) { + sa, err := syscall.Getpeername(int(fd)) + if err != nil { + return nil, os.NewSyscallError("getpeername", err) + } + return sockaddrIP(sa) +} + +// Disorder cannot observe unsent bytes here. It writes the low-hop piece only +// once SO_NWRITE reports an empty send buffer, so the kernel builds the +// segment within the send call; that transmission is inferred, not observed. +var platformDisorder = DisorderCapability{Supported: true, Mechanism: "SO_NWRITE"} diff --git a/hop_linux.go b/hop_linux.go new file mode 100644 index 0000000..0b1019e --- /dev/null +++ b/hop_linux.go @@ -0,0 +1,42 @@ +//go:build linux + +package desync + +import ( + "net" + "os" + "syscall" +) + +// Linux and Android: an IPv4 or IPv4-mapped destination uses IP_TTL (also on +// an AF_INET6 socket, where the kernel sends mapped traffic through IPv4), an +// IPv6 destination IPV6_UNICAST_HOPS. getsockopt returns the effective value, +// including the system default. +func hopFor(fd uintptr, dst net.IP) (savedHop, error) { + h := savedHop{level: syscall.IPPROTO_IP, option: syscall.IP_TTL} + if dst.To4() == nil { + h.level, h.option = syscall.IPPROTO_IPV6, syscall.IPV6_UNICAST_HOPS + } + v, err := syscall.GetsockoptInt(int(fd), h.level, h.option) + if err != nil { + return h, os.NewSyscallError("getsockopt hop limit", err) + } + h.restore = v + return h, nil +} + +func setHop(fd uintptr, h savedHop, value int) error { + return os.NewSyscallError("setsockopt hop limit", syscall.SetsockoptInt(int(fd), h.level, h.option, value)) +} + +func socketPeer(fd uintptr) (net.IP, error) { + sa, err := syscall.Getpeername(int(fd)) + if err != nil { + return nil, os.NewSyscallError("getpeername", err) + } + return sockaddrIP(sa) +} + +// Disorder waits until SIOCOUTQNSD reports no unsent bytes, so the low-hop +// piece was transmitted before the hop limit is restored. +var platformDisorder = DisorderCapability{Supported: true, Mechanism: "SIOCOUTQNSD", Observed: true, Reliable: true} diff --git a/hop_other.go b/hop_other.go new file mode 100644 index 0000000..32d988e --- /dev/null +++ b/hop_other.go @@ -0,0 +1,16 @@ +//go:build !linux && !darwin && !windows + +package desync + +import ( + "errors" + "net" +) + +var errHopUnsupported = errors.New("desync: changing the hop limit is not implemented on this platform") + +func hopFor(uintptr, net.IP) (savedHop, error) { return savedHop{}, errHopUnsupported } +func setHop(uintptr, savedHop, int) error { return errHopUnsupported } +func socketPeer(uintptr) (net.IP, error) { return nil, errHopUnsupported } + +var platformDisorder = DisorderCapability{} diff --git a/hop_windows.go b/hop_windows.go new file mode 100644 index 0000000..57e3fc5 --- /dev/null +++ b/hop_windows.go @@ -0,0 +1,41 @@ +//go:build windows + +package desync + +import ( + "net" + "os" + "syscall" +) + +// Windows: select the option by the destination family. Reading IP_TTL can +// succeed on an IPv6-only socket although setting it fails, and an +// IPv4-mapped destination on a dual-stack socket uses IP_TTL. +func hopFor(fd uintptr, dst net.IP) (savedHop, error) { + h := savedHop{level: syscall.IPPROTO_IP, option: syscall.IP_TTL} + if dst.To4() == nil { + h.level, h.option = syscall.IPPROTO_IPV6, syscall.IPV6_UNICAST_HOPS + } + v, err := getsockoptInt(syscall.Handle(fd), h.level, h.option) + if err != nil { + return h, os.NewSyscallError("getsockopt hop limit", err) + } + h.restore = v + return h, nil +} + +func setHop(fd uintptr, h savedHop, value int) error { + return os.NewSyscallError("setsockopt hop limit", syscall.SetsockoptInt(syscall.Handle(fd), h.level, h.option, value)) +} + +func socketPeer(fd uintptr) (net.IP, error) { + sa, err := syscall.Getpeername(syscall.Handle(fd)) + if err != nil { + return nil, os.NewSyscallError("getpeername", err) + } + return sockaddrIP(sa) +} + +// Disorder waits until SIO_TCP_INFO counts the low-hop piece as sent; the +// counters are not reliable (see AckCapability.Reliable). +var platformDisorder = DisorderCapability{Supported: true, Mechanism: "SIO_TCP_INFO", Observed: true} diff --git a/key.go b/key.go index 9537a3f..86a6c91 100644 --- a/key.go +++ b/key.go @@ -78,6 +78,13 @@ func (o Options) Key() string { b.WriteString(",timeout:") b.WriteString(strconv.FormatInt(int64(o.SplitWaitTimeout), 10)) } + if o.Disorder { + b.WriteString(";disorder=1") + } + if o.OOB != nil { + b.WriteString(";oob=") + b.WriteString(strconv.Itoa(int(o.OOB.urgentByte()))) + } return b.String() } diff --git a/oob_other.go b/oob_other.go new file mode 100644 index 0000000..7f7669c --- /dev/null +++ b/oob_other.go @@ -0,0 +1,9 @@ +//go:build !linux && !darwin && !windows + +package desync + +import "syscall" + +const supportsOOB = false + +func sendOOB(syscall.RawConn, []byte) (int, error) { return 0, ErrOOBUnsupported } diff --git a/oob_unix.go b/oob_unix.go new file mode 100644 index 0000000..8ab5730 --- /dev/null +++ b/oob_unix.go @@ -0,0 +1,29 @@ +//go:build linux || darwin + +package desync + +import ( + "os" + "syscall" +) + +const supportsOOB = true + +// sendOOB writes p with MSG_OOB, which marks its last byte as urgent data. +// It waits for socket space through the runtime poller, so the underlying +// connection's write deadline and Close bound it. +func sendOOB(raw syscall.RawConn, p []byte) (int, error) { + var n int + var opErr error + err := raw.Write(func(fd uintptr) bool { + n, opErr = syscall.SendmsgN(int(fd), p, nil, nil, syscall.MSG_OOB) + return opErr != syscall.EAGAIN && opErr != syscall.EINTR + }) + if n < 0 { + n = 0 + } + if err == nil && opErr != nil { + err = os.NewSyscallError("sendmsg MSG_OOB", opErr) + } + return n, err +} diff --git a/oob_windows.go b/oob_windows.go new file mode 100644 index 0000000..712cc12 --- /dev/null +++ b/oob_windows.go @@ -0,0 +1,27 @@ +//go:build windows + +package desync + +import ( + "os" + "syscall" +) + +const supportsOOB = true + +const msgOOB = 0x1 // winsock2.h MSG_OOB + +// sendOOB writes p with MSG_OOB, which marks its last byte as urgent data. The +// send is synchronous (no OVERLAPPED), so Go's completion port never sees it. +func sendOOB(raw syscall.RawConn, p []byte) (int, error) { + var sent uint32 + var opErr error + err := raw.Control(func(fd uintptr) { + buf := syscall.WSABuf{Len: uint32(len(p)), Buf: &p[0]} + opErr = syscall.WSASend(syscall.Handle(fd), &buf, 1, &sent, msgOOB, nil, nil) + }) + if err == nil && opErr != nil { + err = os.NewSyscallError("WSASend MSG_OOB", opErr) + } + return int(sent), err +} diff --git a/packet_darwin.go b/packet_darwin.go new file mode 100644 index 0000000..1058ed2 --- /dev/null +++ b/packet_darwin.go @@ -0,0 +1,9 @@ +//go:build darwin + +package desync + +// suppressUDPErrors has nothing to do on macOS: udp_ctlinput delivers an ICMP +// error only to a socket whose foreign address and port match exactly +// (in_pcblookup_hash without wildcard), so an unconnected socket never sees +// the time-exceeded replies to the low-TTL datagrams. +func suppressUDPErrors(uintptr) error { return nil } diff --git a/packet_errors_unix_test.go b/packet_errors_unix_test.go new file mode 100644 index 0000000..7ac6200 --- /dev/null +++ b/packet_errors_unix_test.go @@ -0,0 +1,98 @@ +//go:build linux || darwin + +package desync + +import ( + "errors" + "net" + "os" + "runtime" + "syscall" + "testing" + "time" +) + +// closedUDPPort returns a loopback address nothing listens on, so a datagram +// to it draws an ICMP port-unreachable reply. +func closedUDPPort(t *testing.T) *net.UDPAddr { + t.Helper() + c, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}) + if err != nil { + t.Fatal(err) + } + addr := c.LocalAddr().(*net.UDPAddr) + c.Close() + return addr +} + +func setRecvErr(t *testing.T, c *net.UDPConn, on int) { + t.Helper() + if runtime.GOOS != "linux" { + return + } + raw, err := c.SyscallConn() + if err != nil { + t.Fatal(err) + } + var opErr error + if err := raw.Control(func(fd uintptr) { + opErr = syscall.SetsockoptInt(int(fd), syscall.IPPROTO_IP, 0xb, on) // IP_RECVERR + }); err != nil || opErr != nil { + t.Fatal(err, opErr) + } +} + +// readAfterICMP sends one datagram to a closed port and reports what the next +// ReadFrom returns. +func readAfterICMP(t *testing.T, pc net.PacketConn, to net.Addr) error { + t.Helper() + if _, err := pc.WriteTo([]byte("probe"), to); err != nil { + t.Fatal(err) + } + _ = pc.SetReadDeadline(time.Now().Add(300 * time.Millisecond)) + _, _, err := pc.ReadFrom(make([]byte, 64)) + return err +} + +// ICMP errors caused by the burst must not surface on the owned socket. A +// port-unreachable reply on loopback takes the same path as a time-exceeded +// reply on a real route (udp_err / udp_ctlinput). +func TestUDPFakeSuppressesICMPErrors(t *testing.T) { + to := closedUDPPort(t) + if runtime.GOOS == "linux" { + // Control: with IP_RECVERR on, the error reaches ReadFrom. + c, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}) + if err != nil { + t.Fatal(err) + } + setRecvErr(t, c, 1) + err = readAfterICMP(t, c, to) + c.Close() + if !errors.Is(err, syscall.ECONNREFUSED) { + t.Fatalf("control without suppression: %v, want ECONNREFUSED", err) + } + } + c, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}) + if err != nil { + t.Fatal(err) + } + setRecvErr(t, c, 1) + wrapped, err := WrapPacketConn(c, UDPOptions{TTL: 4, Repeats: 2}) + if err != nil { + c.Close() + t.Fatal(err) + } + defer wrapped.Close() + if err := readAfterICMP(t, wrapped, to); !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("ReadFrom after ICMP error: %v, want a timeout", err) + } + if runtime.GOOS == "linux" { + raw, _ := c.SyscallConn() + var v int + var opErr error + _ = raw.Control(func(fd uintptr) { v, opErr = syscall.GetsockoptInt(int(fd), syscall.IPPROTO_IP, 0xb) }) + if opErr != nil || v != 0 { + t.Fatalf("IP_RECVERR after wrap: %d %v", v, opErr) + } + } +} diff --git a/packet_linux.go b/packet_linux.go new file mode 100644 index 0000000..4786c9b --- /dev/null +++ b/packet_linux.go @@ -0,0 +1,37 @@ +//go:build linux + +package desync + +import ( + "os" + "syscall" +) + +// suppressUDPErrors keeps the ICMP time-exceeded replies to the low-TTL +// datagrams from surfacing on this owned socket. Linux reports ICMP errors on +// an unconnected UDP socket only with IP_RECVERR/IPV6_RECVERR enabled (see +// __udp4_lib_err/__udp6_lib_err: without it, a soft error such as time +// exceeded is dropped, and a hard one is reported only on a connected +// socket). Both are off by default; if the caller enabled them, they are +// turned off, otherwise a time-exceeded reply would fail the next ReadFrom +// with EHOSTUNREACH and be queued on the error queue. +func suppressUDPErrors(fd uintptr) error { + options := [][2]int{{syscall.IPPROTO_IP, syscall.IP_RECVERR}} + if sa, err := syscall.Getsockname(int(fd)); err == nil { + if _, ok := sa.(*syscall.SockaddrInet6); ok { + options = append(options, [2]int{syscall.IPPROTO_IPV6, syscall.IPV6_RECVERR}) + } + } + for _, o := range options { + v, err := syscall.GetsockoptInt(int(fd), o[0], o[1]) + if err != nil { + return os.NewSyscallError("getsockopt RECVERR", err) + } + if v != 0 { + if err := syscall.SetsockoptInt(int(fd), o[0], o[1], 0); err != nil { + return os.NewSyscallError("setsockopt RECVERR", err) + } + } + } + return nil +} diff --git a/packet_other.go b/packet_other.go index b8212dc..3dcc8fc 100644 --- a/packet_other.go +++ b/packet_other.go @@ -1,4 +1,4 @@ -//go:build !windows +//go:build !windows && !linux && !darwin package desync diff --git a/packet_unix.go b/packet_unix.go new file mode 100644 index 0000000..099040f --- /dev/null +++ b/packet_unix.go @@ -0,0 +1,64 @@ +//go:build linux || darwin + +package desync + +import ( + "errors" + "fmt" + "io" + "net" + "syscall" +) + +const supportsUDPFake = true + +func configureUDPFake(raw syscall.RawConn) error { + var opErr error + err := raw.Control(func(fd uintptr) { + kind, err := syscall.GetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_TYPE) + if err != nil || kind != syscall.SOCK_DGRAM { + opErr = ErrUDPFakeRequiresSocket + return + } + opErr = suppressUDPErrors(fd) + }) + return errors.Join(err, opErr) +} + +func sendUDPFake(pc net.PacketConn, raw syscall.RawConn, opts UDPOptions, addr net.Addr) (unsafeTTL bool, err error) { + var dst net.IP + if udp, ok := addr.(*net.UDPAddr); ok { + dst = udp.IP + } + var opErr error + controlErr := raw.Control(func(fd uintptr) { + // The option follows the destination family (see hopFor), so an + // IPv4 peer on a dual-stack socket gets the IPv4 TTL changed. + saved, getErr := hopFor(fd, dst) + if getErr != nil { + opErr = fmt.Errorf("desync: read UDP hop limit: %w", getErr) + return + } + if setErr := setHop(fd, saved, opts.TTL); setErr != nil { + opErr = fmt.Errorf("desync: set UDP fake hop limit: %w", setErr) + unsafeTTL = true + return + } + for i := 0; i < opts.Repeats; i++ { + n, sendErr := pc.WriteTo(opts.Payload, addr) + if sendErr == nil && n != len(opts.Payload) { + sendErr = io.ErrShortWrite + } + if sendErr != nil { + opErr = sendErr + break + } + opts.Counters.fakes.Add(1) + } + if restoreErr := setHop(fd, saved, saved.restore); restoreErr != nil { + unsafeTTL = true + opErr = errors.Join(opErr, fmt.Errorf("desync: restore UDP hop limit: %w", restoreErr)) + } + }) + return unsafeTTL, errors.Join(controlErr, opErr) +} diff --git a/packet_unix_test.go b/packet_unix_test.go new file mode 100644 index 0000000..65c226b --- /dev/null +++ b/packet_unix_test.go @@ -0,0 +1,206 @@ +//go:build linux || darwin + +package desync + +import ( + "bytes" + "errors" + "net" + "net/netip" + "os" + "sync" + "testing" + "time" +) + +func udpSocketTTL(c *net.UDPConn) (int, error) { + return udpSocketTTLFor(c, c.LocalAddr().(*net.UDPAddr).IP) +} + +func udpSocketTTLFor(c *net.UDPConn, destination net.IP) (int, error) { + raw, err := c.SyscallConn() + if err != nil { + return 0, err + } + var value int + var operationErr error + err = raw.Control(func(fd uintptr) { + var h savedHop + h, operationErr = hopFor(fd, destination) + value = h.restore + }) + return value, errors.Join(err, operationErr) +} + +type udpRecordedWrite struct { + ttl int + data []byte +} +type udpRecordingConn struct { + *net.UDPConn + writes []udpRecordedWrite + failFake bool +} + +func (c *udpRecordingConn) WriteTo(p []byte, addr net.Addr) (int, error) { + ttl, err := udpSocketTTLFor(c.UDPConn, addr.(*net.UDPAddr).IP) + if err != nil { + return 0, err + } + c.writes = append(c.writes, udpRecordedWrite{ttl: ttl, data: append([]byte(nil), p...)}) + if c.failFake && ttl == 4 { + return 0, errors.New("injected send failure") + } + return c.UDPConn.WriteTo(p, addr) +} + +func TestUDPFakeNativeOrderSourcePortTTLAndConcurrentWrites(t *testing.T) { + for _, tc := range []struct{ network, address, serverNetwork, serverAddress string }{{"udp4", "127.0.0.1:0", "udp4", "127.0.0.1:0"}, {"udp6", "[::1]:0", "udp6", "[::1]:0"}, {"udp", "[::]:0", "udp4", "127.0.0.1:0"}} { + t.Run(tc.network, func(t *testing.T) { + server, err := net.ListenPacket(tc.serverNetwork, tc.serverAddress) + if err != nil { + if tc.network == "udp6" { + t.Skip(err) + } + t.Fatal(err) + } + defer server.Close() + client, err := net.ListenPacket(tc.network, tc.address) + if err != nil { + t.Fatal(err) + } + recorder := &udpRecordingConn{UDPConn: client.(*net.UDPConn)} + originalTTL, err := udpSocketTTLFor(recorder.UDPConn, server.LocalAddr().(*net.UDPAddr).IP) + if err != nil { + t.Fatal(err) + } + fakePayload := []byte("fake-datagram") + wrapped, err := WrapPacketConn(recorder, UDPOptions{TTL: 4, Repeats: 2, Packets: 3, Payload: fakePayload}) + if err != nil { + client.Close() + t.Fatal(err) + } + defer wrapped.Close() + fakePayload[0] = 'X' // options must own the buffer + const originals = 20 + var writers sync.WaitGroup + for i := 0; i < originals; i++ { + writers.Add(1) + go func() { + defer writers.Done() + if _, err := wrapped.WriteTo([]byte("original-datagram"), server.LocalAddr()); err != nil { + t.Error(err) + } + }() + } + writers.Wait() + if ttl, err := udpSocketTTLFor(recorder.UDPConn, server.LocalAddr().(*net.UDPAddr).IP); err != nil || ttl != originalTTL { + t.Fatalf("TTL leaked: %d want %d: %v", ttl, originalTTL, err) + } + if len(recorder.writes) != originals+6 { + t.Fatalf("unbounded or missing injections: %d", len(recorder.writes)) + } + if !bytes.Equal(recorder.writes[0].data, []byte("fake-datagram")) { + t.Fatal("first packet was not the independent fake payload") + } + for _, write := range recorder.writes { + want := originalTTL + if bytes.Equal(write.data, []byte("fake-datagram")) { + want = 4 + } else if !bytes.Equal(write.data, []byte("original-datagram")) { + t.Fatalf("application payload changed: %q", write.data) + } + if write.ttl != want { + t.Fatalf("wrong TTL at actual UDP write: %d want %d", write.ttl, want) + } + } + if err := server.SetReadDeadline(time.Now().Add(2 * time.Second)); err != nil { + t.Fatal(err) + } + for i, write := range recorder.writes { + buf := make([]byte, 256) + n, source, err := server.ReadFrom(buf) + if err != nil { + t.Fatal(err) + } + if source.(*net.UDPAddr).Port != client.LocalAddr().(*net.UDPAddr).Port || !bytes.Equal(buf[:n], write.data) { + t.Fatalf("datagram %d/order/source changed: %s %q", i, source, buf[:n]) + } + } + stats := wrapped.Counters() + if stats.Packets != originals || stats.FakePackets != 6 || stats.FakeErrors != 0 || stats.Peers != 1 { + t.Fatalf("wrong counters: %+v", stats) + } + }) + } +} + +func TestUDPFakeRestoresTTLOnFailureAndDeadlineRecovery(t *testing.T) { + server, err := net.ListenPacket("udp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer server.Close() + client, err := net.ListenPacket("udp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + recorder := &udpRecordingConn{UDPConn: client.(*net.UDPConn), failFake: true} + originalTTL, err := udpSocketTTL(recorder.UDPConn) + if err != nil { + t.Fatal(err) + } + wrapped, err := WrapPacketConn(recorder, UDPOptions{TTL: 4, Repeats: 1, Packets: 3}) + if err != nil { + client.Close() + t.Fatal(err) + } + defer wrapped.Close() + if _, err := wrapped.WriteTo([]byte("original"), server.LocalAddr()); err == nil { + t.Fatal("lost fake send failure") + } + if ttl, err := udpSocketTTL(recorder.UDPConn); err != nil || ttl != originalTTL { + t.Fatalf("failure leaked TTL: %d %v", ttl, err) + } + recorder.failFake = false + if err := wrapped.SetWriteDeadline(time.Now().Add(-time.Second)); err != nil { + t.Fatal(err) + } + if _, err := wrapped.WriteTo([]byte("original"), server.LocalAddr()); !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("lost deadline: %v", err) + } + if ttl, err := udpSocketTTL(recorder.UDPConn); err != nil || ttl != originalTTL { + t.Fatalf("deadline leaked TTL: %d %v", ttl, err) + } + if err := wrapped.SetWriteDeadline(time.Time{}); err != nil { + t.Fatal(err) + } + if _, err := wrapped.WriteTo([]byte("original"), server.LocalAddr()); err != nil { + t.Fatalf("deadline could not be reset: %v", err) + } + if err := wrapped.Close(); err != nil { + t.Fatal(err) + } + if _, err := wrapped.WriteTo([]byte("original"), server.LocalAddr()); !errors.Is(err, net.ErrClosed) { + t.Fatalf("lost Close: %v", err) + } +} + +func TestUDPPeerTrackingIsBounded(t *testing.T) { + c := &PacketConn{opts: UDPOptions{Packets: 1, Counters: &UDPCounters{}}, peers: make(map[netip.AddrPort]udpPeer)} + for i := 1; i <= 64; i++ { + if !c.shouldInject(&net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 1000 + i}) { + t.Fatal("missing peer") + } + } + if c.shouldInject(&net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 9000}) || len(c.peers) != 64 { + t.Fatal("peer map is not bounded") + } + for peer, state := range c.peers { + state.last = time.Now().Add(-3 * time.Minute) + c.peers[peer] = state + } + if !c.shouldInject(&net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 9000}) || len(c.peers) != 1 { + t.Fatal("expired peers were not reclaimed") + } +} diff --git a/sockopt_other_test.go b/sockopt_other_test.go new file mode 100644 index 0000000..a5c9de7 --- /dev/null +++ b/sockopt_other_test.go @@ -0,0 +1,5 @@ +//go:build !linux && !darwin && !windows + +package desync + +func setOOBInline(uintptr) error { return ErrOOBUnsupported } diff --git a/sockopt_unix_test.go b/sockopt_unix_test.go new file mode 100644 index 0000000..3ff8fe8 --- /dev/null +++ b/sockopt_unix_test.go @@ -0,0 +1,9 @@ +//go:build linux || darwin + +package desync + +import "syscall" + +func setOOBInline(fd uintptr) error { + return syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_OOBINLINE, 1) +} diff --git a/sockopt_windows_test.go b/sockopt_windows_test.go index 18d8218..27299f9 100644 --- a/sockopt_windows_test.go +++ b/sockopt_windows_test.go @@ -58,3 +58,7 @@ func TestGetsockoptIntRoundTrip(t *testing.T) { t.Fatalf("IPv6 hop limit: %d %v", hops, err) } } + +func setOOBInline(fd uintptr) error { + return syscall.SetsockoptInt(syscall.Handle(fd), syscall.SOL_SOCKET, 0x0100, 1) // SO_OOBINLINE +} diff --git a/tcpinfo_linux_386_test.go b/tcpinfo_linux_386_test.go new file mode 100644 index 0000000..1a5d78c --- /dev/null +++ b/tcpinfo_linux_386_test.go @@ -0,0 +1,12 @@ +//go:build linux && 386 + +package desync + +import ( + "net" + "testing" +) + +// linux/386 reaches getsockopt through socketcall; the retransmission count +// is not read there. +func tcpRetransmits(testing.TB, *net.TCPConn) (uint32, bool) { return 0, false } diff --git a/tcpinfo_linux_test.go b/tcpinfo_linux_test.go new file mode 100644 index 0000000..4fa04bd --- /dev/null +++ b/tcpinfo_linux_test.go @@ -0,0 +1,32 @@ +//go:build linux && !386 + +package desync + +import ( + "net" + "syscall" + "testing" + "unsafe" +) + +// tcpRetransmits returns tcpi_total_retrans of the connection. +func tcpRetransmits(t testing.TB, c *net.TCPConn) (uint32, bool) { + t.Helper() + raw, err := c.SyscallConn() + if err != nil { + t.Fatal(err) + } + var info syscall.TCPInfo + size := uint32(syscall.SizeofTCPInfo) + var errno syscall.Errno + if err := raw.Control(func(fd uintptr) { + _, _, errno = syscall.Syscall6(syscall.SYS_GETSOCKOPT, fd, syscall.IPPROTO_TCP, syscall.TCP_INFO, + uintptr(unsafe.Pointer(&info)), uintptr(unsafe.Pointer(&size)), 0) + }); err != nil { + t.Fatal(err) + } + if errno != 0 { + t.Fatal(errno) + } + return info.Total_retrans, true +} diff --git a/third_party/NOTICE b/third_party/NOTICE new file mode 100644 index 0000000..6588f7d --- /dev/null +++ b/third_party/NOTICE @@ -0,0 +1,20 @@ +Third-party material in this module +=================================== + +ByeDPI (https://github.com/hufrea/byedpi), MIT License, Copyright (c) 2024 +hufrea. The license text is in BYEDPI-LICENSE. Derived from it: + +- fake_payload.go: the default fake TLS ClientHello template (packets.c, + v0.17.3), copied byte for byte. +- fake_windows.go: the TransmitFile mechanism of the Windows fake (send the + prefix from a temporary file with a low TTL, rewrite the file with the + original bytes for the retransmission), desync.c send_fake for _WIN32. +- fake_linux.go: the Linux fake mechanism (vmsplice a page holding the fake + bytes into a pipe, splice it to the socket with a low TTL, wait until it was + sent, overwrite the page with the original bytes, restore the TTL), + desync.c send_fake and restore_state for __linux__. Reimplemented in Go; + the mapping is MAP_SHARED instead of MAP_PRIVATE. +- disorder.go: the semantics of --disorder (hop limit 1 for a piece, restored + before the next one), --oob and --disoob (the piece and one urgent byte sent + with MSG_OOB), desync.c DESYNC_DISORDER, DESYNC_OOB, DESYNC_DISOOB and + send_oob. Reimplemented in Go; the default urgent byte 'a' is ByeDPI's.