Files
zapret-autotune/cmd/zapret-autotune/resource_dns_test.go
T
ZeusinaandGPT-6 Bot 4d7c4b33c3 feat: add declarative HTTPS resource checks
Add strict check-only resource configuration, owned DNS resolution and pinned HTTPS probes with bounded private output. Document the schema limits and pending remote acceptance; leave generic controller and strategy migration out of scope.

Co-authored-by: GPT-6 <gpt-6@openai.com>
2026-10-13 18:38:46 +03:00

317 lines
12 KiB
Go

package main
import (
"context"
"encoding/binary"
"errors"
"io"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
)
func resourceDNSNameForTest(host string) []byte {
var name []byte
for _, s := range strings.Split(host, ".") {
name = append(name, byte(len(s)))
name = append(name, s...)
}
return append(name, 0)
}
func resourceDNSRecordForTest(owner string, kind uint16, data []byte) []byte {
r := resourceDNSNameForTest(owner)
r = append(r, byte(kind>>8), byte(kind), 0, 1, 0, 0, 0, 1, byte(len(data)>>8), byte(len(data)))
return append(r, data...)
}
func resourceDNSResponseForTest(q []byte, answers, additional [][]byte) []byte {
r := append([]byte(nil), q...)
r[2], r[3] = 0x81, 0x80
binary.BigEndian.PutUint16(r[6:8], uint16(len(answers)))
binary.BigEndian.PutUint16(r[10:12], uint16(len(additional)))
for _, rr := range answers {
r = append(r, rr...)
}
for _, rr := range additional {
r = append(r, rr...)
}
return r
}
func TestResourceDNSWireOnlyAndAliases(t *testing.T) {
for _, mode := range []string{"hosts", "alias", "follow", "loop", "cross-loop", "incomplete", "additional", "unrelated", "mixed", "mapped", "linklocal", "servfail", "wrong-id", "wrong-question", "bad-cname", "duplicate-cname", "alias-address", "bad-address", "truncated", "cancel"} {
t.Run(mode, func(t *testing.T) {
calls := 0
var workers sync.WaitGroup
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
dial := func(ctx context.Context, network, server string) (net.Conn, error) {
calls++
if network != "tcp" || server != dnsListenAddress {
t.Fatal("wrong DNS route")
}
client, peer := net.Pipe()
workers.Add(1)
go func() {
defer workers.Done()
defer peer.Close()
peer.SetDeadline(time.Now().Add(time.Second))
var size [2]byte
if _, err := io.ReadFull(peer, size[:]); err != nil {
return
}
q := make([]byte, int(binary.BigEndian.Uint16(size[:])))
if _, err := io.ReadFull(peer, q); err != nil {
return
}
end, question, ok := dnsQuestion(q)
if !ok {
t.Error("bad query")
return
}
host, _ := resourceDNSHost(question[:len(question)-4])
kind := binary.BigEndian.Uint16(q[end-4:])
if mode == "cancel" {
cancel()
var b [1]byte
peer.Read(b[:])
return
}
if mode == "truncated" {
peer.Write([]byte{0, 20, 1})
return
}
address := resourceDNSRecordForTest(host, 1, []byte{93, 184, 216, 34})
var answer, additional [][]byte
if kind == 1 {
answer = [][]byte{address}
}
switch mode {
case "alias":
if kind == 1 {
answer = [][]byte{resourceDNSRecordForTest(host, 5, resourceDNSNameForTest("cdn.example")), resourceDNSRecordForTest("cdn.example", 1, []byte{93, 184, 216, 34})}
}
case "follow", "incomplete":
if host != "cdn.example" {
answer = [][]byte{resourceDNSRecordForTest(host, 5, resourceDNSNameForTest("cdn.example"))}
} else if mode == "incomplete" {
answer = nil
} else {
answer = [][]byte{resourceDNSRecordForTest(host, kind, net.ParseIP("2606:4700::1111").To16())}
if kind == 1 {
answer = [][]byte{address}
}
}
case "loop":
answer = [][]byte{resourceDNSRecordForTest(host, 5, resourceDNSNameForTest("cdn.example")), resourceDNSRecordForTest("cdn.example", 5, resourceDNSNameForTest(host))}
case "cross-loop":
if host == "example.com" {
answer = [][]byte{resourceDNSRecordForTest(host, 5, resourceDNSNameForTest("cdn.example"))}
} else {
answer = [][]byte{resourceDNSRecordForTest(host, 5, resourceDNSNameForTest("example.com")), resourceDNSRecordForTest("example.com", 1, []byte{93, 184, 216, 34})}
}
case "bad-cname":
answer = [][]byte{resourceDNSRecordForTest(host, 5, []byte{0xc0, 12, 0})}
case "duplicate-cname":
answer = [][]byte{resourceDNSRecordForTest(host, 5, resourceDNSNameForTest("one.example")), resourceDNSRecordForTest(host, 5, resourceDNSNameForTest("two.example"))}
case "alias-address":
answer = [][]byte{address, resourceDNSRecordForTest(host, 5, resourceDNSNameForTest("cdn.example"))}
case "bad-address":
answer = [][]byte{resourceDNSRecordForTest(host, 1, []byte{1, 2, 3})}
case "additional":
additional = [][]byte{resourceDNSRecordForTest("other.example", 1, []byte{127, 0, 0, 1})}
case "unrelated":
answer = append(answer, resourceDNSRecordForTest("other.example", 1, []byte{127, 0, 0, 1}))
case "mixed":
if kind == 1 {
answer = append(answer, resourceDNSRecordForTest(host, 1, []byte{10, 0, 0, 1}))
}
case "mapped":
if kind == 28 {
answer = [][]byte{resourceDNSRecordForTest(host, 28, net.ParseIP("::ffff:10.0.0.1").To16())}
}
case "linklocal":
if kind == 28 {
answer = [][]byte{resourceDNSRecordForTest(host, 28, net.ParseIP("fe80::1").To16())}
}
}
r := resourceDNSResponseForTest(q, answer, additional)
if mode == "servfail" {
r[3] = 0x82
}
if mode == "wrong-id" {
r[0] ^= 1
}
if mode == "wrong-question" {
r[13] ^= 1
}
binary.BigEndian.PutUint16(size[:], uint16(len(r)))
writeDNSFrame(peer, size[:], r)
}()
return client, nil
}
host := "example.com"
if mode == "hosts" {
host = "localhost"
}
ips, err := resolveResourceIPsWithDial(ctx, dnsListenAddress, host, dial)
workers.Wait()
valid := mode == "hosts" || mode == "alias" || mode == "follow" || mode == "additional" || mode == "mixed" || mode == "mapped" || mode == "linklocal"
if (err == nil) != valid || calls == 0 {
t.Fatalf("calls=%d ips=%v err=%v", calls, ips, err)
}
if mode == "hosts" && (calls != 2 || len(ips) != 1 || ips[0].String() != "93.184.216.34") {
t.Fatal("hosts file used", ips)
}
if mode == "additional" && len(ips) != 1 {
t.Fatal("additional glue collected", ips)
}
if mode == "mixed" || mode == "mapped" || mode == "linklocal" {
denied := false
for _, ip := range ips {
if !approvedResourceIP(resourceCheckSpec{}, ip) {
denied = true
}
}
if !denied {
t.Fatal("unsafe answer lost", ips)
}
}
})
}
for _, host := range []string{"localhost", "dev.home.zeusina.ru"} {
calls := 0
_, err := resolveResourceIPsWithDial(context.Background(), dnsListenAddress, host, func(context.Context, string, string) (net.Conn, error) { calls++; return nil, errors.New("offline") })
if err == nil || calls != 1 {
t.Fatal("system hosts/DNS bypass")
}
}
}
func resourceRuntimeFixture(t *testing.T) (managedDNSConfig, string, string, string) {
t.Helper()
root := t.TempDir()
proc, dir := filepath.Join(root, "proc"), filepath.Join(root, "private")
mkdir := func(p string) {
t.Helper()
if err := os.MkdirAll(p, 0700); err != nil {
t.Fatal(err)
}
}
write := func(p, s string) {
t.Helper()
if err := os.WriteFile(p, []byte(s), 0600); err != nil {
t.Fatal(err)
}
}
link := func(target, path string) {
t.Helper()
if err := os.Symlink(target, path); err != nil {
t.Fatal(err)
}
}
mkdir(dir)
mkdir(filepath.Join(proc, "net"))
mkdir(filepath.Join(proc, "1/fd"))
mkdir(filepath.Join(proc, "self/ns"))
executable := filepath.Join(root, "binary")
write(executable, "binary")
link(executable, filepath.Join(proc, "self/exe"))
for _, ns := range []string{"pid", "net"} {
link(ns+"[1]", filepath.Join(proc, "self/ns", ns))
}
write(filepath.Join(dir, "dns-ready"), "42\n")
link(dir, filepath.Join(proc, "1/fd/8"))
link(filepath.Join(dir, "dns-ready"), filepath.Join(proc, "1/fd/9"))
write(filepath.Join(dir, "local.json"), `{"server":"127.0.0.1","server_port":8388,"local_port":1080}`)
for _, p := range []struct {
pid int
exe string
args []string
sockets []string
}{
{42, executable, []string{"/usr/local/bin/zapret-autotune", "dns-forwarder", "serve"}, []string{"11", "12"}},
{43, "/usr/bin/ss-local", []string{"ss-local", "-c", dir + "/local.json"}, []string{"13"}},
{44, "/usr/bin/ss-server", []string{"ss-server", "-c", dir + "/server.json", "-d", dnsListenAddress}, []string{"14"}},
} {
base := filepath.Join(proc, strconv.Itoa(p.pid))
mkdir(filepath.Join(base, "fd"))
mkdir(filepath.Join(base, "ns"))
link(p.exe, filepath.Join(base, "exe"))
write(filepath.Join(base, "cmdline"), strings.Join(p.args, "\x00")+"\x00")
uid := strconv.Itoa(os.Geteuid())
write(filepath.Join(base, "status"), "PPid:\t1\nUid:\t"+strings.Join([]string{uid, uid, uid, uid}, "\t")+"\n")
for _, ns := range []string{"pid", "net"} {
link(ns+"[1]", filepath.Join(base, "ns", ns))
}
for i, inode := range p.sockets {
link("socket:["+inode+"]", filepath.Join(base, "fd", strconv.Itoa(i)))
}
}
write(filepath.Join(proc, "net/tcp"), "0: 0100007F:14E9 00000000:0000 0A 0 0 0 0 0 11\n1: 00000000:0438 00000000:0000 0A 0 0 0 0 0 13\n2: 00000000:20C4 00000000:0000 0A 0 0 0 0 0 14\n")
write(filepath.Join(proc, "net/udp"), "0: 0100007F:14E9 00000000:0000 07 0 0 0 0 0 12\n")
return managedDNSConfig{Mode: "doh"}, proc, dir, executable
}
func TestResourceDNSOwnedRuntime(t *testing.T) {
for _, mode := range []string{"valid", "missing", "symlink", "permissions", "stale", "unanchored", "foreign-udp", "foreign-tcp", "foreign-exe", "wrong-parent", "namespace", "ss-dns", "ss-remote"} {
t.Run(mode, func(t *testing.T) {
cfg, proc, dir, exe := resourceRuntimeFixture(t)
write := func(path, data string) {
if err := os.WriteFile(path, []byte(data), 0600); err != nil {
t.Fatal(err)
}
}
switch mode {
case "missing":
os.Remove(filepath.Join(dir, "dns-ready"))
case "symlink":
os.Rename(filepath.Join(dir, "dns-ready"), filepath.Join(dir, "other"))
os.Symlink("other", filepath.Join(dir, "dns-ready"))
case "permissions":
os.Chmod(filepath.Join(dir, "dns-ready"), 0644)
case "stale":
write(filepath.Join(dir, "dns-ready"), "45\n")
case "unanchored":
os.Remove(filepath.Join(proc, "1/fd/9"))
case "foreign-udp":
write(filepath.Join(proc, "net/udp"), "0: 0100007F:14E9 00000000:0000 07 0 0 0 0 0 99\n")
case "foreign-tcp":
write(filepath.Join(proc, "net/tcp"), "0: 0100007F:14E9 00000000:0000 0A 0 0 0 0 0 99\n")
case "foreign-exe":
os.Remove(filepath.Join(proc, "42/exe"))
os.Symlink("/usr/bin/other", filepath.Join(proc, "42/exe"))
case "wrong-parent":
write(filepath.Join(proc, "42/status"), "PPid: 45\nUid: 0 0 0 0\n")
case "namespace":
os.Remove(filepath.Join(proc, "42/ns/net"))
os.Symlink("net[other]", filepath.Join(proc, "42/ns/net"))
case "ss-dns":
write(filepath.Join(proc, "44/cmdline"), "ss-server\x00-c\x00"+dir+"/server.json\x00-d\x008.8.8.8\x00")
case "ss-remote":
write(filepath.Join(dir, "local.json"), `{"server":"8.8.8.8","server_port":8388,"local_port":1080}`)
}
err := verifyResourceDNSRuntimeAt(cfg, proc, dir, exe)
if (err == nil) != (mode == "valid") {
t.Fatalf("err=%v", err)
}
if mode != "valid" {
d := resourceCheckDeps{lookup: resourceCheckLookup, guard: func() error { return verifyResourceDNSRuntimeAt(cfg, proc, dir, exe) }, resolve: func(context.Context, string, string) ([]net.IP, error) {
t.Fatal("DNS probe before ownership")
return nil, nil
}, runner: func(context.Context, []string, io.Reader, io.Writer, io.Writer) error {
t.Fatal("transfer before ownership")
return nil
}}
if code := resourceCheckCLI(context.Background(), resourceCheckFile(t, resourceCheckExample), io.Discard, io.Discard, d); code != 2 {
t.Fatal("ownership failure did not block", code)
}
}
})
}
}