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
8 changes: 7 additions & 1 deletion core/internal/diag/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Expand Down Expand Up @@ -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)
Expand All @@ -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)
}
Expand Down
4 changes: 2 additions & 2 deletions core/internal/engine/real_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
112 changes: 112 additions & 0 deletions core/internal/profile/dnstunnel.go
Original file line number Diff line number Diff line change
@@ -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
}
77 changes: 77 additions & 0 deletions core/internal/profile/dnstunnel_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
3 changes: 3 additions & 0 deletions core/internal/profile/profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
Expand Down
Loading
Loading