Skip to content
Open
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
2 changes: 2 additions & 0 deletions core/cmd/mistgate-clientd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:<id>" in the rules: the services of the bypass set
slog.SetDefault(logger.With("src", "engine"))
var eng engine.Engine
var routeState session.RouteState
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion core/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions core/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down
355 changes: 355 additions & 0 deletions core/internal/engine/bypass_dns_windows.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading