Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
47 changes: 35 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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}},
Expand All @@ -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{
Expand All @@ -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")
Expand All @@ -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
Expand All @@ -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.
Expand All @@ -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).
57 changes: 44 additions & 13 deletions capability.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -263,36 +286,44 @@ 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++ {
deadline, changed, err := c.writeState()
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()
Expand Down
21 changes: 17 additions & 4 deletions capability_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand Down
34 changes: 31 additions & 3 deletions cmd/desync-socks/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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}
}
Expand All @@ -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 {
Expand All @@ -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))
Expand Down
Loading
Loading