diff --git a/core/cmd/mistgate-clientd/main.go b/core/cmd/mistgate-clientd/main.go index 9a69e82..552c020 100644 --- a/core/cmd/mistgate-clientd/main.go +++ b/core/cmd/mistgate-clientd/main.go @@ -277,6 +277,7 @@ func run(ctx context.Context, useFake bool, dataDir, verify string, powerEvents fmt.Fprintln(os.Stderr, "cannot open geo cache:", err) return err } + geoStore.SetServices(engine.ServiceDomains) // "service:" in the rules: the services of the bypass set slog.SetDefault(logger.With("src", "engine")) var eng engine.Engine var routeState session.RouteState @@ -311,6 +312,7 @@ func run(ctx context.Context, useFake bool, dataDir, verify string, powerEvents real := engine.NewReal(store.Profiles, settingsStore.Get, geoStore, verify) eng = real real.AllowDest = proxy.AllowedAddr + real.BypassMemory = filepath.Join(dataDir, "bypass-memory.json") dialVPN = real.DialVPN homeAddr = real.HomeAddr routeState.Effective = real.EffectiveRoute diff --git a/core/go.mod b/core/go.mod index 9e60e98..05a0e96 100644 --- a/core/go.mod +++ b/core/go.mod @@ -8,9 +8,10 @@ require ( github.com/apernet/hysteria/core/v2 v2.12.3 github.com/apernet/hysteria/extras/v2 v2.12.3 github.com/apernet/quic-go v0.62.1-0.20260912175848-73339f7edbb9 + github.com/mistgate/mistgate-bypass v0.0.0-20261201095031-c314645ccddf + github.com/refraction-networking/utls v1.8.3-0.20261108164504-a13c59ffe98b github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b github.com/xtls/xray-core v1.260327.1-0.20261109052709-676eaf66f8f0 - github.com/refraction-networking/utls v1.8.3-0.20261108164504-a13c59ffe98b go.yaml.in/yaml/v3 v3.0.5 golang.org/x/net v0.62.0 golang.org/x/sys v0.49.0 diff --git a/core/go.sum b/core/go.sum index 5b60cf5..88e5fe2 100644 --- a/core/go.sum +++ b/core/go.sum @@ -48,6 +48,8 @@ github.com/libp2p/go-netroute v0.2.1 h1:V8kVrpD8GK0Riv15/7VN6RbUQ3URNZVosw7H2v9t github.com/libp2p/go-netroute v0.2.1/go.mod h1:hraioZr0fhBjG0ZRXJJ6Zj2IVEVNx6tDTFQfSmcq7mQ= github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE= github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ= +github.com/mistgate/mistgate-bypass v0.0.0-20261201095031-c314645ccddf h1:jQN2RguMYC+SmdXPXwgPpAj3ugFU0FO5TkkhDB4wVDM= +github.com/mistgate/mistgate-bypass v0.0.0-20261201095031-c314645ccddf/go.mod h1:TfIRVeC42AaZoZNo6e/ZwpxPpZGeaCWDkMERR2Wzp2I= github.com/molecule-man/go-brrr v1.2.0 h1:dOJU45BC3Gc2WXoxAW0rgCAgVuu2gruAOGncfieA0Jw= github.com/molecule-man/go-brrr v1.2.0/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4= github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= diff --git a/core/internal/engine/bypass_dns_windows.go b/core/internal/engine/bypass_dns_windows.go new file mode 100644 index 0000000..7179350 --- /dev/null +++ b/core/internal/engine/bypass_dns_windows.go @@ -0,0 +1,355 @@ +//go:build windows + +package engine + +import ( + "bytes" + "context" + "encoding/binary" + "io" + "net" + "net/netip" + "sync" + "time" + + "github.com/mistgate/mistgate-client/core/internal/netcfg" + "github.com/mistgate/mistgate-client/core/internal/safe" +) + +// dnsChainStick is how long the DoH step that gave the last real answer is asked first. +var dnsChainStick = 10 * time.Minute + +// dnsChainSlots bounds the questions the chain works on at once; one past it gets SERVFAIL at once. +const dnsChainSlots = 64 + +// dnsStep is one way of asking: it returns the answer, or nil after its own wait. +type dnsStep interface { + ask(ctx context.Context, query []byte) []byte +} + +// The grades of an answer, worst first. The chain goes on past anything below dnsGood and gives the best it saw. +const ( + dnsNone = iota // none, truncated, or the resolver's own failure (SERVFAIL, REFUSED…) + dnsNoName // NXDOMAIN: public resolvers do not know the local and company names the physical one knows + dnsStub // stubAnswer: a resolver that blocks, or a name that really points at a private address + dnsGood +) + +func gradeAnswer(answer []byte) int { + if len(answer) < 12 || answer[2]&0x02 != 0 { // TC + return dnsNone + } + switch answer[3] & 0x0f { + case 0: + if stubAnswer(answer) { + return dnsStub + } + return dnsGood + case 3: + return dnsNoName + } + return dnsNone +} + +// dnsChain is where the questions of a run with no tunnel go: the steps in order until a good answer (gradeAnswer). +// The first sticky steps (DoH: a path cannot forge them) are asked first for dnsChainStick once one answered. +type dnsChain struct { + steps []dnsStep + sticky int + slots chan struct{} // nil: no bound + mu sync.Mutex + first int + until time.Time +} + +// newDNSChain is the built-in order: DoH by address (no name to cut by), plain UDP to public resolvers (a path may +// forge it), the physical interface's own resolvers. +// ponytail: no DoH by name through a bypass strategy yet, and the order is not the set's; both come with the set (step 9). +func newDNSChain(ctx context.Context) *dnsChain { + var steps []dnsStep + for _, raw := range []string{"https://1.1.1.1/dns-query", "https://8.8.8.8/dns-query"} { + if d := newDoH(ctx, raw, nil, directOutbound{}, netip.Addr{}); d != nil { + steps = append(steps, dohStep{d}) + } + } + sticky := len(steps) + public := []netip.Addr{netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("1.1.1.1"), netip.MustParseAddr("9.9.9.9")} + steps = append(steps, + udpStep{servers: func() []netip.Addr { return public }}, + udpStep{servers: netcfg.PhysicalDNS4}, + ) + return &dnsChain{steps: steps, sticky: sticky, slots: make(chan struct{}, dnsChainSlots)} +} + +func (c *dnsChain) exchange(ctx context.Context, query []byte) []byte { + if len(query) < 12 { + return nil + } + if c.slots != nil { + select { + case c.slots <- struct{}{}: + defer func() { <-c.slots }() + default: + return nil + } + } + c.mu.Lock() + start := 0 + if time.Now().Before(c.until) { + start = c.first + } + c.mu.Unlock() + var best []byte + grade := dnsNone + for i := range c.steps { + step := (start + i) % len(c.steps) + answer := c.steps[step].ask(ctx, query) + if g := gradeAnswer(answer); g == dnsGood { + if step < c.sticky { + c.mu.Lock() + c.first, c.until = step, time.Now().Add(dnsChainStick) + c.mu.Unlock() + } + return answer + } else if g > grade { + best, grade = answer, g + } + if ctx.Err() != nil { + break + } + } + return best +} + +func (c *dnsChain) close() { + for _, step := range c.steps { + if d, ok := step.(dohStep); ok { + d.close() + } + } +} + +type dohStep struct{ *dohResolver } + +// ask skips a resolver that is resting, and a failure of its own rests it: a dead one would cost every question its wait. +func (d dohStep) ask(ctx context.Context, query []byte) []byte { + if !d.ready() { + return nil + } + answer := d.dohResolver.ask(ctx, query) + if answer == nil && ctx.Err() == nil { + d.rest() + } + return answer +} + +// udpStep sends the question to every server at once. A good answer or NXDOMAIN is taken at once (one dead server must +// not cost every name its wait); else the best one after all have answered or the wait is over. +type udpStep struct{ servers func() []netip.Addr } + +func (s udpStep) ask(ctx context.Context, query []byte) []byte { + servers := s.servers() + if len(servers) == 0 { + return nil + } + ctx, cancel := context.WithTimeout(ctx, dnsDirectWait) + defer cancel() + answers := make(chan []byte, len(servers)) + for _, server := range servers { + go func() { + answers <- askUDP(ctx, netip.AddrPortFrom(server, 53), query) + }() + } + var best []byte + grade := dnsNone + for range servers { + answer := <-answers + switch g := gradeAnswer(answer); { + case g == dnsGood || g == dnsNoName: + return answer + case g > grade: + best, grade = answer, g + } + } + return best +} + +// askUDP asks one resolver over the physical interface; an answer counts only with the question's id and question. +func askUDP(ctx context.Context, server netip.AddrPort, query []byte) []byte { + conn, err := directPacketConn(ctx, server) + if err != nil { + return nil + } + defer conn.Close() + deadline, _ := ctx.Deadline() + _ = conn.SetDeadline(deadline) + if _, err := conn.WriteTo(query, net.UDPAddrFromAddrPort(server)); err != nil { + return nil + } + _, end, questionOK := dnsQuestion(query) + buf := make([]byte, 65535) + for { + n, from, err := conn.ReadFrom(buf) + if err != nil { + return nil + } + answer := buf[:n] + source, ok := from.(*net.UDPAddr) + if !ok || source.AddrPort().Addr().Unmap() != server.Addr() || n < 12 || answer[0] != query[0] || answer[1] != query[1] || answer[2]&0x80 == 0 { + continue + } + if questionOK && (n < end || !bytes.Equal(answer[12:end], query[12:end])) { + continue + } + return append([]byte(nil), answer...) + } +} + +// noTunnelOutbound stands for the VPN in a run with no server: DNS (UDP and TCP port 53) is answered by the chain. +// Other TCP the bridge would send to a VPN (private addresses beyond the gateway, IPv6: its probe finds out whether +// the machine has IPv6) goes direct when direct is set, else nowhere. +// ponytail: UDP to such addresses has nowhere to go; a flow that also writes direct would carry it. +type noTunnelOutbound struct { + chain *dnsChain + direct outbound +} + +func (o noTunnelOutbound) DialTCP(ctx context.Context, target netip.AddrPort) (net.Conn, error) { + if target.Port() != 53 { + if o.direct == nil { + return nil, ErrNoTunnel + } + return o.direct.DialTCP(ctx, target) + } + if err := ctx.Err(); err != nil { + return nil, err + } + app, ours := net.Pipe() + go o.serveTCP(ctx, ours) + return app, nil +} + +// serveTCP answers length-prefixed questions (RFC 1035 4.2.2) one by one until the other side closes. ctx is the run's: +// a question in flight when the program goes away still runs to its wait, which the chain's slots bound. +func (o noTunnelOutbound) serveTCP(ctx context.Context, conn net.Conn) { + defer conn.Close() + defer func() { + if r := recover(); r != nil { + safe.Report("dns over tcp", r) + } + }() + for { + var size [2]byte + if _, err := io.ReadFull(conn, size[:]); err != nil { + return + } + query := make([]byte, binary.BigEndian.Uint16(size[:])) + if _, err := io.ReadFull(conn, query); err != nil { + return + } + askCtx, cancel := context.WithTimeout(ctx, 4*dnsDirectWait+2*dohWait) + answer := o.chain.answer(askCtx, query) + cancel() + if answer == nil || len(answer) > 65535 { + return + } + reply := binary.BigEndian.AppendUint16(make([]byte, 0, 2+len(answer)), uint16(len(answer))) + if _, err := conn.Write(append(reply, answer...)); err != nil { + return + } + } +} + +// answer is exchange with the question's id, and SERVFAIL when the chain has nothing: the program stops waiting at +// once. nil only for a query too short to answer. +func (c *dnsChain) answer(ctx context.Context, query []byte) []byte { + answer := c.exchange(ctx, query) + if answer == nil { + return serverFailure(query) + } + copy(answer[:2], query[:2]) + return answer +} + +// serverFailure turns a query into SERVFAIL, in place; a question it cannot read is left out. +func serverFailure(query []byte) []byte { + if len(query) < 12 { + return nil + } + _, end, ok := dnsQuestion(query) + if !ok { + end = 12 + clear(query[4:6]) + } + answer := noData(query, end) + answer[3] = 0x82 + return answer +} + +func (o noTunnelOutbound) ListenUDP(ctx context.Context) (packetFlow, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + ctx, cancel := context.WithCancel(ctx) + return &chainFlow{chain: o.chain, ctx: ctx, cancel: cancel, answers: make(chan chainAnswer, 16)}, nil +} + +type chainAnswer struct { + payload []byte + from netip.AddrPort +} + +// chainFlow is a UDP flow to a DNS server that the chain answers for: every question is asked on its own goroutine, +// and the answers come back from the address the question was sent to. +type chainFlow struct { + chain *dnsChain + ctx context.Context + cancel context.CancelFunc + answers chan chainAnswer +} + +func (f *chainFlow) WriteTo(payload []byte, to netip.AddrPort) error { + if to.Port() != 53 { + return ErrNoTunnel + } + if err := f.ctx.Err(); err != nil { + return net.ErrClosed + } + query := append([]byte(nil), payload...) + go func() { + defer func() { + if r := recover(); r != nil { + safe.Report("dns chain", r) + } + }() + answer := f.chain.answer(f.ctx, query) + if answer == nil || f.ctx.Err() != nil { + return + } + select { + case f.answers <- chainAnswer{answer, to}: + case <-f.ctx.Done(): + } + }() + return nil +} + +func (f *chainFlow) ReadFrom() ([]byte, netip.AddrPort, error) { + select { + case a := <-f.answers: + return a.payload, a.from, nil + case <-f.ctx.Done(): + return nil, netip.AddrPort{}, net.ErrClosed + } +} + +func (f *chainFlow) Close() error { + f.cancel() + return nil +} + +// bypassDNS is what DNS flows do differently in a run with no server: a stub answer of a direct resolver goes to the +// chain, and a name always says whether the bypass works on it (such a name gets no HTTPS record). +type bypassDNS struct { + always func(name string) bool +} diff --git a/core/internal/engine/bypass_dns_windows_test.go b/core/internal/engine/bypass_dns_windows_test.go new file mode 100644 index 0000000..85ea889 --- /dev/null +++ b/core/internal/engine/bypass_dns_windows_test.go @@ -0,0 +1,202 @@ +//go:build windows + +package engine + +import ( + "bytes" + "context" + "encoding/binary" + "io" + "net/netip" + "sync/atomic" + "testing" + "time" + + "golang.org/x/net/dns/dnsmessage" +) + +func dnsAnswerA(t *testing.T, query []byte, address string) []byte { + t.Helper() + var p dnsmessage.Parser + header, err := p.Start(query) + if err != nil { + t.Fatal(err) + } + question, err := p.Question() + if err != nil { + t.Fatal(err) + } + header.Response = true + b := dnsmessage.NewBuilder(nil, header) + _ = b.StartQuestions() + _ = b.Question(question) + _ = b.StartAnswers() + _ = b.AResource(dnsmessage.ResourceHeader{Name: question.Name, Class: dnsmessage.ClassINET, TTL: 60}, dnsmessage.AResource{A: netip.MustParseAddr(address).As4()}) + out, err := b.Finish() + if err != nil { + t.Fatal(err) + } + return out +} + +type fakeStep struct { + calls atomic.Int32 + answer func(query []byte) []byte +} + +func (s *fakeStep) ask(_ context.Context, query []byte) []byte { + s.calls.Add(1) + return s.answer(query) +} + +func TestStubAnswer(t *testing.T) { + query := dnsQuery(t, 1, "example.com", dnsmessage.TypeA, dnsmessage.ClassINET) + for address, want := range map[string]bool{"0.0.0.0": true, "127.0.0.1": true, "10.1.2.3": true, "198.18.0.5": true, "93.184.215.14": false} { + if got := stubAnswer(dnsAnswerA(t, query, address)); got != want { + t.Errorf("stubAnswer(%s) = %t", address, got) + } + } + if stubAnswer(query) || stubAnswer([]byte{1, 2}) { + t.Error("a question or garbage counted as a stub answer") + } +} + +// withRcode is an answer with its RCODE and TC set as given. +func withRcode(answer []byte, rcode byte, truncated bool) []byte { + answer = append([]byte(nil), answer...) + answer[3] = answer[3]&0xf0 | rcode + if truncated { + answer[2] |= 0x02 + } + return answer +} + +func TestDNSChainOrderStubsAndStick(t *testing.T) { + query := dnsQuery(t, 7, "example.com", dnsmessage.TypeA, dnsmessage.ClassINET) + good := func(q []byte) []byte { return dnsAnswerA(t, q, "93.184.215.14") } + failing := &fakeStep{answer: func(q []byte) []byte { return withRcode(good(q), 2, false) }} // SERVFAIL + truncated := &fakeStep{answer: func(q []byte) []byte { return withRcode(good(q), 0, true) }} // TC + stub := &fakeStep{answer: func(q []byte) []byte { return dnsAnswerA(t, q, "0.0.0.0") }} + doh := &fakeStep{answer: good} + chain := &dnsChain{steps: []dnsStep{failing, truncated, stub, doh}, sticky: 4} + if answer := chain.exchange(context.Background(), query); gradeAnswer(answer) != dnsGood { + t.Fatalf("answer = %v", answer) + } + if failing.calls.Load() != 1 || truncated.calls.Load() != 1 || stub.calls.Load() != 1 || doh.calls.Load() != 1 { + t.Fatal("not every step was asked in order") + } + // a sticky step that answered is asked first now + _ = chain.exchange(context.Background(), query) + if failing.calls.Load() != 1 || doh.calls.Load() != 2 { + t.Fatalf("second: %d %d", failing.calls.Load(), doh.calls.Load()) + } + // and only for a while + chain.until = time.Now().Add(-time.Second) + _ = chain.exchange(context.Background(), query) + if failing.calls.Load() != 2 { + t.Fatalf("after the stick: %d", failing.calls.Load()) + } + // a step past the sticky ones does not stick + chain = &dnsChain{steps: []dnsStep{failing, doh}, sticky: 1} + _ = chain.exchange(context.Background(), query) + if !chain.until.IsZero() { + t.Fatal("a plain UDP step stuck") + } + + // nothing good: the best seen comes back, a stub over NXDOMAIN (a local name the physical resolver knows) + noName := &fakeStep{answer: func(q []byte) []byte { return withRcode(good(q), 3, false) }} + if answer := (&dnsChain{steps: []dnsStep{noName, stub, failing}}).exchange(context.Background(), query); gradeAnswer(answer) != dnsStub { + t.Fatalf("best = %v", answer) + } + if answer := (&dnsChain{steps: []dnsStep{failing, noName}}).exchange(context.Background(), query); gradeAnswer(answer) != dnsNoName { + t.Fatalf("NXDOMAIN = %v", answer) + } + if (&dnsChain{steps: []dnsStep{failing, truncated}}).exchange(context.Background(), query) != nil { + t.Fatal("failures came back as an answer") + } + + // full slots: no step is asked + full := &dnsChain{steps: []dnsStep{doh}, slots: make(chan struct{}, 1)} + full.slots <- struct{}{} + before := doh.calls.Load() + if full.exchange(context.Background(), query) != nil || doh.calls.Load() != before { + t.Fatal("a question past the slots was asked") + } + // and the program gets SERVFAIL with its id and question + reply := full.answer(context.Background(), append([]byte(nil), query...)) + if len(reply) != len(query) || reply[0] != 0 || reply[1] != 7 || reply[3]&0x0f != 2 || reply[2]&0x80 == 0 || !bytes.Equal(reply[12:], query[12:]) { + t.Fatalf("SERVFAIL = %v", reply) + } +} + +func TestNoTunnelOutbound(t *testing.T) { + good := &fakeStep{answer: func(q []byte) []byte { + answer := dnsAnswerA(t, q, "93.184.215.14") + answer[0], answer[1] = 0, 0 // a resolver may answer with id 0 + return answer + }} + out := noTunnelOutbound{chain: &dnsChain{steps: []dnsStep{good}}} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if _, err := out.DialTCP(ctx, netip.MustParseAddrPort("192.0.2.1:443")); err != ErrNoTunnel { + t.Fatalf("DialTCP 443: %v", err) + } + + // UDP: the answer comes back from where the question went, with the question's id + flow, err := out.ListenUDP(ctx) + if err != nil { + t.Fatal(err) + } + if err := flow.WriteTo([]byte("x"), netip.MustParseAddrPort("192.0.2.1:443")); err != ErrNoTunnel { + t.Fatalf("WriteTo 443: %v", err) + } + server := netip.MustParseAddrPort("198.18.0.2:53") + query := dnsQuery(t, 0x1234, "example.com", dnsmessage.TypeA, dnsmessage.ClassINET) + if err := flow.WriteTo(query, server); err != nil { + t.Fatal(err) + } + answer, from, err := flow.ReadFrom() + if err != nil || from != server || answer[0] != 0x12 || answer[1] != 0x34 || stubAnswer(answer) { + t.Fatalf("ReadFrom = %v, %v, %v", answer, from, err) + } + _ = flow.Close() + if _, _, err := flow.ReadFrom(); err == nil { + t.Fatal("a closed flow reads") + } + + // TCP: two questions on one connection + conn, err := out.DialTCP(ctx, netip.MustParseAddrPort("198.18.0.2:53")) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(5 * time.Second)) + for _, id := range []uint16{1, 2} { + query := dnsQuery(t, id, "example.com", dnsmessage.TypeA, dnsmessage.ClassINET) + if _, err := conn.Write(append(binary.BigEndian.AppendUint16(nil, uint16(len(query))), query...)); err != nil { + t.Fatal(err) + } + var size [2]byte + if _, err := io.ReadFull(conn, size[:]); err != nil { + t.Fatal(err) + } + answer := make([]byte, binary.BigEndian.Uint16(size[:])) + if _, err := io.ReadFull(conn, answer); err != nil { + t.Fatal(err) + } + if binary.BigEndian.Uint16(answer) != id || !bytes.Equal(answer[12:len(query)], query[12:]) { + t.Fatalf("tcp answer %d = %v", id, answer) + } + } +} + +func TestNoTunnelOutboundSendsOtherTCPDirect(t *testing.T) { + server := newLoopServer(t, true) + direct := &loopOutbound{addr: server.ln.Addr().String()} + out := noTunnelOutbound{chain: &dnsChain{}, direct: direct} + conn, err := out.DialTCP(context.Background(), netip.MustParseAddrPort("10.1.2.3:8080")) + if err != nil || direct.dials.Load() != 1 { + t.Fatalf("DialTCP to a private address: %v, %d direct dials", err, direct.dials.Load()) + } + _ = conn.Close() +} diff --git a/core/internal/engine/bypass_set.go b/core/internal/engine/bypass_set.go new file mode 100644 index 0000000..43797d1 --- /dev/null +++ b/core/internal/engine/bypass_set.go @@ -0,0 +1,22 @@ +package engine + +import "github.com/mistgate/mistgate-bypass/sets" + +// bypassSet is the set of strategies in use. ponytail: the one built into the library; delivery of newer ones (signed +// files, the panel's seq) is a step of its own and swaps this for an atomic pointer. +var bypassSet = sets.Embedded + +// ServiceDomains is the catalogue for geo.Store.SetServices: the domains of a service of the set, every part. +func ServiceDomains(id string) []string { + for _, service := range bypassSet().Services { + if service.ID != id { + continue + } + var domains []string + for _, part := range service.Parts { + domains = append(domains, part.Domains...) + } + return domains + } + return nil +} diff --git a/core/internal/engine/bypass_tcp_windows.go b/core/internal/engine/bypass_tcp_windows.go new file mode 100644 index 0000000..946bb39 --- /dev/null +++ b/core/internal/engine/bypass_tcp_windows.go @@ -0,0 +1,128 @@ +//go:build windows + +package engine + +import ( + "context" + "errors" + "net" + "net/netip" + "time" + + "github.com/mistgate/mistgate-bypass/flow" + "github.com/mistgate/mistgate-client/core/internal/geo" +) + +// bypassFlows is the bypass of a run: the ladder for direct TLS flows, and the QUIC it refuses. nil (the bridge's +// default) leaves every flow on the path it had before. +type bypassFlows struct { + flows *flow.Flows + // never: the name is an exception (the user's direct selection), and its flows are not touched. + never func(name string) bool + // quicOff: QUIC to the name is refused, so that the browser takes TCP, where the ladder works. + quicOff func(name string) bool + // fallback: there is a VPN to send a flow to when the ladder finds no way; false in a run with no server. + fallback bool +} + +func (b *gvisorBridge) setBypass(l *bypassFlows) { b.bypass.Store(l) } + +// openTCP takes a TLS flow the bridge has read the name of, when the bypass is on and the flow goes direct: it opens +// it through the ladder and starts the copy. false: not such a flow, and the caller dials it as before. hello is all +// that was read from the application; it holds the ClientHello first. +func (b *gvisorBridge) openTCP(local net.Conn, target netip.AddrPort, name string, sniffed []byte, app appVerdict, watching bool) bool { + l := b.bypass.Load() + if l == nil || app != appNone || target.Port() != 443 || name == "" || l.never != nil && l.never(name) { + return false + } + end := tlsHelloEnd(sniffed) + if end == 0 { + return false + } + if _, route := selectOutbound(target, name, nil, b.shouldDirect, app, b.vpn, b.direct); route != geo.ViaDirect { + return false + } + result, err := l.flows.Open(b.ctx, name, sniffed[:end], func(ctx context.Context) (*net.TCPConn, error) { + conn, err := b.direct.DialTCP(ctx, target) + if err != nil { + return nil, err + } + tcp, ok := conn.(*net.TCPConn) + if !ok { // not a socket a strategy can be applied to + _ = conn.Close() + return nil, errors.ErrUnsupported + } + return tcp, nil + }) + now := time.Now() + var remote net.Conn + var watch *flowWatch + switch { + case err == nil: + remote = result.Conn + if watching && result.Silent { + watch = &flowWatch{track: b.track, route: geo.ViaDirect, name: name} + } else if watching { + b.track.OK(geo.ViaDirect, name, now) + } + if len(result.First) > 0 { + if _, err := local.Write(result.First); err != nil { + _ = local.Close() + _ = remote.Close() + return true + } + } + sniffed = sniffed[end:] // the application's bytes after the ClientHello, which the ladder held back + case l.fallback && (errors.Is(err, flow.ErrNoWay) || errors.Is(err, flow.ErrUnreachable)): + if watching { + b.track.Fail(geo.ViaDirect, name, now) + } + if remote, err = b.vpn.DialTCP(b.ctx, target); err != nil { + if watching && b.ctx.Err() == nil { + b.track.Fail(geo.ViaVPN, name, now) + } + _ = local.Close() + return true + } + if watching { + watch = &flowWatch{track: b.track, route: geo.ViaVPN, name: name} + } + default: + if watching && b.ctx.Err() == nil { + b.track.Fail(geo.ViaDirect, name, now) + } + _ = local.Close() + return true + } + for len(sniffed) > 0 { + n, err := remote.Write(sniffed) + sniffed = sniffed[n:] + if err != nil || n == 0 { + _ = local.Close() + _ = remote.Close() + return true + } + } + if !b.startForward(func() { proxyTCP(local, remote, watch) }) { + _ = local.Close() + _ = remote.Close() + } + return true +} + +// refusesQUIC says whether a new UDP flow to port 443 is QUIC the bypass turns away: a name the resolver gave its +// address has its QUIC off and is no exception. It runs on the packet pump, before the program is known, so it only +// reads memory and asks neither the route nor the program: a refused flow costs no more than the browser's fallback +// to TCP, even when that TCP goes through the VPN or by a program's rule. +func (b *gvisorBridge) refusesQUIC(target netip.AddrPort) bool { + l := b.bypass.Load() + if l == nil || l.quicOff == nil || target.Port() != 443 { + return false + } + for _, name := range b.dns.lookupNames(target.Addr()) { + if l.quicOff(name) && (l.never == nil || !l.never(name)) { + return true + } + } + return false +} diff --git a/core/internal/engine/bypass_tcp_windows_test.go b/core/internal/engine/bypass_tcp_windows_test.go new file mode 100644 index 0000000..43c6817 --- /dev/null +++ b/core/internal/engine/bypass_tcp_windows_test.go @@ -0,0 +1,244 @@ +//go:build windows + +package engine + +import ( + "bytes" + "context" + "io" + "net" + "net/netip" + "sync/atomic" + "testing" + "time" + + "github.com/mistgate/mistgate-bypass/flow" +) + +// loopServer accepts on loopback; answer: every connection gets a TLS-looking reply to its first bytes, else silence. +// got carries everything one connection received before it closed. +type loopServer struct { + ln net.Listener + got chan []byte +} + +func newLoopServer(t *testing.T, answer bool) *loopServer { + t.Helper() + ln, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + s := &loopServer{ln: ln, got: make(chan []byte, 16)} + t.Cleanup(func() { _ = ln.Close() }) + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + go func() { + defer conn.Close() + var all []byte + buf := make([]byte, 4096) + answered := false + for { + _ = conn.SetReadDeadline(time.Now().Add(3 * time.Second)) + n, err := conn.Read(buf) + all = append(all, buf[:n]...) + if n > 0 && answer && !answered { + answered = true + _, _ = conn.Write([]byte{0x16, 3, 3, 0, 1, 2}) + } + if err != nil { + s.got <- all + return + } + } + }() + } + }() + return s +} + +// loopOutbound dials its server whatever the target, and counts. +type loopOutbound struct { + addr string + dials atomic.Int32 +} + +func (o *loopOutbound) DialTCP(ctx context.Context, _ netip.AddrPort) (net.Conn, error) { + o.dials.Add(1) + var d net.Dialer + return d.DialContext(ctx, "tcp4", o.addr) +} + +func (o *loopOutbound) ListenUDP(context.Context) (packetFlow, error) { return nil, ErrNoTunnel } + +var bypassTarget = netip.MustParseAddrPort("93.184.215.14:443") + +func bypassBridge(t *testing.T, direct, vpn *loopOutbound, toDirect bool) *gvisorBridge { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + b := &gvisorBridge{ctx: ctx, cancel: cancel, direct: direct, vpn: vpn, dns: &dnsMemory{entries: map[netip.Addr]dnsEntry{}}, + shouldDirect: func(netip.Addr, string, []string) bool { return toDirect }} + t.Cleanup(func() { + cancel() + b.wg.Wait() + }) + return b +} + +func quickFlows() *flow.Flows { + return flow.New(flow.Config{Timing: flow.Timing{TMin: 40 * time.Millisecond, TMax: 80 * time.Millisecond, Budget: 400 * time.Millisecond, MaxAttempts: 2}}) +} + +// openAndRead runs openTCP with the app on the other end of a pipe; it returns what openTCP said and the first bytes +// the app got (none when the flow was closed). +func openAndRead(t *testing.T, b *gvisorBridge, sniffed []byte) (bool, []byte) { + t.Helper() + app, local := net.Pipe() + t.Cleanup(func() { _ = app.Close() }) + took := make(chan bool, 1) + go func() { took <- b.openTCP(local, bypassTarget, "example.com", sniffed, appNone, false) }() + _ = app.SetReadDeadline(time.Now().Add(3 * time.Second)) + buf := make([]byte, 6) // the reply the test servers send; it may come in more than one piece + n, _ := io.ReadFull(app, buf) + select { + case handled := <-took: + return handled, buf[:n] + case <-time.After(3 * time.Second): + t.Fatal("openTCP did not return") + return false, nil + } +} + +func TestOpenTCPLeavesFlowsAloneWithoutTheBypass(t *testing.T) { + server := newLoopServer(t, true) + direct, vpn := &loopOutbound{addr: server.ln.Addr().String()}, &loopOutbound{addr: server.ln.Addr().String()} + hello := captureClientHello(t, "example.com") + + b := bypassBridge(t, direct, vpn, true) + local, other := net.Pipe() + defer local.Close() + defer other.Close() + if b.openTCP(local, bypassTarget, "example.com", hello, appNone, false) { + t.Fatal("no bypass, yet openTCP took the flow") + } + b.setBypass(&bypassFlows{flows: quickFlows(), never: func(name string) bool { return name == "example.com" }}) + if b.openTCP(local, bypassTarget, "example.com", hello, appNone, false) { + t.Fatal("an exception went through the ladder") + } + b.setBypass(&bypassFlows{flows: quickFlows()}) + for _, c := range []struct { + target netip.AddrPort + app appVerdict + data []byte + }{ + {netip.MustParseAddrPort("93.184.215.14:8443"), appNone, hello}, // not 443 + {bypassTarget, appDirect, hello}, // a program's own rule + {bypassTarget, appNone, []byte("GET / HTTP/1.1\r\n\r\n")}, // not TLS + } { + if b.openTCP(local, c.target, "example.com", c.data, c.app, false) { + t.Errorf("openTCP took %v %v", c.target, c.app) + } + } + if direct.dials.Load() != 0 || vpn.dials.Load() != 0 { + t.Fatalf("dials: %d direct, %d vpn", direct.dials.Load(), vpn.dials.Load()) + } + // a flow the rules send through the VPN + if bypassBridge(t, direct, vpn, false).openTCP(local, bypassTarget, "example.com", hello, appNone, false) || direct.dials.Load() != 0 { + t.Fatal("a VPN flow went through the ladder") + } +} + +func TestOpenTCPAnsweredDirect(t *testing.T) { + server := newLoopServer(t, true) + direct, vpn := &loopOutbound{addr: server.ln.Addr().String()}, &loopOutbound{addr: server.ln.Addr().String()} + b := bypassBridge(t, direct, vpn, true) + b.setBypass(&bypassFlows{flows: quickFlows(), fallback: true}) + hello := captureClientHello(t, "example.com") + handled, first := openAndRead(t, b, append(append([]byte(nil), hello...), "EARLY"...)) + if !handled || !bytes.Equal(first, []byte{0x16, 3, 3, 0, 1, 2}) { + t.Fatalf("openTCP = %t, app got %v", handled, first) + } + b.cancel() + _ = server.ln.Close() + select { + case got := <-server.got: + if !bytes.HasPrefix(got, hello) || !bytes.HasSuffix(got, []byte("EARLY")) || len(got) != len(hello)+5 { + t.Fatalf("the server got %d bytes", len(got)) + } + case <-time.After(5 * time.Second): + t.Fatal("the server saw nothing") + } + if vpn.dials.Load() != 0 { + t.Fatal("an answered flow went to the VPN") + } +} + +func TestOpenTCPFallsBackToTheVPN(t *testing.T) { + silent, answering := newLoopServer(t, false), newLoopServer(t, true) + direct, vpn := &loopOutbound{addr: silent.ln.Addr().String()}, &loopOutbound{addr: answering.ln.Addr().String()} + b := bypassBridge(t, direct, vpn, true) + b.setBypass(&bypassFlows{flows: quickFlows(), fallback: true}) + hello := captureClientHello(t, "example.com") + sniffed := append(append([]byte(nil), hello...), "EARLY"...) + handled, first := openAndRead(t, b, sniffed) + if !handled || !bytes.Equal(first, []byte{0x16, 3, 3, 0, 1, 2}) || vpn.dials.Load() != 1 || direct.dials.Load() == 0 { + t.Fatalf("openTCP = %t, app got %v, dials %d direct %d vpn", handled, first, direct.dials.Load(), vpn.dials.Load()) + } + b.cancel() + _ = answering.ln.Close() + if got := <-answering.got; !bytes.Equal(got, sniffed) { + t.Fatalf("the VPN side got %d bytes, want the %d read from the app", len(got), len(sniffed)) + } +} + +func TestOpenTCPWithoutFallbackClosesTheFlow(t *testing.T) { + server := newLoopServer(t, true) + direct := &loopOutbound{addr: "127.0.0.1:1"} // refused: unreachable + vpn := &loopOutbound{addr: server.ln.Addr().String()} + b := bypassBridge(t, direct, vpn, true) + b.setBypass(&bypassFlows{flows: quickFlows()}) + handled, first := openAndRead(t, b, captureClientHello(t, "example.com")) + if !handled || len(first) != 0 || vpn.dials.Load() != 0 { + t.Fatalf("openTCP = %t, app got %v, vpn dials %d", handled, first, vpn.dials.Load()) + } +} + +func TestRefusesQUIC(t *testing.T) { + b := bypassBridge(t, &loopOutbound{}, &loopOutbound{}, true) + address := bypassTarget.Addr() + b.dns.rememberAddressAt(address, "video.example", time.Minute, time.Now()) + quic := netip.AddrPortFrom(address, 443) + if b.refusesQUIC(quic) { + t.Fatal("refused without the bypass") + } + b.setBypass(&bypassFlows{flows: quickFlows(), quicOff: func(name string) bool { return name == "video.example" }}) + if !b.refusesQUIC(quic) { + t.Fatal("QUIC to a name with QUIC off was let through") + } + if b.refusesQUIC(netip.AddrPortFrom(address, 8443)) || b.refusesQUIC(netip.MustParseAddrPort("93.184.215.15:443")) { + t.Fatal("refused another flow") + } + b.setBypass(&bypassFlows{flows: quickFlows(), quicOff: func(string) bool { return true }, never: func(string) bool { return true }}) + if b.refusesQUIC(quic) { + t.Fatal("refused QUIC to an exception") + } +} + +func TestTLSHelloEnd(t *testing.T) { + hello := captureClientHello(t, "example.com") + if got := tlsHelloEnd(append(append([]byte(nil), hello...), "EARLY"...)); got != len(hello) { + t.Fatalf("tlsHelloEnd = %d, want %d", got, len(hello)) + } + recordLength := int(hello[3])<<8 | int(hello[4]) + payload := hello[5 : 5+recordLength] + two := appendTLSRecord(appendTLSRecord(nil, hello[1:3], payload[:10]), hello[1:3], payload[10:]) + if got := tlsHelloEnd(two); got != len(two) { + t.Fatalf("two records: %d, want %d", got, len(two)) + } + if tlsHelloEnd(hello[:len(hello)-1]) != 0 || tlsHelloEnd([]byte("GET /")) != 0 { + t.Fatal("an incomplete or foreign start has an end") + } +} diff --git a/core/internal/engine/dns.go b/core/internal/engine/dns.go index c6847db..b9da3b0 100644 --- a/core/internal/engine/dns.go +++ b/core/internal/engine/dns.go @@ -7,6 +7,7 @@ import ( "github.com/mistgate/mistgate-client/core/internal/geo" "github.com/mistgate/mistgate-client/core/internal/profile" + "golang.org/x/net/dns/dnsmessage" ) const ( @@ -154,3 +155,49 @@ func tunnelDNS(lists ...[]netip.Addr) []netip.Addr { } return nil } + +// stubAnswer says whether an answer gives an address no public service has: unspecified, loopback, private, shared or +// reserved space. Resolvers that block a name answer with such addresses, so the answer is no answer. +func stubAnswer(message []byte) bool { + var parser dnsmessage.Parser + if _, err := parser.Start(message); err != nil || parser.SkipAllQuestions() != nil { + return false + } + answers, err := parser.AllAnswers() + if err != nil { + return false + } + for _, answer := range answers { + var address netip.Addr + switch body := answer.Body.(type) { + case *dnsmessage.AResource: + address = netip.AddrFrom4(body.A) + case *dnsmessage.AAAAResource: + address = netip.AddrFrom16(body.AAAA).Unmap() + default: + continue + } + if stubAddr(address) { + return true + } + } + return false +} + +var stubNets = []netip.Prefix{ + netip.MustParsePrefix("100.64.0.0/10"), netip.MustParsePrefix("192.0.0.0/24"), netip.MustParsePrefix("192.0.2.0/24"), + netip.MustParsePrefix("198.18.0.0/15"), netip.MustParsePrefix("198.51.100.0/24"), netip.MustParsePrefix("203.0.113.0/24"), + netip.MustParsePrefix("240.0.0.0/4"), +} + +func stubAddr(a netip.Addr) bool { + if a.IsUnspecified() || a.IsLoopback() || a.IsPrivate() || !a.IsGlobalUnicast() { + return true + } + for _, p := range stubNets { + if p.Contains(a) { + return true + } + } + return false +} diff --git a/core/internal/engine/dns_flow_windows_test.go b/core/internal/engine/dns_flow_windows_test.go index bfd466e..043b382 100644 --- a/core/internal/engine/dns_flow_windows_test.go +++ b/core/internal/engine/dns_flow_windows_test.go @@ -79,6 +79,12 @@ func newDNSRig(t *testing.T, names func(string) (bool, netip.AddrPort)) *dnsRig // newDNSRigDoH is newDNSRig with the preset's DoH resolver for the questions that go through the VPN. func newDNSRigDoH(t *testing.T, names func(string) (bool, netip.AddrPort), doh *dohResolver) *dnsRig { + t.Helper() + return newDNSRigWith(t, names, doh, nil) +} + +// newDNSRigWith is newDNSRigDoH in a run with no server when bypass is set. +func newDNSRigWith(t *testing.T, names func(string) (bool, netip.AddrPort), doh *dohResolver, bypass *bypassDNS) *dnsRig { t.Helper() rig := &dnsRig{vpn: newScriptFlow(), direct: newScriptFlow()} rig.out = &countOutbound{flow: rig.direct} @@ -91,7 +97,7 @@ func newDNSRigDoH(t *testing.T, names func(string) (bool, netip.AddrPort), doh * rig.asked.Add(1) return names(name) }, - direct: rig.out, down: new(atomic.Int64), doh: doh, + direct: rig.out, down: new(atomic.Int64), doh: doh, bypass: func() *bypassDNS { return bypass }, } rig.flow.lastActivity.Store(time.Now().UnixNano()) done := make(chan struct{}) @@ -328,3 +334,70 @@ func TestUDPFlowAnswersAAAAWithNoDataWhenTheVPNHasNoIPv6(t *testing.T) { t.Fatal("the A question did not go through the VPN") } } + +func TestUDPFlowWithoutServerSendsStubAnswersToTheChain(t *testing.T) { + rig := newDNSRigWith(t, func(string) (bool, netip.AddrPort) { return false, testResolver }, nil, &bypassDNS{}) + query := dnsQuery(t, 0x0C0D, "blocked.example", dnsmessage.TypeA, dnsmessage.ClassINET) + rig.ask(t, query) + recvPacket(t, rig.direct) + rig.direct.recv <- scriptPacket{replyFor(t, query, 0x0C0D, [4]byte{0, 0, 0, 0}), testResolver} + // at once, not after dnsDirectWait, and the app does not see the stub + select { + case got := <-rig.vpn.sent: + <-rig.vpn.targets + if string(got) != string(query) { + t.Fatal("another question went to the chain") + } + case <-time.After(dnsDirectWait / 2): + t.Fatal("the stub answer did not send the question to the chain") + } + rig.silent(t) + if rig.flow.down.Load() != 0 { + t.Fatal("one stub rested the provider's resolver") + } + // a real answer is the app's as before + query = dnsQuery(t, 0x0C0E, "fine.example", dnsmessage.TypeA, dnsmessage.ClassINET) + rig.ask(t, query) + recvPacket(t, rig.direct) + answer := replyFor(t, query, 0x0C0E, [4]byte{93, 184, 215, 14}) + rig.direct.recv <- scriptPacket{answer, testResolver} + if string(rig.heard(t)) != string(answer) { + t.Fatal("the app got another answer") + } + nothingSent(t, rig.vpn) +} + +func TestUDPFlowStubAnswersStayInTheVPNModes(t *testing.T) { + rig := newDNSRig(t, func(string) (bool, netip.AddrPort) { return false, testResolver }) + query := dnsQuery(t, 0x0C0F, "blocked.example", dnsmessage.TypeA, dnsmessage.ClassINET) + rig.ask(t, query) + recvPacket(t, rig.direct) + answer := replyFor(t, query, 0x0C0F, [4]byte{0, 0, 0, 0}) + rig.direct.recv <- scriptPacket{answer, testResolver} + if string(rig.heard(t)) != string(answer) { + t.Fatal("a VPN mode changed what the regional resolver said") + } +} + +func TestUDPFlowWithoutServerGivesBypassNamesNoHTTPSRecord(t *testing.T) { + rig := newDNSRigWith(t, func(string) (bool, netip.AddrPort) { return false, netip.AddrPort{} }, nil, + &bypassDNS{always: func(name string) bool { return name == "video.example" }}) + rig.ask(t, dnsQuery(t, 0x0D01, "video.example", dnsmessage.TypeHTTPS, dnsmessage.ClassINET)) + var parser dnsmessage.Parser + header, err := parser.Start(rig.heard(t)) + if err != nil || header.ID != 0x0D01 || !header.Response || header.RCode != dnsmessage.RCodeSuccess { + t.Fatalf("answer header = %+v, %v", header, err) + } + if err := parser.SkipAllQuestions(); err != nil { + t.Fatal(err) + } + if all, err := parser.AllAnswers(); err != nil || len(all) != 0 { + t.Fatalf("answers = %v, %v", all, err) + } + nothingSent(t, rig.vpn) + // its A record, and another name's HTTPS record, are asked as usual + rig.ask(t, dnsQuery(t, 0x0D02, "video.example", dnsmessage.TypeA, dnsmessage.ClassINET)) + recvPacket(t, rig.vpn) + rig.ask(t, dnsQuery(t, 0x0D03, "other.example", dnsmessage.TypeHTTPS, dnsmessage.ClassINET)) + recvPacket(t, rig.vpn) +} diff --git a/core/internal/engine/gvisor_bridge_windows.go b/core/internal/engine/gvisor_bridge_windows.go index 3db9904..7c48a7e 100644 --- a/core/internal/engine/gvisor_bridge_windows.go +++ b/core/internal/engine/gvisor_bridge_windows.go @@ -67,6 +67,11 @@ type gvisorBridge struct { // server without IPv6). Asked once when the tunnel comes up. Names that go through the VPN then get no IPv6 // addresses and IPv6 connections are refused at once, so every app uses IPv4 instead of waiting on a dead path. noVPN6 atomic.Bool + // bypassDNS is set in a run with no server (nil in the VPN modes, which it leaves as they are); flows of port 53 + // read it when they start. + bypassDNS atomic.Pointer[bypassDNS] + // bypass is the ladder and the QUIC refusal of a run with the bypass on; nil leaves flows on their old path. + bypass atomic.Pointer[bypassFlows] mu sync.Mutex closed bool @@ -125,8 +130,8 @@ func newGvisorBridge(parent context.Context, tunDevice tun.Device, mtu int, vpn, } tcpForwarder := tcp.NewForwarder(st, 0, 1024, bridge.forwardTCP) udpForwarder := udp.NewForwarder(st, func(req *udp.ForwarderRequest) bool { - bridge.forwardUDP(req) - return true // every UDP flow is ours; an unhandled one would get an ICMP unreachable + // every UDP flow is ours but QUIC the bypass refuses: an unhandled one gets an ICMP unreachable + return bridge.forwardUDP(req) }) st.SetTransportProtocolHandler(tcp.ProtocolNumber, tcpForwarder.HandlePacket) st.SetTransportProtocolHandler(udp.ProtocolNumber, udpForwarder.HandlePacket) @@ -332,6 +337,9 @@ func (b *gvisorBridge) forwardTCP(req *tcp.ForwarderRequest) { } } watching = watching && name != "" + if b.openTCP(local, target, name, sniffed, app, watching) { + return + } var err error var route geo.Route remote, route, err = b.dialTCPName(b.ctx, target, name, app) @@ -394,7 +402,8 @@ func (b *gvisorBridge) readsName(app appVerdict, port uint16) (needsName, watchi return (port == 443 || port == 80) && b.apps.blocks(), false } watching = b.track != nil && port == 443 - return b.hasSiteRules != nil && b.hasSiteRules() || watching, watching + // with the bypass on, a TLS flow's name decides whether the ladder takes it + return b.hasSiteRules != nil && b.hasSiteRules() || watching || port == 443 && b.bypass.Load() != nil, watching } var noAnswerAfter = 10 * time.Second // a variable for the test @@ -469,11 +478,12 @@ func proxyTCP(local, remote net.Conn, watch *flowWatch) { <-done } -func (b *gvisorBridge) forwardUDP(req *udp.ForwarderRequest) { +// forwardUDP says false only for a flow it refuses, which then gets an ICMP unreachable (QUIC the bypass turns away). +func (b *gvisorBridge) forwardUDP(req *udp.ForwarderRequest) bool { id := req.ID() address, ok := netip.AddrFromSlice(id.LocalAddress.AsSlice()) if !ok { - return + return true } target := netip.AddrPortFrom(address.Unmap(), id.LocalPort) srcAddr, _ := netip.AddrFromSlice(id.RemoteAddress.AsSlice()) @@ -481,11 +491,14 @@ func (b *gvisorBridge) forwardUDP(req *udp.ForwarderRequest) { // This runs on the packet pump (readTun), which must never wait: finding the owner of the socket may wait for a // table snapshot, and the outbound's ListenUDP may redial a dead QUIC session for seconds. So the endpoint is made // first (the flow's next packets queue on it instead of starting new requests) and the rest runs on the flow's goroutine. + if b.refusesQUIC(target) { + return false + } app, ready := b.appQuick(true, src, target) var queue waiter.Queue endpoint, err := req.CreateEndpoint(&queue) if err != nil { - return + return true } local := gonet.NewUDPConn(&queue, endpoint) if !b.startForward(func() { @@ -496,6 +509,7 @@ func (b *gvisorBridge) forwardUDP(req *udp.ForwarderRequest) { }) { _ = local.Close() } + return true } // runUDP gives an accepted flow its outbound once the program is known. @@ -521,6 +535,7 @@ func (b *gvisorBridge) serveUDP(local net.Conn, remote packetFlow, target netip. } if target.Port() == 53 { flow.names, flow.direct, flow.down, flow.noVPN6, flow.doh = b.names, b.direct, &b.dnsDown, b.noVPN6.Load, b.doh + flow.bypass = b.bypassDNS.Load } flow.lastActivity.Store(time.Now().UnixNano()) b.mu.Lock() @@ -560,8 +575,9 @@ type udpFlow struct { names func(string) (bool, netip.AddrPort) direct outbound down *atomic.Int64 - noVPN6 func() bool // port 53 only: the VPN carries no IPv6 - doh *dohResolver // port 53 only; nil: questions for the VPN stay plain + noVPN6 func() bool // port 53 only: the VPN carries no IPv6 + doh *dohResolver // port 53 only; nil: questions for the VPN stay plain + bypass func() *bypassDNS // port 53 only; read at each question: the bridge may get it after its first flows sendMu sync.Mutex // the VPN flow takes one writer at a time (Hysteria2 reuses one send buffer) mu sync.Mutex // guards the fields below; never held across a send @@ -600,6 +616,12 @@ func (f *udpFlow) dnsPacket(payload []byte) bool { _, _ = f.local.Write(blockedAnswer(payload, end)) return true } + // A name the bypass works on gets no HTTPS record: without ECH and the h3 hint the browser sends the real name over + // TCP, which is what the strategies and their memory go by. + if bypass := f.bypassNow(); bypass != nil && payload[end-4] == 0 && payload[end-3] == dnsTypeHTTPS && bypass.always != nil && bypass.always(name) { + _, _ = f.local.Write(noData(payload, end)) + return true + } // A name that goes through a VPN without IPv6 gets no IPv6 addresses (see noVPN6). if !resolver.IsValid() && payload[end-4] == 0 && payload[end-3] == dnsTypeAAAA && f.noVPN6 != nil && f.noVPN6() { _, _ = f.local.Write(noData(payload, end)) @@ -759,6 +781,12 @@ func (f *udpFlow) readDirect(flow packetFlow, resolver netip.AddrPort) { if ask == nil || len(payload) < ask.end || !bytes.Equal(payload[12:ask.end], ask.payload[12:ask.end]) || !f.settle(id, ask) { continue } + // With no server the provider's resolver is the one that blocks: a stub address is no answer, and the question + // goes to the chain at once (no wait, and the resolver does not rest: the next name may be fine). + if f.bypassNow() != nil && stubAnswer(payload) { + _ = f.send(ask.payload) + continue + } if f.dns != nil { f.dns.remember(payload) } @@ -1059,3 +1087,10 @@ func globalIPv6(a netip.Addr) bool { // HasIPv6 says whether this machine reaches IPv6 outside any tunnel. func HasIPv6() bool { return directIPv6() } + +func (f *udpFlow) bypassNow() *bypassDNS { + if f.bypass == nil { + return nil + } + return f.bypass() +} diff --git a/core/internal/engine/real_bypass_windows.go b/core/internal/engine/real_bypass_windows.go new file mode 100644 index 0000000..3894eab --- /dev/null +++ b/core/internal/engine/real_bypass_windows.go @@ -0,0 +1,232 @@ +//go:build windows + +package engine + +import ( + "context" + "log/slog" + "net/netip" + "strings" + "time" + + "github.com/mistgate/mistgate-bypass/flow" + "github.com/mistgate/mistgate-client/core/internal/diag" + "github.com/mistgate/mistgate-client/core/internal/geo" + "github.com/mistgate/mistgate-client/core/internal/netcfg" +) + +// startBypass is Start in the mode with no server: the adapter takes every flow, the bridge sends them all direct, TLS +// through the ladder, and DNS to the chain of resolvers. Nothing to resolve, shake hands with or verify. +// The rules read as in smart: the direct selection are the exceptions (sites and programs the ladder leaves alone), +// the block list blocks. +func (r *Real) startBypass(ctx context.Context, run *realRun, report func(Step)) (Info, error) { + step(report, StepTunnel) + if !hasDefaultRoute() { + return Info{}, failure("offline", "bypass: no default route") + } + configured := r.settings() + // the country of the set: the route settings' region, else the one the public address is in, found before the + // adapter takes the machine's DNS + r.setAutoRegion("") + r.bypassRegion(ctx) + if err := ctx.Err(); err != nil { + return Info{}, err + } + country := func() string { return r.routeRegion(r.settings()) } + + mtu := 1500 + if configured.MTU != 0 { + mtu = configured.MTU + } + adapter, err := netcfg.Create(mtu) + if err != nil { + return Info{}, failure("tunnel_failed", "bypass: create adapter") + } + if !run.tunnel.setAdapter(adapter) { + return Info{}, context.Canceled + } + // DNS only, as with the kill switch off: Windows must not ask the network's resolvers around the chain + dns := defaultTunnelDNS + if err := r.setFirewall(run, true, adapter.LUID(), dns, configured.LAN); err != nil && !consoleFirewallUnavailable(err) { + if ctx.Err() != nil { + return Info{}, ctx.Err() + } + return Info{}, failure("tunnel_failed", "enable firewall rules") + } + if err := adapter.Configure(netcfg.Config{ + MTU: mtu, + Addresses: []netip.Prefix{netip.MustParsePrefix("198.18.0.1/30")}, + DNS: dns, + }); err != nil { + if ctx.Err() != nil { + return Info{}, ctx.Err() + } + return Info{}, failure("tunnel_failed", "bypass: adapter configuration") + } + + rules := func() *geo.SiteRules { + if r.geo == nil { + return nil + } + return r.geo.ActiveSiteRules() + } + exception := func(name string) bool { return rules().ByName("smart", name) == geo.RuleDirect } + set := bypassSet() + chain := newDNSChain(ctx) + mem := r.bypassMemory() + // the network before the first flow: the memory is the service's, and still on the last run's network + network := bypassNetwork{} + network.set(mem, true) + flows := flow.New(flow.Config{ + Memory: mem, + Country: country, + Own: func(name string) bool { return r.ownBypassSite(name) }, + NoFallback: func() bool { return true }, + }) + names := func(name string) (bool, netip.AddrPort) { + return rules().ByName("smart", name) == geo.RuleBlock, netip.AddrPort{} // every question goes to the chain + } + hasSiteRules := func() bool { + active := rules() + return active != nil && (active.HasDirect || active.HasBlock) + } + apps := &appRouter{ + owners: processOwners, + listed: func() bool { return appsListed("smart", rules()) }, + rule: func(path string) appVerdict { return appRule("smart", rules(), path) }, + blocks: func() bool { + active := rules() + return active != nil && active.HasBlock + }, + } + direct := func(netip.Addr, string, []string) bool { return true } + // no tracker: it learns which names to send through the VPN, and there is none + if err := run.tunnel.createBridge(ctx, adapter.Device(), mtu, noTunnelOutbound{chain: chain, direct: directOutbound{}}, directOutbound{}, direct, hasSiteRules, nil, names, apps, nil); err != nil { + chain.close() + if ctx.Err() != nil { + return Info{}, ctx.Err() + } + return Info{}, failure("tunnel_failed", "bypass: bridge") + } + // ponytail: a TLS flow in the microseconds before this goes plain (DNS flows read it at each question); a + // constructor argument closes that + run.tunnel.setBypass( + &bypassDNS{always: func(name string) bool { + _, known := set.Match(name) + return (known || rules().ByName("smart", name) == geo.RuleBypass) && !exception(name) + }}, + &bypassFlows{ + flows: flows, + never: exception, + quicOff: func(name string) bool { return set.BlocksQUIC(country(), name) }, + }, + ) + + r.mu.Lock() + if r.current != run || ctx.Err() != nil { + r.mu.Unlock() + chain.close() + return Info{}, context.Canceled + } + run.bypass = true + r.mu.Unlock() + go r.keepBypass(ctx, mem, chain, network) + return Info{Route: "bypass"}, nil +} + +// bypassMemory is opened once per service: it holds the installation's salt, and what was learnt stays across runs. +func (r *Real) bypassMemory() *flow.Memory { + r.bypassMemOnce.Do(func() { r.bypassMem = flow.OpenMemory(r.BypassMemory, nil) }) + return r.bypassMem +} + +// ownBypassSite: a site the person put in the bypass selection themself (not a service's collection). +func (r *Real) ownBypassSite(name string) bool { + if r.geo == nil { + return false + } + for _, site := range r.geo.GetRules().Bypass.Sites { + if name == site || strings.HasSuffix(name, "."+site) { + return true + } + } + return false +} + +// bypassRegion finds the country of the set when the route settings leave it to the public address. It asks the +// network: never on the packet path. +func (r *Real) bypassRegion(ctx context.Context) { + if !autoRoute(r.settings().RouteRegion) { + return + } + region := "none" + if public, err := publicAddress(ctx); err == nil && r.geo != nil { + if detected := r.geo.Detect(public, []string{"ru", "by", "kz", "cn", "ir", "tr"}); detected != "" { + region = detected + } + } + if ctx.Err() == nil { + r.setAutoRegion(region) + } +} + +// bypassForget is how often the same network is told again: that is when the memory forgets the names it found down. +// The manager's health probes wake the run too, and must not wipe them every time. +const bypassForget = 10 * time.Minute + +// bypassNetwork is what the memory was last told. +type bypassNetwork struct { + key string + at time.Time +} + +// set tells the memory the network now, if it is another one or bypassForget has passed (or always); it says whether +// the network is another one. +// ponytail: the key is the gateway's address and the interface's kind (diag.NetworkKey); two networks of one kind with +// the same gateway address share what was learnt. +func (n *bypassNetwork) set(mem *flow.Memory, always bool) (changed bool) { + salt := mem.Salt() + key, _ := diag.NetworkKey(salt[:]) + changed = key != n.key + if !changed && !always && time.Since(n.at) < bypassForget { + return false + } + n.key, n.at = key, time.Now() + mem.SetNetwork(key) // "": no network, nothing is learnt + return changed +} + +// keepBypass lives with the run: at every sign of a change it tells the memory the network and, on a new one, finds the +// country again; it writes the memory once a minute and at the end, and closes the chain's resolvers. +// ponytail: nothing waits for the last Save when the service stops; at most a minute of learning is lost. +func (r *Real) keepBypass(ctx context.Context, mem *flow.Memory, chain *dnsChain, network bypassNetwork) { + save := time.NewTicker(time.Minute) + defer save.Stop() + defer chain.close() + defer func() { + if err := mem.Save(); err != nil { + slog.Warn("bypass: memory not saved: " + err.Error()) + } + }() + for { + select { + case <-ctx.Done(): + return + case <-r.bypassWake: + if network.set(mem, false) { + r.bypassRegion(ctx) + } + case <-save.C: + _ = mem.Save() + } + } +} + +func (t *realTunnel) setBypass(dns *bypassDNS, flows *bypassFlows) { + t.mu.Lock() + defer t.mu.Unlock() + if t.bridge != nil { + t.bridge.bypassDNS.Store(dns) + t.bridge.setBypass(flows) + } +} diff --git a/core/internal/engine/real_bypass_windows_test.go b/core/internal/engine/real_bypass_windows_test.go new file mode 100644 index 0000000..919ab97 --- /dev/null +++ b/core/internal/engine/real_bypass_windows_test.go @@ -0,0 +1,35 @@ +//go:build windows + +package engine + +import ( + "testing" + + "github.com/mistgate/mistgate-client/core/internal/settings" +) + +func TestBypassModeRoute(t *testing.T) { + r := NewReal(nil, settings.Defaults, nil) + configured := settings.Defaults() + configured.Mode = "bypass" + if route := r.EffectiveRoute(configured); route != "bypass" { + t.Fatalf("EffectiveRoute = %q", route) + } + if path := r.RoutePath(configured, Target{Server: "auto"}, ""); path != "bypass" { + t.Fatalf("RoutePath = %q", path) + } + configured.Mode = "vpn" + if path := r.RoutePath(configured, Target{Server: "auto"}, ""); path == "bypass" { + t.Fatal("a VPN mode took the bypass path") + } +} + +func TestServiceDomains(t *testing.T) { + domains := ServiceDomains("yt") + if len(domains) == 0 { + t.Fatal("the built-in set has no domains for yt") + } + if ServiceDomains("no-such-service") != nil { + t.Fatal("an unknown service has domains") + } +} diff --git a/core/internal/engine/real_other.go b/core/internal/engine/real_other.go index 40eed65..f85e6cd 100644 --- a/core/internal/engine/real_other.go +++ b/core/internal/engine/real_other.go @@ -15,8 +15,9 @@ import ( ) type Real struct { - geo *geo.Store - AllowDest func(netip.Addr) bool + geo *geo.Store + AllowDest func(netip.Addr) bool + BypassMemory string } func NewReal(_ func() ([]profile.Profile, error), _ func() settings.Settings, geoStore *geo.Store, _ ...string) *Real { diff --git a/core/internal/engine/real_windows.go b/core/internal/engine/real_windows.go index 6ea6d63..3b6dff4 100644 --- a/core/internal/engine/real_windows.go +++ b/core/internal/engine/real_windows.go @@ -29,6 +29,7 @@ import ( coreerrs "github.com/apernet/hysteria/core/v2/errors" "github.com/apernet/hysteria/extras/v2/obfs" "github.com/apernet/hysteria/extras/v2/transport/udphop" + "github.com/mistgate/mistgate-bypass/flow" "github.com/mistgate/mistgate-client/core/internal/diag" "github.com/mistgate/mistgate-client/core/internal/firewall" "github.com/mistgate/mistgate-client/core/internal/geo" @@ -66,6 +67,15 @@ type Real struct { gatewayInterfaces map[winipcfg.LUID]struct{} panelSplit atomic.Pointer[[]profile.DNSSplit] // the panel's regional resolvers of the profile last started + // bypassOn: the run has the bypass on (its bridge has a ladder). Read by every flow's routing, like autoRegion. + bypassOn atomic.Bool + + // BypassMemory, when set before the first connect, is the file of what the bypass ladder learns; "": RAM only. + BypassMemory string + bypassMemOnce sync.Once + bypassMem *flow.Memory + bypassWake chan struct{} // a sign that the network may have changed, for the run of the bypass + // AllowDest, when set before the first connect, vets the addresses a name resolves to inside DialVPN. AllowDest func(netip.Addr) bool } @@ -84,6 +94,7 @@ type realRun struct { profile profile.Profile // what the tunnel was built from, as the subscriptions gave it (Stale compares it) luid uint64 dns []netip.Addr + bypass bool // the run of the bypass: no server, nothing to probe lastRX uint64 lastTX uint64 @@ -115,6 +126,7 @@ func NewReal(load func() ([]profile.Profile, error), getSettings func() settings resolved: make(map[string]netip.Addr), changed: make(chan struct{}, 1), interfaceChanges: make(chan struct{}, 1), + bypassWake: make(chan struct{}, 1), gatewayInterfaces: make(map[winipcfg.LUID]struct{}), } diag.LiveAWG = func() (string, string, time.Duration) { @@ -213,6 +225,10 @@ func (r *Real) signalChange() { case r.changed <- struct{}{}: default: } + select { + case r.bypassWake <- struct{}{}: + default: + } } func (r *Real) debounceInterfaceChanges(quiet time.Duration) { @@ -263,6 +279,9 @@ func ipv4GatewayInterfaces() (map[winipcfg.LUID]struct{}, error) { } func (r *Real) EffectiveRoute(configured settings.Settings) string { + if configured.Mode == "bypass" { + return "bypass" + } switch configured.RouteMode { case "selected": return "selected" @@ -280,6 +299,9 @@ func (r *Real) EffectiveRoute(configured settings.Settings) string { } func (r *Real) RoutePath(configured settings.Settings, target Target, activeProtocol string) string { + if configured.Mode == "bypass" { // another path: a change of mode is a new attempt + return "bypass" + } protocol := activeProtocol if protocol == "" || protocol == "auto" { if r.load != nil { @@ -332,7 +354,11 @@ func (r *Real) routeDirectNames(address netip.Addr, name string, remembered []st } } } - return directByRulesNames(address, name, remembered, configured.RouteMode, region, rules) + if directByRulesNames(address, name, remembered, configured.RouteMode, region, rules) { + return true + } + // with the bypass on, a name of the bypass selection goes direct in smart too (in selected every unlisted name does) + return configured.RouteMode == "smart" && name != "" && r.bypassOn.Load() && directAddressAllowed(address) && rules.ByName("smart", name) == geo.RuleBypass } // nameRoute is the bridge's view of a host name: blocked, or the regional resolver its DNS question goes to (zero: the @@ -345,7 +371,7 @@ func (r *Real) nameRoute(name string) (block bool, resolver netip.AddrPort) { } region := r.routeRegion(configured) // In "all" DecideName only blocks (the panel's ad list); nothing else applies there. - switch route, _ := geo.DecideName(name, configured.RouteMode, region, rules); route { + switch route, _ := geo.DecideName(name, configured.RouteMode, region, rules, r.bypassOn.Load()); route { case geo.NameBlock: return true, netip.AddrPort{} case geo.NameDirect: @@ -372,8 +398,7 @@ func (r *Real) directResolver(name, region string, rules *geo.SiteRules) netip.A // CheckSite is routes.check: where the forwarder would send a site now, by the code the flows use. func (r *Real) CheckSite(configured settings.Settings, name string) geo.Check { region := r.routeRegion(configured) - // no flow gets a bypass strategy yet, so the answer says "never" until the bridge does it - return r.geo.CheckName(configured.RouteMode, region, name, r.directResolver(name, region, r.geo.ActiveSiteRules()).IsValid(), false) + return r.geo.CheckName(configured.RouteMode, region, name, r.directResolver(name, region, r.geo.ActiveSiteRules()).IsValid(), r.bypassOn.Load()) } func (r *Real) Routes(configured settings.Settings) geo.Routes { @@ -512,6 +537,9 @@ func (r *Real) Start(ctx context.Context, target Target, report func(Step)) (inf if err := runCtx.Err(); err != nil { return Info{}, err } + if r.settings().Mode == "bypass" { + return r.startBypass(runCtx, run, report) + } if r.load == nil { return Info{}, failure("no_subscription", "load profiles") @@ -1401,6 +1429,19 @@ func (r *Real) counters() (rx, tx uint64) { func (r *Real) Probe(ctx context.Context) error { r.mu.Lock() run := r.current + if run != nil && run.bypass && run.tunnel.adapterSnapshot() != nil { + r.mu.Unlock() + // No tunnel to lose: the manager probes after a new network or a wake-up, and the run is told (bypassWake). + // Without a network the run is down, and the next attempt waits for one as offline. + select { + case r.bypassWake <- struct{}{}: + default: + } + if !hasDefaultRoute() { + return errors.New("no network") + } + return nil + } if run == nil || !run.probeIP.IsValid() || run.tunnel.adapterSnapshot() == nil { r.mu.Unlock() return errors.New("no active tunnel") diff --git a/core/internal/engine/site.go b/core/internal/engine/site.go index 08b3594..df8e59a 100644 --- a/core/internal/engine/site.go +++ b/core/internal/engine/site.go @@ -585,3 +585,29 @@ func directAddressAllowed(address netip.Addr) bool { return address.IsValid() && !address.IsPrivate() && !address.IsLoopback() && !address.IsLinkLocalUnicast() && !address.IsLinkLocalMulticast() && !address.IsMulticast() && !address.IsUnspecified() } + +// tlsHelloEnd is where the TLS records that carry a whole ClientHello end in data, or 0 when data does not start with +// one: what follows (early data) is the application's and must not be sent again with the ClientHello. +func tlsHelloEnd(data []byte) int { + var handshake []byte + for offset := 0; len(data)-offset >= 5; { + if data[offset] != 22 || data[offset+1] != 3 { + return 0 + } + recordLen := int(data[offset+3])<<8 | int(data[offset+4]) + if recordLen == 0 || len(data)-offset < 5+recordLen { + return 0 + } + handshake = append(handshake, data[offset+5:offset+5+recordLen]...) + offset += 5 + recordLen + if len(handshake) >= 4 { + if handshake[0] != 1 { + return 0 + } + if helloLen := int(handshake[1])<<16 | int(handshake[2])<<8 | int(handshake[3]); len(handshake) >= 4+helloLen { + return offset + } + } + } + return 0 +} diff --git a/core/internal/geo/names.go b/core/internal/geo/names.go index d6c80d7..4fcaec7 100644 --- a/core/internal/geo/names.go +++ b/core/internal/geo/names.go @@ -42,7 +42,8 @@ func (r *SiteRules) ByName(mode, name string) RuleVerdict { if mode == "selected" && r.VPN.Len() != 0 && r.VPN.Match(name) { return RuleVPN } - if r.Bypass.Len() != 0 && r.Bypass.Match(name) { + // The VPN selection wins over the bypass even in smart, which does not read it otherwise. + if r.Bypass.Len() != 0 && r.Bypass.Match(name) && !(r.VPN.Len() != 0 && r.VPN.Match(name)) { return RuleBypass } return NoRule @@ -62,7 +63,8 @@ const ( // DecideName is what the forwarder decides for a host name alone, without an address. In smart mode "vpn by default" // only means that no name rule applies: the address of the flow still decides there. -func DecideName(name, mode, region string, rules *SiteRules) (route, by string) { +// bypass: the bypass is in force for direct flows; a name of the bypass selection then goes direct in smart. +func DecideName(name, mode, region string, rules *SiteRules, bypass bool) (route, by string) { verdict := rules.ByName(mode, name) if verdict == RuleBlock { return NameBlock, byRules @@ -75,6 +77,10 @@ func DecideName(name, mode, region string, rules *SiteRules) (route, by string) return NameDirect, byRules case RuleVPN: return NameVPN, byRules + case RuleBypass: + if bypass && mode == "smart" { + return NameDirect, byRules + } } if mode == "selected" { return NameDirect, byDefault @@ -132,7 +138,7 @@ type Check struct { // bypass that the bypass is in force for direct flows. func (s *Store) CheckName(mode, region, name string, resolver, bypass bool) Check { rules := s.ActiveSiteRules() - route, by := DecideName(name, mode, region, rules) + route, by := DecideName(name, mode, region, rules, bypass) check := Check{Route: route, By: by, DNS: NameVPN, Bypass: "never"} if bypass && route == NameDirect && rules != nil && !rules.Direct.Match(name) { check.Bypass = "auto" @@ -162,6 +168,18 @@ func (s *Store) matching(route, name string) (by, rule string) { case NameVPN: selection = rules.VPN } + if by, rule := matchingIn(s, selection, name); by != "" { + return by, rule + } + if route == NameDirect { // the direct selection did not have it: a name of the bypass selection (smart) + if by, rule := matchingIn(s, rules.Bypass, name); by != "" { + return by, rule + } + } + return "site", "" // the lists changed between the decision and this look +} + +func matchingIn(s *Store, selection Selection, name string) (by, rule string) { for _, site := range selection.Sites { if name == site || strings.HasSuffix(name, "."+site) { return "site", site @@ -172,5 +190,5 @@ func (s *Store) matching(route, name string) (by, rule string) { return "collection", collection } } - return "site", "" // the lists changed between the decision and this look + return "", "" } diff --git a/core/internal/geo/names_test.go b/core/internal/geo/names_test.go index fa178f7..fcd80a6 100644 --- a/core/internal/geo/names_test.go +++ b/core/internal/geo/names_test.go @@ -67,22 +67,22 @@ func TestDecideNameTable(t *testing.T) { {"selected", "ru", "yandex.ru", NameDirect, "default"}, } for _, test := range tests { - route, by := DecideName(test.name, test.mode, test.region, rules) + route, by := DecideName(test.name, test.mode, test.region, rules, false) if route != test.route || by != test.by { t.Errorf("DecideName(%q, %s, %q) = %s, %s; want %s, %s", test.name, test.mode, test.region, route, by, test.route, test.by) } } - if route, by := DecideName("anything.example", "smart", "ru", nil); route != NameVPN || by != "default" { + if route, by := DecideName("anything.example", "smart", "ru", nil, false); route != NameVPN || by != "default" { t.Errorf("no rules at all: %s, %s", route, by) } - if route, by := DecideName("anything.ru", "smart", "ru", nil); route != NameDirect || by != "region" { + if route, by := DecideName("anything.ru", "smart", "ru", nil, false); route != NameDirect || by != "region" { t.Errorf("region without rules: %s, %s", route, by) } } func TestByNameDoesNotAllocateForRegionAndEmptySets(t *testing.T) { rules := nameStore(t).ActiveSiteRules() - if allocs := testing.AllocsPerRun(100, func() { _, _ = DecideName("www.example.com", "smart", "ru", rules) }); allocs != 0 { + if allocs := testing.AllocsPerRun(100, func() { _, _ = DecideName("www.example.com", "smart", "ru", rules, false) }); allocs != 0 { t.Fatalf("DecideName allocates %v times for a lower-case name", allocs) } } @@ -193,7 +193,7 @@ func TestPanelAdListBlocksInEveryModeAndIsLetGo(t *testing.T) { {"smart", "ads.example", NameBlock, "rules"}, } for _, test := range tests { - if route, by := DecideName(test.name, test.mode, "", rules); route != test.route || by != test.by { + if route, by := DecideName(test.name, test.mode, "", rules, false); route != test.route || by != test.by { t.Errorf("DecideName(%q, %s) = %s, %s; want %s, %s", test.name, test.mode, route, by, test.route, test.by) } } @@ -356,9 +356,25 @@ func TestBypassRules(t *testing.T) { } } // today's callers read a bypass name as one without a rule - if route, by := DecideName("slow.example", "smart", "", active); route != NameVPN || by != byDefault { + if route, by := DecideName("slow.example", "smart", "", active, false); route != NameVPN || by != byDefault { t.Errorf("DecideName = %s, %s", route, by) } + // with the bypass in force, smart sends a bypass name direct, and routes.check names the rule + if route, by := DecideName("slow.example", "smart", "", active, true); route != NameDirect || by != byRules { + t.Errorf("DecideName with the bypass = %s, %s", route, by) + } + if route, _ := DecideName("vpn.example", "smart", "", active, true); route != NameVPN { + t.Errorf("a VPN site with the bypass = %s", route) + } + for name, want := range map[string]Check{ + "a.slow.example": {"direct", "site", "slow.example", "vpn", "always"}, + "a.video.example": {"direct", "collection", "service:video", "vpn", "always"}, + "both.example": {"direct", "site", "both.example", "vpn", "never"}, + } { + if got := store.CheckName("smart", "", name, false, true); got != want { + t.Errorf("CheckName(smart, %s) = %+v; want %+v", name, got, want) + } + } for _, test := range []struct { mode, name string bypass bool diff --git a/core/internal/netcfg/netcfg_windows.go b/core/internal/netcfg/netcfg_windows.go index ede6b97..df29162 100644 --- a/core/internal/netcfg/netcfg_windows.go +++ b/core/internal/netcfg/netcfg_windows.go @@ -613,3 +613,30 @@ func (d *sessionDevice) Close() error { } func (d *sessionDevice) BatchSize() int { return 1 } + +// PhysicalDNS4 is the IPv4 DNS servers of the interface PhysicalInterfaceIndex4 names (the provider's, from DHCP as a +// rule); none when there is no such interface. +func PhysicalDNS4() []netip.Addr { + index, err := PhysicalInterfaceIndex4() + if err != nil || index == 0 { + return nil + } + adapters, err := winipcfg.GetAdaptersAddresses(windows.AF_INET, winipcfg.GAAFlagDefault) + if err != nil { + return nil + } + for _, adapter := range adapters { + if adapter.IfIndex != index { + continue + } + dns, _ := adapter.LUID.DNS() + var out []netip.Addr + for _, server := range dns { + if server = server.Unmap(); server.Is4() { + out = append(out, server) + } + } + return out + } + return nil +} diff --git a/core/internal/session/manager.go b/core/internal/session/manager.go index db61045..33c7c42 100644 --- a/core/internal/session/manager.go +++ b/core/internal/session/manager.go @@ -690,7 +690,7 @@ func (m *Manager) run() { state.status.SinceUnix = time.Now().Unix() } state.status.Error = code - if !state.bootConnect { + if !state.bootConnect && m.currentSettings().Mode != "bypass" { // the bypass has no server to go round failedServer := request.info.ServerID if failedServer == "" { failedServer = state.target.Server @@ -1219,7 +1219,8 @@ func (m *Manager) settingsChanged(state *actorState) { } routeSettingsChanged := state.routeSettings.RouteMode != configured.RouteMode || state.routeSettings.RouteRegion != configured.RouteRegion // The adapter takes its DNS and MTU when it is configured, so a new value needs a new attempt, held like a path change. - adapterChanged := state.routeSettings.DNS != configured.DNS || state.routeSettings.MTU != configured.MTU + // The bypass takes no DNS of the person's: its questions go to the chain of resolvers. + adapterChanged := state.routeSettings.DNS != configured.DNS && configured.Mode != "bypass" || state.routeSettings.MTU != configured.MTU switch state.status.State { case "connected": path := m.routePath(configured, state.target, state.status.Protocol) @@ -1286,12 +1287,13 @@ func (m *Manager) settingsChanged(state *actorState) { func (m *Manager) reconnectRoute(state *actorState, configured settings.Settings) { target := state.target - target.Hold = true + hold := configured.Mode != "bypass" // the bypass never holds the network: there is no tunnel to leak around + target.Hold = hold wasConnected := state.status.State == "connected" wasHeld := state.holdReconnect - state.holdReconnect = true + state.holdReconnect = hold state.routeSettings = configured - if m.engine != nil && (wasConnected || !wasHeld) { + if m.engine != nil && hold && (wasConnected || !wasHeld) { m.engine.Hold() } if state.runCancel != nil { diff --git a/core/internal/session/manager_bypass_test.go b/core/internal/session/manager_bypass_test.go new file mode 100644 index 0000000..7204347 --- /dev/null +++ b/core/internal/session/manager_bypass_test.go @@ -0,0 +1,38 @@ +package session + +import ( + "context" + "encoding/json" + "testing" + + "github.com/mistgate/mistgate-client/core/internal/engine" + "github.com/mistgate/mistgate-client/core/internal/settings" +) + +// A switch to the bypass is a new attempt, but the network is not held for it: the bypass never holds it. +func TestBypassSwitchDoesNotHold(t *testing.T) { + store := testSettings(t, "off") + path := func(configured settings.Settings, _ engine.Target, _ string) string { + if configured.Mode == "bypass" { + return "bypass" + } + return "forwarder" + } + fake := engine.NewFake(engine.FakeConfig{StepDelay: 1}) + manager := NewManager(fake, store.Get, RouteState{Path: path}) + defer manager.Close() + if _, err := manager.Connect(context.Background(), engine.Target{Server: "server-a", Protocol: "hysteria2"}); err != nil { + t.Fatal(err) + } + waitForManagerStatus(t, manager, func(status Status) bool { return status.State == "connected" }) + holds := fake.HoldCount() + if _, err := store.Set(map[string]json.RawMessage{"mode": json.RawMessage(`"bypass"`)}); err != nil { + t.Fatal(err) + } + manager.SettingsChanged() + waitForStarts(t, fake, 2) + waitForManagerStatus(t, manager, func(status Status) bool { return status.State == "connected" }) + if targets := fake.Targets(); len(targets) != 2 || targets[1].Hold || fake.HoldCount() != holds { + t.Fatalf("switch to the bypass: targets %#v, holds %d -> %d", targets, holds, fake.HoldCount()) + } +} diff --git a/core/internal/session/memory.go b/core/internal/session/memory.go index b875fe8..2c7c769 100644 --- a/core/internal/session/memory.go +++ b/core/internal/session/memory.go @@ -64,7 +64,7 @@ func (m *Manager) pathUp(state *actorState, r attemptResult) { state.autoNet, state.autoPath = r.net, path } state.status.Auto, state.status.Reason = false, "" - if isAuto(state.target.Server) { + if isAuto(state.target.Server) && r.info.Route != "bypass" { // back on the path the connection died on (the network went and came back) is no failover, whatever failed meanwhile back := state.deadPath != "" && state.deadPath == path failover := !back && (len(state.roundFailures) > 0 || state.deadPath != "") diff --git a/core/internal/session/quality.go b/core/internal/session/quality.go index 3c598b0..ff32d42 100644 --- a/core/internal/session/quality.go +++ b/core/internal/session/quality.go @@ -48,7 +48,7 @@ func (m *Manager) endLive(state *actorState) { // autoOwn: the connection is Auto's own pick, on a network the memory knows, and not on the path for allowlists. func (m *Manager) autoOwn(state *actorState) bool { - return state.status.State == "connected" && state.liveNet != "" && isAuto(state.userServer) && isAuto(state.target.Server) && + return state.status.State == "connected" && state.liveNet != "" && state.status.Route != "bypass" && isAuto(state.userServer) && isAuto(state.target.Server) && !state.status.WhitelistByRule && state.status.Purpose != profile.PurposeWhitelist } @@ -490,6 +490,9 @@ func (m *Manager) noteDeath(state *actorState) { state.shortDeath = "" return } + if path == "" { // the bypass: no path to set aside + return + } if state.shortDeath != path { state.shortDeath = path return diff --git a/docs/ipc.md b/docs/ipc.md index c312b8d..d92f590 100644 --- a/docs/ipc.md +++ b/docs/ipc.md @@ -97,7 +97,7 @@ at home or on the same PC is a real case. | `routes.update` | none | The `routes.get` object as it is now; the downloads go on in the background and a `routes` event follows when they end | | `routes.lists` | none | `{"lists": [{"id": "", "entries": N, "updated_unix": N, "error": ""}], "unique": N, "duplicates": N}` | | `routes.set` | `{"direct": Selection, "vpn": Selection, "block": Selection, "bypass": Selection}` (any key may be omitted; an omitted one keeps what is stored). A `Selection` is `{"collections": [...], "sites": [...], "apps": [...]}`, any key may be omitted too, and an omitted one keeps what is stored | The `routes.get` object | -| `routes.check` | `{"site": ""}`; a host name or an https URL of one, checked like a site entry | `{"route": "direct" \| "vpn" \| "block", "by": "mode" \| "site" \| "collection" \| "region" \| "default", "rule": "", "dns": "direct" | "vpn", "bypass": "always" | "auto" | "never"}` || "vpn"}` | +| `routes.check` | `{"site": ""}`; a host name or an https URL of one, checked like a site entry | `{"route": "direct" \| "vpn" \| "block", "by": "mode" \| "site" \| "collection" \| "region" \| "default", "rule": "", "dns": "direct" \| "vpn", "bypass": "always" \| "auto" \| "never"}` | | `routes.dismiss` | `{"route": "direct" \| "vpn", "site": ""}`; `route` is the `suggest` list the site was in | The `routes.get` object | | `apps.list` | none; a trusted caller only | `{"apps": [{"path": "c:\\tools\\app.exe", "name": "App", "running": true}]}`: the programs for the "Programs" tab (see "Rules by program") | | `diag.run` | `{"sub": ""}` (optional; empty selects the first subscription) | Diagnostic State | @@ -308,7 +308,8 @@ when protocol selection is automatic (default `false`); `route_mode` is `all`, ` `route_region` is `auto`, `none`, or a two-letter lower-case country code (default `auto`). `mode` is `vpn` or `bypass` (default `vpn`): what `connect` does. In `bypass` no server is used and the kill switch is not in force whatever `kill_switch` says: the network is never held, and the service start connects by `autoconnect` or `restore` without a `last_server`. `bypass_direct` (default `true`) -gives the bypass to the direct flows of `smart` and `selected` in `vpn`. The engine has no `bypass` branch yet: the two keys are stored and nothing more. `settings.set` accepts only these keys, updates only the keys +gives the bypass to the direct flows of `smart` and `selected` in `vpn`. In `bypass` every flow goes direct, TLS through the bypass, DNS through resolvers the service asks itself; the +rules read as in `smart` (the direct selection are exceptions, the block list blocks). `bypass_direct` does nothing yet. `settings.set` accepts only these keys, updates only the keys provided, and returns `bad_params` for an unknown key or invalid value. Changes apply immediately to the active firewall policy and are pushed to subscribers of `settings` as a Settings object. When `connect.protocol` is omitted or `auto`, automatic selection uses the configured `protocol`; when that is also `auto`, `game: true` prefers AWG if @@ -631,7 +632,9 @@ The `bypass` selection names the sites and services that get a bypass strategy a rules saved before it existed read as an empty one. A name in it is read after every other rule: `block`, `direct` (an exception: never a strategy) and `vpn` win. `routes.check` answers `bypass`: `always` (in the selection), `auto` (a strategy after a plain attempt failed) or `never` (the route is not direct, the name is an exception, or the bypass -is not in force). No flow gets a strategy yet, so the answer is `never` for now. +is not in force). While the bypass is in force, `smart` sends a name of the selection direct too (`by` and `rule` then +name the selection's entry; `vpn` still wins). The bypass of `vpn` (`bypass_direct`) is not in force yet, so the answer is `never` for now; with `mode` `bypass`, +`routes.check` still answers for the route settings of `vpn`. Each selection accepts at most 200 collections and 500 sites. A collection is `geosite:` (lower-case letters, digits, `!`, `@`, and `-`, up to 48 characters) or `list:` (up to 512 URL characters, HTTPS only, no @@ -657,7 +660,8 @@ for the answer TTL clamped to 60 seconds through 1 hour, in a cache capped at 50 not visible here; QUIC without a known DNS name cannot be matched; and ECH can hide the actual TLS server name. Site names, DNS questions, and destination addresses are never logged. -`status.route` is `all`, `smart:` when a smart region list is available, `smart` when it is not, or `selected`. +`status.route` is `all`, `smart:` when a smart region list is available, `smart` when it is not, `selected`, or +`bypass` (`mode` is `bypass`: no server, `server` and `protocol` are empty). Changing `mode` starts a new attempt. Changing route rules or refreshing a list does not reconnect. An AmneziaWG session reconnects with the network held only when switching between its native path in `all` and its forwarder path in `smart` or `selected`.