diff --git a/core/internal/diag/runner.go b/core/internal/diag/runner.go index 8b0f5e5..58176cc 100644 --- a/core/internal/diag/runner.go +++ b/core/internal/diag/runner.go @@ -262,7 +262,7 @@ func (r *Runner) check(ctx context.Context, sub string) (*Result, error) { } selected := make([]profile.Profile, 0) for _, p := range profiles { - if p.Sub == sub { + if p.Sub == sub && p.DNST == nil { // the DNS tunnel is not a server to dial selected = append(selected, p) } } @@ -532,6 +532,9 @@ func LiveGuard(p profile.Profile) (time.Duration, bool) { // Handshake is one handshake attempt to p's server outside the tunnel, on the physical interface, resolve included, // in timeout at most. It returns the round trip. The engine uses it to find the quickest server. func Handshake(ctx context.Context, p profile.Profile, timeout time.Duration) (time.Duration, error) { + if p.DNST != nil { + return 0, errNoAnswer // not a server to dial + } ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() endpoint, physical, err := resolveProfile(ctx, p) @@ -544,6 +547,9 @@ func Handshake(ctx context.Context, p profile.Profile, timeout time.Duration) (t // Latency is the round trip to p's server, for a number on the screen. For VLESS and TrustTunnel, one TCP connect to // the server's port is the same circle, without a session through the server every time the number is asked for. func Latency(ctx context.Context, p profile.Profile, timeout time.Duration) (time.Duration, error) { + if p.DNST != nil { + return 0, errNoAnswer // not a server to dial + } if p.Protocol != "vless" && p.Protocol != "trusttunnel" { return Handshake(ctx, p, timeout) } diff --git a/core/internal/engine/real_windows.go b/core/internal/engine/real_windows.go index 9a909c8..bcce2df 100644 --- a/core/internal/engine/real_windows.go +++ b/core/internal/engine/real_windows.go @@ -968,8 +968,8 @@ const latencyEvery = 5 * time.Minute // either way, so that the clients of one server do not measure together). The tunnel's own probes cannot give it: // with the forwarder they are answered inside this process. func (r *Real) keepLatency(ctx context.Context, run *realRun, p profile.Profile) { - if p.Protocol == "awg" { - return // its key is the tunnel's: the time of the tunnel's own handshake stays + if p.Protocol == "awg" || p.DNST != nil { + return // awg: its key is the tunnel's, the time of its own handshake stays; the DNS tunnel has no server to time } for { if rtt, err := diag.Latency(ctx, p, fastestTimeout); err == nil { diff --git a/core/internal/profile/dnstunnel.go b/core/internal/profile/dnstunnel.go new file mode 100644 index 0000000..015aa64 --- /dev/null +++ b/core/internal/profile/dnstunnel.go @@ -0,0 +1,112 @@ +package profile + +import ( + "encoding/json" + "errors" + "net/netip" + "slices" + "strings" +) + +const maxDNSTunnelSettings = 4 * 1024 + +// DNSTunnel is the settings of a panel's "dnstunnel" path (experimental, no engine yet). Key is opaque: it is never +// parsed, checked, logged or put into an error. +type DNSTunnel struct { + V int + Domain string + Key string + KbpsHint int +} + +// ParseDNSTunnelPath reads the settings object of a dnstunnel path. Unknown fields and "udp" are ignored. +func ParseDNSTunnelPath(settings json.RawMessage) (*DNSTunnel, error) { + if len(settings) == 0 || len(settings) > maxDNSTunnelSettings { + return nil, errors.New("invalid DNS tunnel settings") + } + var input struct { + V int `json:"v"` + Domain string `json:"domain"` + Key string `json:"key"` + KbpsHint int `json:"kbps_hint"` + } + if json.Unmarshal(settings, &input) != nil { + return nil, errors.New("invalid DNS tunnel settings") + } + switch { + case input.V != 1: + return nil, errors.New("unsupported DNS tunnel version") + case !validDNSName(input.Domain): + return nil, errors.New("invalid DNS tunnel domain") + case input.Key == "" || len(input.Key) > 1024: + return nil, errors.New("invalid DNS tunnel key") + } + return &DNSTunnel{V: 1, Domain: input.Domain, Key: input.Key, KbpsHint: max(input.KbpsHint, 0)}, nil +} + +// validDNSName is a name of at least two labels of letters, digits and inner hyphens. +func validDNSName(name string) bool { + if len(name) == 0 || len(name) > 253 || strings.Count(name, ".") == 0 { + return false + } + for _, label := range strings.Split(name, ".") { + if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' { + return false + } + for _, c := range []byte(label) { + if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-') { + return false + } + } + } + return true +} + +// DNSResolver is one entry of the panel's dns_tunnel resolver list: "system" (the physical interface's DNS) or an +// address as IP:port. +type DNSResolver struct { + Addr string `json:"addr"` + ASN []uint32 `json:"asn,omitempty"` + Operator string `json:"operator,omitempty"` +} + +// DNSTunnelResolvers is the panel's dns_tunnel block as kept. TTL is the panel's word on freshness (seconds); an +// expired list is still used, since under an allowlist the panel cannot be reached for a new one. +type DNSTunnelResolvers struct { + TTL int64 `json:"ttl,omitempty"` + ClientASN uint32 `json:"client_asn,omitempty"` + Resolvers []DNSResolver `json:"resolvers,omitempty"` +} + +// Endpoints is the list as addresses for the engine: "system" is replaced by `system` (the physical interface's IPv4 +// DNS servers, port 53), duplicates go, the entries whose ASN holds ClientASN come first, the rest keep their order. +func (d *DNSTunnelResolvers) Endpoints(system []netip.Addr) []netip.AddrPort { + if d == nil { + return nil + } + var near, rest []netip.AddrPort + for _, r := range d.Resolvers { + var found []netip.AddrPort + if r.Addr == "system" { + for _, a := range system { + if a = a.Unmap(); a.Is4() { + found = append(found, netip.AddrPortFrom(a, 53)) + } + } + } else if ap, err := netip.ParseAddrPort(r.Addr); err == nil { + found = append(found, ap) + } + if d.ClientASN != 0 && slices.Contains(r.ASN, d.ClientASN) { + near = append(near, found...) + } else { + rest = append(rest, found...) + } + } + out := make([]netip.AddrPort, 0, len(near)+len(rest)) + for _, ap := range append(near, rest...) { + if !slices.Contains(out, ap) { + out = append(out, ap) + } + } + return out +} diff --git a/core/internal/profile/dnstunnel_test.go b/core/internal/profile/dnstunnel_test.go new file mode 100644 index 0000000..ef4d28e --- /dev/null +++ b/core/internal/profile/dnstunnel_test.go @@ -0,0 +1,77 @@ +package profile + +import ( + "encoding/json" + "net/netip" + "reflect" + "strings" + "testing" +) + +func TestParseDNSTunnelPath(t *testing.T) { + const secret = "kid1.SECRETsecret_-" + settings := func(change map[string]any) json.RawMessage { + m := map[string]any{"v": 1, "domain": "k3x9ab.t.example.com", "key": secret, "udp": true, "kbps_hint": 200, "later": []int{1}} + for k, v := range change { + m[k] = v + } + data, _ := json.Marshal(m) + return data + } + got, err := ParseDNSTunnelPath(settings(nil)) + if err != nil || *got != (DNSTunnel{V: 1, Domain: "k3x9ab.t.example.com", Key: secret, KbpsHint: 200}) { + t.Fatalf("good = %#v, %v (udp and unknown fields are ignored)", got, err) + } + if got, err = ParseDNSTunnelPath(settings(map[string]any{"kbps_hint": nil})); err != nil || got.KbpsHint != 0 { + t.Fatalf("no kbps_hint = %#v, %v", got, err) + } + for name, change := range map[string]map[string]any{ + "v2": {"v": 2}, + "no v": {"v": nil}, + "empty key": {"key": ""}, + "no key": {"key": nil}, + "bad domain": {"domain": "bad_name.example.com"}, + "one label": {"domain": "example"}, + "empty label": {"domain": "a..example.com"}, + "hyphen start": {"domain": "-a.example.com"}, + "empty domain": {"domain": ""}, + "key a number": {"key": 5}, + } { + if _, err := ParseDNSTunnelPath(settings(change)); err == nil { + t.Errorf("%s: accepted", name) + } else if strings.Contains(err.Error(), "SECRET") { + t.Errorf("%s: the key is in the error %q", name, err) + } + } + // A key that is not a string fails inside the decoder: its text must not come back in the error either. + if _, err := ParseDNSTunnelPath(json.RawMessage(`{"v":1,"domain":"a.example.com","key":{"SECRETsecret":1}}`)); err == nil || strings.Contains(err.Error(), "SECRET") { + t.Errorf("object key: %v", err) + } + if _, err := ParseDNSTunnelPath(nil); err == nil { + t.Error("empty settings accepted") + } +} + +func TestDNSTunnelEndpoints(t *testing.T) { + list := &DNSTunnelResolvers{ClientASN: 64496, Resolvers: []DNSResolver{ + {Addr: "192.0.2.1:53"}, + {Addr: "system"}, + {Addr: "192.0.2.53:53", ASN: []uint32{64497, 64496}}, + {Addr: "192.0.2.1:53", ASN: []uint32{64496}}, // a duplicate that sorts first: it wins, the later one goes + {Addr: "[2001:db8::53]:5353"}, + }} + system := []netip.Addr{netip.MustParseAddr("192.0.2.1"), netip.MustParseAddr("192.0.2.77"), netip.MustParseAddr("2001:db8::1")} + want := []netip.AddrPort{ + netip.MustParseAddrPort("192.0.2.53:53"), netip.MustParseAddrPort("192.0.2.1:53"), + netip.MustParseAddrPort("192.0.2.77:53"), netip.MustParseAddrPort("[2001:db8::53]:5353"), + } + if got := list.Endpoints(system); !reflect.DeepEqual(got, want) { + t.Fatalf("endpoints = %v, want %v", got, want) + } + if got := list.Endpoints(nil); len(got) != 3 { + t.Fatalf("without system DNS: %v", got) + } + if (*DNSTunnelResolvers)(nil).Endpoints(system) != nil { + t.Fatal("a nil list has endpoints") + } +} diff --git a/core/internal/profile/profile.go b/core/internal/profile/profile.go index b4ecdbe..02f4c42 100644 --- a/core/internal/profile/profile.go +++ b/core/internal/profile/profile.go @@ -28,6 +28,7 @@ type Profile struct { AWG *AWG VLESS *VLESS TT *TrustTunnel + DNST *DNSTunnel // experimental DNS tunnel path; nil for every other Verify string // From a panel's client API: how the path reaches the server (direct, relay, warp); empty when not known. Via string @@ -39,6 +40,8 @@ type Profile struct { // The preset's DoH resolver: its https URL and the addresses of its host (maybe none); empty URL for none. PanelDoH string PanelDoHIPs []netip.Addr + // The sync's dns_tunnel block, for a dnstunnel path: the engine takes its resolvers from it (Endpoints). + PanelDNST *DNSTunnelResolvers // The panel said no IPv6 leaves through this path (ipv6_egress false): the engine takes its word and does not probe. NoIPv6 bool } diff --git a/core/internal/subs/api.go b/core/internal/subs/api.go index 0d006dc..477b9fd 100644 --- a/core/internal/subs/api.go +++ b/core/internal/subs/api.go @@ -24,6 +24,11 @@ import ( "github.com/mistgate/mistgate-client/core/internal/version" ) +// dnsTunnelEngine says that this build has an engine for dnstunnel paths. While false, a path of that kind is read and +// counted as unsupported, not offered, and capsHeader leaves "dnstunnel=1" out so that the panel does not send it. The +// branch with the engine sets it true and adds "dnstunnel=1" to capsHeader. A variable only for the tests. +var dnsTunnelEngine = false + const ( capsHeader = "v=1; hysteria2=2; gecko=1; awg=2.0,3.1; vless=1; trusttunnel=1" apiUserAgent = "Mistgate/" + version.Service + " (Windows)" @@ -70,6 +75,9 @@ type apiState struct { // The preset's DoH resolver (its URL, and the addresses the panel gave for its host), for the tunnel's questions. DNSDoH string `json:"dns_doh,omitempty"` DNSDoHIPs []netip.Addr `json:"dns_doh_ips,omitempty"` + // The panel's resolvers for the experimental DNS tunnel. Kept past its ttl (under an allowlist the panel cannot be reached), + // and kept by a sync that has a dnstunnel path but no block. + DNSTunnel *profile.DNSTunnelResolvers `json:"dns_tunnel,omitempty"` // The ASN of this device's network as the panel saw it; only a block report uses it, the window never gets it. ASN uint32 `json:"asn,omitempty"` } @@ -90,8 +98,9 @@ type syncBody struct { QuotaBytes int64 `json:"quota_bytes"` UsedBytes int64 `json:"used_bytes"` } `json:"plan"` - DNS *syncDNS `json:"dns"` - Probe *struct { + DNS *syncDNS `json:"dns"` + DNSTunnel json.RawMessage `json:"dns_tunnel"` + Probe *struct { Intake bool `json:"intake"` V int `json:"v"` } `json:"probe"` @@ -628,6 +637,9 @@ func (s *Store) syncNow(ctx context.Context, st storedSubscription) (storedSubsc st.DNS, st.DNSSplit, st.DNSIPv4Only = panelDNS(b.DNS) // absent unless active: the old resolvers go with the old answer st.DNSBlockAds = b.DNS != nil && b.DNS.BlockAds st.DNSDoH, st.DNSDoHIPs = panelDoH(b.DNS) + oldDNSTunnel := st.DNSTunnel + st.DNSTunnel = panelDNSTunnel(b.DNSTunnel) + sawDNSTunnel := false st.Servers, st.Entries, st.Unsupported, st.UnsupportedKinds = []Server{}, nil, 0, nil st.Telegram, st.DevicesUsed, st.DevicesLimit = nil, 0, 0 st.Debug = panelDebug(b.Debug) @@ -663,11 +675,14 @@ func (s *Store) syncNow(ctx context.Context, st storedSubscription) (storedSubsc continue } path.Via = shortText(path.Via) - if path.Purpose != profile.PurposeWhitelist { + if path.Protocol == "dnstunnel" { + sawDNSTunnel = true + path.Purpose = profile.PurposeWhitelist // never an ordinary path, whatever the panel says + } else if path.Purpose != profile.PurposeWhitelist { path.Purpose = "" } raw, err := json.Marshal(path) - if _, _, _, _, perr := pathProfile(string(raw)); err != nil || perr != nil || path.ID == "" || len(path.ID) > 128 { + if _, _, _, _, _, perr := pathProfile(string(raw)); err != nil || perr != nil || path.ID == "" || len(path.ID) > 128 { st.Unsupported++ continue } @@ -698,6 +713,9 @@ func (s *Store) syncNow(ctx context.Context, st storedSubscription) (storedSubsc st.Entries = append(st.Entries, storedEntry{Server: entry, Raw: string(raw)}) } } + if st.DNSTunnel == nil && sawDNSTunnel { + st.DNSTunnel = oldDNSTunnel // a sync with the path but no block keeps the list it had + } for _, proxy := range b.Telegram { if len(st.Telegram) < maxTelegram && telegramLink(proxy.Link) { st.Telegram = append(st.Telegram, Telegram{Node: shortText(proxy.ServerID), Country: countryCode(proxy.Country), City: shortText(proxy.City), @@ -814,18 +832,25 @@ func (s *Store) pendingKey(link string) (string, error) { } // pathProfile turns stored panel JSON into a protocol profile using that protocol's settings parser. -func pathProfile(raw string) (*profile.Hy2, *profile.AWG, *profile.VLESS, *profile.TrustTunnel, error) { +func pathProfile(raw string) (*profile.Hy2, *profile.AWG, *profile.VLESS, *profile.TrustTunnel, *profile.DNSTunnel, error) { var path syncPath if json.Unmarshal([]byte(raw), &path) != nil { - return nil, nil, nil, nil, errors.New("invalid stored path") + return nil, nil, nil, nil, nil, errors.New("invalid stored path") } if path.Protocol == "vless" { vless, err := profile.ParseVLESS(path.Settings) - return nil, nil, vless, nil, err + return nil, nil, vless, nil, nil, err } if path.Protocol == "trusttunnel" { trustTunnel, err := profile.ParseTrustTunnelPath(path.Settings) - return nil, nil, nil, trustTunnel, err + return nil, nil, nil, trustTunnel, nil, err + } + if path.Protocol == "dnstunnel" { + dnst, err := profile.ParseDNSTunnelPath(path.Settings) + if err == nil && !dnsTunnelEngine { + err = errors.New("DNS tunnel is not supported by this client") // read and counted, but not offered + } + return nil, nil, nil, nil, dnst, err } var proxy map[string]any var err error @@ -838,10 +863,10 @@ func pathProfile(raw string) (*profile.Hy2, *profile.AWG, *profile.VLESS, *profi err = errors.New("unsupported path protocol") } if err != nil { - return nil, nil, nil, nil, err + return nil, nil, nil, nil, nil, err } _, hy2, awg, err := parseProxyProfile(proxy) - return hy2, awg, nil, nil, err + return hy2, awg, nil, nil, nil, err } func hy2Proxy(settings json.RawMessage) (map[string]any, error) { @@ -930,3 +955,48 @@ func awgProxy(settings json.RawMessage) (map[string]any, error) { } return proxy, nil } + +// maxDNSTunnelResolvers is what is kept of the panel's dns_tunnel list. +const maxDNSTunnelResolvers = 64 + +// panelDNSTunnel reads the sync's dns_tunnel block: nil when it is absent or not an object. A resolver that is not +// "system" or an IP (or IP:port, port 53 by default), or whose proto is not udp, is dropped on its own; so are those +// past the 64th. The ttl is kept but does not expire the list. +func panelDNSTunnel(raw json.RawMessage) *profile.DNSTunnelResolvers { + var block struct { + TTL int64 `json:"ttl"` + ClientASN uint32 `json:"client_asn"` + Resolvers []json.RawMessage `json:"resolvers"` + } + if len(raw) == 0 || json.Unmarshal(raw, &block) != nil { + return nil + } + out := &profile.DNSTunnelResolvers{TTL: max(block.TTL, 0), ClientASN: block.ClientASN} + for _, item := range block.Resolvers { + var r struct { + Addr string `json:"addr"` + Proto string `json:"proto"` + ASN []uint32 `json:"asn"` + Operator string `json:"operator"` + } + if len(out.Resolvers) >= maxDNSTunnelResolvers { + break + } + if json.Unmarshal(item, &r) != nil || r.Proto != "" && strings.ToLower(r.Proto) != "udp" { + continue + } + addr := r.Addr + if addr != "system" { + ap, err := netip.ParseAddrPort(addr) + if ip, ipErr := netip.ParseAddr(addr); ipErr == nil { + ap, err = netip.AddrPortFrom(ip, 53), nil + } + if err != nil || ap.Port() == 0 || ap.Addr().Zone() != "" || ap.Addr().IsUnspecified() || ap.Addr().IsMulticast() { + continue + } + addr = ap.String() + } + out.Resolvers = append(out.Resolvers, profile.DNSResolver{Addr: addr, ASN: r.ASN[:min(len(r.ASN), 16)], Operator: shortText(r.Operator)}) + } + return out +} diff --git a/core/internal/subs/dnstunnel_test.go b/core/internal/subs/dnstunnel_test.go new file mode 100644 index 0000000..da79aec --- /dev/null +++ b/core/internal/subs/dnstunnel_test.go @@ -0,0 +1,123 @@ +package subs + +import ( + "context" + "encoding/json" + "fmt" + "net/netip" + "testing" + + "github.com/mistgate/mistgate-client/core/internal/profile" +) + +func TestPanelDNSTunnelBlock(t *testing.T) { + var many []map[string]any + for i := 0; i < 65; i++ { + many = append(many, map[string]any{"addr": fmt.Sprintf("192.0.2.%d", i+1)}) + } + block := func(resolvers any) json.RawMessage { + data, _ := json.Marshal(map[string]any{"ttl": 86400, "client_asn": 64496, "resolvers": resolvers}) + return data + } + if got := panelDNSTunnel(block(many)); len(got.Resolvers) != 64 || got.Resolvers[63].Addr != "192.0.2.64:53" || got.TTL != 86400 || got.ClientASN != 64496 { + t.Fatalf("65 entries: %d kept, %#v", len(got.Resolvers), got) + } + got := panelDNSTunnel(block([]map[string]any{ + {"addr": "system"}, + {"addr": "192.0.2.53:5353", "proto": "udp", "asn": []int{64496}, "operator": "Example Net"}, + {"addr": "192.0.2.54", "proto": ""}, + {"addr": "[2001:db8::53]:53"}, + {"addr": "dns.example.com"}, + {"addr": "dns.example.com:53"}, + {"addr": "192.0.2.0/24"}, + {"addr": "192.0.2.55", "proto": "doh"}, + {"addr": "192.0.2.56", "proto": "tcp"}, + {"addr": "0.0.0.0"}, + {"addr": "192.0.2.57:0"}, + {"addr": "192.0.2.58", "asn": "bad"}, + })) + want := []profile.DNSResolver{ + {Addr: "system"}, {Addr: "192.0.2.53:5353", ASN: []uint32{64496}, Operator: "Example Net"}, + {Addr: "192.0.2.54:53"}, {Addr: "[2001:db8::53]:53"}, + } + if fmt.Sprint(got.Resolvers) != fmt.Sprint(want) { + t.Fatalf("resolvers = %v, want %v", got.Resolvers, want) + } + if panelDNSTunnel(nil) != nil || panelDNSTunnel(json.RawMessage(`"x"`)) != nil { + t.Fatal("an absent or malformed block is a block") + } +} + +func dnstDoc(t *testing.T, block map[string]any, paths ...map[string]any) string { + var doc map[string]any + if err := json.Unmarshal([]byte(syncDoc("active", apiServer("Berlin", "DE", paths...))), &doc); err != nil { + t.Fatal(err) + } + if block != nil { + doc["dns_tunnel"] = block + } + data, _ := json.Marshal(doc) + return string(data) +} + +func dnstPath(purpose string) map[string]any { + path := apiPath("pth_dns", "dnstunnel", "direct", false, map[string]any{"v": 1, "domain": "k3x9ab.t.example.com", "key": "kid.SECRET", "kbps_hint": 200}) + if purpose != "" { + path["purpose"] = purpose + } + return path +} + +func TestClientAPIDNSTunnel(t *testing.T) { + block := map[string]any{"ttl": 1, "client_asn": 64496, "resolvers": []map[string]any{{"addr": "system"}, {"addr": "192.0.2.53:53", "asn": []int{64496}}}} + ordinary := apiPath("pth_ok", "hysteria2", "direct", false, map[string]any{"server": "oslo.example", "port": 443, "auth": "a", "tls": "ca"}) + panel, store, sub := managedStore(t) + stored := func() *profile.DNSTunnelResolvers { return store.state.Subscriptions[0].DNSTunnel } + + // The switch is off: the path is read, counted as unsupported and not offered; the block is kept. + panel.set(func() { panel.syncBody = dnstDoc(t, block, dnstPath("whitelist"), ordinary) }) + got, err := store.Refresh(context.Background(), sub.ID) + if err != nil || len(got.Servers) != 1 || got.Servers[0].ID != "pth_ok" || got.Unsupported != 1 { + t.Fatalf("refresh = %#v, %v", got, err) + } + if profiles, _ := store.Profiles(); len(profiles) != 1 || profiles[0].DNST != nil { + t.Fatalf("profiles = %d", len(profiles)) + } + if l := stored(); l == nil || len(l.Resolvers) != 2 || l.TTL != 1 || l.ClientASN != 64496 { + t.Fatalf("stored = %#v", l) + } + + // The switch is on: the path is offered, as a whitelist path even when the panel says nothing of the purpose. + dnsTunnelEngine = true + t.Cleanup(func() { dnsTunnelEngine = false }) + panel.set(func() { panel.syncBody = dnstDoc(t, block, dnstPath(""), ordinary) }) + got, err = store.Refresh(context.Background(), sub.ID) + if err != nil || len(got.Servers) != 2 || got.Servers[0].Purpose != profile.PurposeWhitelist || got.Unsupported != 0 { + t.Fatalf("refresh = %#v, %v", got, err) + } + profiles, _ := store.Profiles() + if len(profiles) != 2 || profiles[0].DNST == nil || profiles[0].DNST.Domain != "k3x9ab.t.example.com" || profiles[0].Purpose != profile.PurposeWhitelist || + profiles[0].PanelDNST == nil || profiles[1].DNST != nil || profiles[1].PanelDNST != nil { + t.Fatalf("profiles = %#v", profiles) + } + if p, ok := profile.Pick(profiles, "auto", "", ""); !ok || p.ID != "pth_ok" { + t.Fatalf("Auto's home = %q", p.ID) + } + if others := profile.Others(profiles, "auto", "", "", "", false, ""); len(others) != 0 { + t.Fatalf("the DNS tunnel is in the round of ordinary paths: %d", len(others)) + } + want := []netip.AddrPort{netip.MustParseAddrPort("192.0.2.53:53"), netip.MustParseAddrPort("192.0.2.9:53")} + if got := profiles[0].PanelDNST.Endpoints(addrs("192.0.2.9")); fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("endpoints = %v", got) + } + + // A sync with the path and no block keeps the list; one with neither drops it. + panel.set(func() { panel.syncBody = dnstDoc(t, nil, dnstPath(""), ordinary) }) + if _, err = store.Refresh(context.Background(), sub.ID); err != nil || stored() == nil || len(stored().Resolvers) != 2 { + t.Fatalf("the list after a sync with no block: %#v, %v", stored(), err) + } + panel.set(func() { panel.syncBody = dnstDoc(t, nil, ordinary) }) + if _, err = store.Refresh(context.Background(), sub.ID); err != nil || stored() != nil { + t.Fatalf("the list after a sync with no path: %#v, %v", stored(), err) + } +} diff --git a/core/internal/subs/store.go b/core/internal/subs/store.go index bce1934..8913a93 100644 --- a/core/internal/subs/store.go +++ b/core/internal/subs/store.go @@ -463,7 +463,10 @@ func (s *Store) Profiles() ([]profile.Profile, error) { var err error switch { case strings.HasPrefix(entry.Raw, "{"): - p.Hy2, p.AWG, p.VLESS, p.TT, err = pathProfile(entry.Raw) + p.Hy2, p.AWG, p.VLESS, p.TT, p.DNST, err = pathProfile(entry.Raw) + if p.DNST != nil { + p.Purpose, p.PanelDNST = profile.PurposeWhitelist, sub.DNSTunnel // never an ordinary path, even from an older store + } case entry.Server.Protocol == "hysteria2": if strings.Contains(entry.Raw, "://") { p.Hy2, err = profile.ParseHy2(entry.Raw) diff --git a/docs/client-api.md b/docs/client-api.md index 7ad2196..66cabb8 100644 --- a/docs/client-api.md +++ b/docs/client-api.md @@ -153,10 +153,11 @@ The body (stable key order; the client ignores fields it does not know): "servers": [ { "transport": "plain|dot|doh", "address": "…", "ips": ["…"] } ], "split": [ { "suffixes": ["ru"], "geo": ["cn"], "servers": [ ] } ], "split_direct": false, "block_ads": false, "ipv4_only": false }, + "dns_tunnel": { "ttl": 86400, "client_asn": 0, "resolvers": [ { "addr": "system" } ] }, "servers": [ { "id": "srv_…", "country": "DE", "city": "Frankfurt", "load": "low|medium|high", "paths": [ - { "id": "pth_…", "protocol": "hysteria2|awg|vless|trusttunnel", "via": "direct|relay|warp", "ipv6": false, "settings": { } } + { "id": "pth_…", "protocol": "hysteria2|awg|vless|trusttunnel|dnstunnel", "via": "direct|relay|warp", "ipv6": false, "settings": { } } ] } ] } @@ -184,6 +185,15 @@ The body (stable key order; the client ignores fields it does not know): flow is read as well. In `all` only the DNS questions are checked, so a program that does not ask the system's DNS gets nothing blocked there; AmneziaWG then also runs behind the client's forwarder. `dns` is absent when the status is not `active` or the panel has no usable preset. +- `dns_tunnel` (**experimental, engine not shipped yet**), for `dnstunnel` paths: `{ "ttl": 86400, "client_asn": 64496, + "resolvers": [ { "addr": "system" }, { "addr": "192.0.2.53:53", "proto": "udp", "asn": [64496], "operator": "…" } ] }`. + `addr` is `system` (the DNS servers of the physical interface, IPv4 only) or an IP or `IP:port` (port 53 by default); + a host name, a CIDR or an unusable address is dropped. `proto` is empty or `udp`; `tcp`, `doh` and the like drop the + entry. At most 64 entries are kept; a dropped entry does not fail the sync. `asn` and `operator` are kept. The client + gives the engine the list as addresses (`profile.DNSTunnelResolvers.Endpoints`): entries whose `asn` holds + `client_asn` first, the rest in order, no duplicates. `ttl` is kept but an expired list is NOT deleted (under an + allowlist the panel cannot be reached; an old list beats none). A sync with no block keeps the list while it still + carries a `dnstunnel` path, and drops it otherwise. - `servers` is `[]` unless the status is `active`. With another status the answer is still `200`, with the status, plan, brand, notice, probe and debug. - Ids are opaque and stable. A server is one exit node; its IPv6 entry and each relay are more **paths** of the same @@ -236,6 +246,15 @@ The body (stable key order; the client ignores fields it does not know): place (`profile.ParseTrustTunnelPath`); an unknown `transport` or `tls`, a missing `sni` or a bad pin makes the path unsupported. The endpoint may answer a refused request with any status: everything but 200 is a refusal, and the client does not retry against an endpoint that refuses. +- `dnstunnel` (DNS tunnel, **experimental, engine not shipped yet**): `{ "v": 1, "domain": "k3x9ab.t.example.com", + "key": ".", "udp": false, "kbps_hint": 200 }`. A slow path for networks that pass only an allowlist + of sites, sent with `purpose: "whitelist"`; the client treats the path as a whitelist path whatever `purpose` says, so + it is never in Auto. `v` other than 1 or a `domain` that is not a DNS name (two or more labels of letters, digits and + inner hyphens) makes the path unsupported; `key` is an opaque non-empty string, never parsed, logged or put in an error; + `udp` is ignored (always false); `kbps_hint` is optional; unknown fields are ignored. The client reads these fields in + one place (`profile.ParseDNSTunnelPath`). Until the engine ships the client does not announce `dnstunnel=1` in + `X-Mistgate-Caps`, and a path of this kind that arrives all the same is read but counted in `unsupported`, not + offered (`subs.dnsTunnelEngine`). **AmneziaWG keys.** The panel generates the device's key pairs and delivers them in `sync` (the owner's ruling). A key the client makes itself would be a later capability. diff --git a/docs/ipc.md b/docs/ipc.md index 38bd249..ce5726a 100644 --- a/docs/ipc.md +++ b/docs/ipc.md @@ -685,6 +685,10 @@ on a panel that does not send them): Subscriptions expose `notice` (empty when the panel sent no message), the panel's `Announce` response header decoded from plain text or `base64:`. +Experimental, engine not shipped yet: a `dnstunnel` path (a DNS tunnel for allowlisted networks, see `docs/client-api.md`) +and the sync's `dns_tunnel` resolver block are read and kept, but no such server is offered: `servers.list` and the +profiles do not have it, and it is counted in `unsupported`. When the engine ships it will be a `purpose: whitelist` +server of protocol `dnstunnel`; it is never in `auto`, and the connection checks and `rtt` skip it. `tt://` links of TrustTunnel are read too (the binary form of its DEEP_LINK.md, versions up to 2, with or without the `?`; protocol `trusttunnel`): the client connects over HTTP/2 only, whatever the link asks; `anti_dpi` and `dns_upstreams` are not used; a link that needs a TLS client random (`client_random_prefix`,