1
0

xray_setting_dns_routing.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. package service
  2. import (
  3. "encoding/json"
  4. "net"
  5. "reflect"
  6. "sort"
  7. "strconv"
  8. "strings"
  9. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  10. )
  11. // dnsAllowRuleShape identifies routing rules this file manages: a plain
  12. // "type=field, ip=[...], port=..., outboundTag=direct" rule with no other
  13. // matchers. An "enabled" key is tolerated as long as it's true — the
  14. // Routing tab's rule editor (RuleFormModal.tsx submit()) and its enabled
  15. // switch (RoutingTab.tsx toggleRule()) always write that key back, even
  16. // when nothing else changed, so requiring its absence would disown the
  17. // rule the first time an admin so much as opens it in the UI. A rule
  18. // toggled off (enabled=false) is treated as no longer ours: the admin
  19. // explicitly turned it off, and re-enabling it on the next save would
  20. // silently override that choice.
  21. //
  22. // Rules shaped like this are kept in sync with the current dns.servers
  23. // config on every save; anything else (including rules an admin wrote by
  24. // hand that happen to also allow-list an IP) is left untouched.
  25. func dnsAllowRuleShape(rule map[string]any) bool {
  26. if t, _ := rule["type"].(string); t != "field" {
  27. return false
  28. }
  29. if out, _ := rule["outboundTag"].(string); out != "direct" {
  30. return false
  31. }
  32. if _, ok := rule["ip"]; !ok {
  33. return false
  34. }
  35. if _, ok := rule["port"]; !ok {
  36. return false
  37. }
  38. for key := range rule {
  39. switch key {
  40. case "type", "outboundTag", "ip", "port":
  41. continue
  42. case "enabled":
  43. if enabled, ok := rule[key].(bool); !ok || !enabled {
  44. return false
  45. }
  46. continue
  47. default:
  48. return false
  49. }
  50. }
  51. return true
  52. }
  53. // findPrivateBlockRule returns the index of a routing rule that blocks
  54. // geoip:private (the panel's default anti-SSRF rule), or -1 if none is
  55. // present. Matched by shape (outboundTag=blocked, ip contains
  56. // "geoip:private") rather than position, since admins can reorder rules.
  57. func findPrivateBlockRule(rules []map[string]any) int {
  58. for i, rule := range rules {
  59. if out, _ := rule["outboundTag"].(string); out != "blocked" {
  60. continue
  61. }
  62. for _, ip := range readRuleIPs(rule["ip"]) {
  63. if strings.EqualFold(ip, "geoip:private") {
  64. return i
  65. }
  66. }
  67. }
  68. return -1
  69. }
  70. func readRuleIPs(raw any) []string {
  71. switch v := raw.(type) {
  72. case []string:
  73. return v
  74. case []any:
  75. out := make([]string, 0, len(v))
  76. for _, item := range v {
  77. if s, ok := item.(string); ok {
  78. out = append(out, s)
  79. }
  80. }
  81. return out
  82. case string:
  83. if v == "" {
  84. return nil
  85. }
  86. return []string{v}
  87. default:
  88. return nil
  89. }
  90. }
  91. // dnsServerEndpoint is a literal (ip, port) pair extracted from a
  92. // dns.servers entry.
  93. type dnsServerEndpoint struct {
  94. ip string
  95. port int
  96. }
  97. // privateDnsServerEndpoint extracts a literal, private/internal (ip, port)
  98. // endpoint from a dns.servers entry, or ok=false if the entry is a domain
  99. // name, a special Xray keyword (localhost, fakedns, ...), or resolves to a
  100. // public IP.
  101. //
  102. // A dns.servers entry is either a bare string or an object with an
  103. // "address" field (see frontend/src/schemas/dns.ts DnsServerEntrySchema);
  104. // the object form may also carry an explicit "port" (default 53 there,
  105. // per DnsServerObjectInnerSchema), which takes precedence over any port
  106. // embedded in the address itself.
  107. func privateDnsServerEndpoint(entry any) (dnsServerEndpoint, bool) {
  108. var address string
  109. explicitPort := 0
  110. switch v := entry.(type) {
  111. case string:
  112. address = v
  113. case map[string]any:
  114. address, _ = v["address"].(string)
  115. if p, ok := v["port"].(float64); ok && p > 0 {
  116. explicitPort = int(p)
  117. }
  118. default:
  119. return dnsServerEndpoint{}, false
  120. }
  121. host, port := splitAddressHostPort(address)
  122. if host == "" {
  123. return dnsServerEndpoint{}, false
  124. }
  125. if explicitPort > 0 {
  126. port = explicitPort
  127. }
  128. ip := net.ParseIP(host)
  129. if ip == nil {
  130. // Domain name, or a special keyword like "localhost"/"fakedns" —
  131. // neither is something we can safely allow-list by IP here.
  132. return dnsServerEndpoint{}, false
  133. }
  134. if !netsafe.IsBlockedIP(ip) {
  135. return dnsServerEndpoint{}, false
  136. }
  137. return dnsServerEndpoint{ip: ip.String(), port: port}, true
  138. }
  139. // splitAddressHostPort extracts the bare host and port (defaulting to 53)
  140. // from an Xray-core DNS server address string. Those may carry a URI
  141. // scheme (tcp://, tcp+local://, https://, https+local://, quic://,
  142. // quic+local://) and, for DoH, a path and/or a bracketed IPv6 host — all
  143. // of that is stripped down to host[:port] before parsing.
  144. func splitAddressHostPort(address string) (host string, port int) {
  145. address = strings.TrimSpace(address)
  146. if address == "" {
  147. return "", 0
  148. }
  149. if idx := strings.Index(address, "://"); idx != -1 {
  150. address = address[idx+3:]
  151. }
  152. // Drop a DoH path, e.g. "1.1.1.1/dns-query".
  153. if idx := strings.Index(address, "/"); idx != -1 {
  154. address = address[:idx]
  155. }
  156. port = 53
  157. host = address
  158. if strings.HasPrefix(host, "[") {
  159. // Bracketed IPv6, with or without a port: "[::1]" / "[::1]:53".
  160. end := strings.Index(host, "]")
  161. if end == -1 {
  162. return host, port
  163. }
  164. rest := host[end+1:]
  165. host = host[1:end]
  166. if p, ok := strings.CutPrefix(rest, ":"); ok {
  167. if n, err := strconv.Atoi(p); err == nil {
  168. port = n
  169. }
  170. }
  171. return host, port
  172. }
  173. if h, p, err := net.SplitHostPort(host); err == nil {
  174. host = h
  175. if n, err := strconv.Atoi(p); err == nil {
  176. port = n
  177. }
  178. }
  179. return host, port
  180. }
  181. // dnsAllowPortGroup is the set of private literal IPs that share a single
  182. // port among the configured dns.servers, e.g. two internal resolvers both
  183. // queried on :53.
  184. type dnsAllowPortGroup struct {
  185. port int
  186. ips []string
  187. }
  188. // collectPrivateDnsAllowGroups returns the private dns.servers endpoints
  189. // grouped by port, sorted by port ascending (ips within a group sorted and
  190. // de-duplicated) for deterministic output.
  191. func collectPrivateDnsAllowGroups(dnsRaw json.RawMessage) []dnsAllowPortGroup {
  192. if len(dnsRaw) == 0 {
  193. return nil
  194. }
  195. var dns struct {
  196. Servers []any `json:"servers"`
  197. }
  198. if err := json.Unmarshal(dnsRaw, &dns); err != nil {
  199. return nil
  200. }
  201. byPort := make(map[int]map[string]bool)
  202. for _, entry := range dns.Servers {
  203. ep, ok := privateDnsServerEndpoint(entry)
  204. if !ok {
  205. continue
  206. }
  207. if byPort[ep.port] == nil {
  208. byPort[ep.port] = make(map[string]bool)
  209. }
  210. byPort[ep.port][ep.ip] = true
  211. }
  212. ports := make([]int, 0, len(byPort))
  213. for p := range byPort {
  214. ports = append(ports, p)
  215. }
  216. sort.Ints(ports)
  217. groups := make([]dnsAllowPortGroup, 0, len(ports))
  218. for _, p := range ports {
  219. ips := make([]string, 0, len(byPort[p]))
  220. for ip := range byPort[p] {
  221. ips = append(ips, ip)
  222. }
  223. sort.Strings(ips)
  224. groups = append(groups, dnsAllowPortGroup{port: p, ips: ips})
  225. }
  226. return groups
  227. }
  228. // EnsureDnsServerRouting keeps a set of managed "direct" allow-rules — one
  229. // per distinct port among any private/internal dns.servers addresses —
  230. // in sync, positioned immediately before the panel's default
  231. // geoip:private block rule.
  232. //
  233. // Why this matters: Xray's own DNS client traffic is dispatched through
  234. // the same routing table as proxied client traffic. If dns.servers points
  235. // at a private IP (e.g. a self-hosted AdGuard Home / Pi-hole reachable on
  236. // the same Docker network as Xray — a common self-hosted setup) and the
  237. // panel's default private-IP block rule is active, Xray's own DNS lookups
  238. // get silently dropped by that rule. Xray then falls back to dialing
  239. // destinations by raw hostname once its internal DNS attempt times out
  240. // (~4s), so proxied connections still work, just with a multi-second stall
  241. // added to every new domain, with no error surfaced to the client or
  242. // admin.
  243. //
  244. // Each managed rule is scoped to its port (not just the IP), so the
  245. // exception only reopens the DNS traffic that actually needs it rather
  246. // than every port on the private host. On every save, all previously
  247. // managed rules are stripped out and a fresh set is rebuilt from the
  248. // current dns.servers config and reinserted right before the block rule
  249. // (recomputing its index after the strip) — this corrects both content
  250. // drift (dns.servers changed) and position drift (an admin dragged a
  251. // managed rule below the block rule in the Routing tab, which would
  252. // otherwise silently reintroduce the stall with nothing to notice or fix
  253. // it). The rebuilt result is only written back if it actually differs
  254. // from the input, so well-formed configs aren't churned on every save.
  255. // Manually-authored rules are never touched — see dnsAllowRuleShape.
  256. func EnsureDnsServerRouting(raw string) (string, error) {
  257. var cfg map[string]json.RawMessage
  258. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  259. return raw, err
  260. }
  261. groups := collectPrivateDnsAllowGroups(cfg["dns"])
  262. var routing map[string]json.RawMessage
  263. if r, ok := cfg["routing"]; ok && len(r) > 0 {
  264. if err := json.Unmarshal(r, &routing); err != nil {
  265. return raw, err
  266. }
  267. }
  268. if routing == nil {
  269. return raw, nil
  270. }
  271. var original []map[string]any
  272. if r, ok := routing["rules"]; ok && len(r) > 0 {
  273. if err := json.Unmarshal(r, &original); err != nil {
  274. return raw, err
  275. }
  276. }
  277. rebuilt := rebuildDnsAllowRules(original, groups)
  278. rulesJSON, err := json.Marshal(rebuilt)
  279. if err != nil {
  280. return raw, err
  281. }
  282. // Compare against the original rules JSON, not the parsed Go values:
  283. // json.Unmarshal into []map[string]any turns "ip" arrays into []any,
  284. // while the rules this function builds use []string — those hold
  285. // identical content but are different types under reflect.DeepEqual,
  286. // which would otherwise report a no-op input as changed and churn the
  287. // JSON on every save for no reason.
  288. origRulesJSON := routing["rules"]
  289. if len(origRulesJSON) == 0 {
  290. origRulesJSON = json.RawMessage("[]")
  291. }
  292. if jsonEqual(origRulesJSON, rulesJSON) {
  293. return raw, nil
  294. }
  295. routing["rules"] = rulesJSON
  296. routingJSON, err := json.Marshal(routing)
  297. if err != nil {
  298. return raw, err
  299. }
  300. cfg["routing"] = routingJSON
  301. out, err := json.Marshal(cfg)
  302. if err != nil {
  303. return raw, err
  304. }
  305. return string(out), nil
  306. }
  307. // rebuildDnsAllowRules strips any existing managed rules out of rules,
  308. // then — if a geoip:private block rule is present and groups is non-empty
  309. // — reinserts a freshly built managed rule per group immediately before
  310. // it. This uniformly handles content updates, position drift, and removal
  311. // (an empty groups list just leaves the managed rules stripped).
  312. func rebuildDnsAllowRules(rules []map[string]any, groups []dnsAllowPortGroup) []map[string]any {
  313. clean := make([]map[string]any, 0, len(rules))
  314. for _, rule := range rules {
  315. if !dnsAllowRuleShape(rule) {
  316. clean = append(clean, rule)
  317. }
  318. }
  319. blockIdx := findPrivateBlockRule(clean)
  320. if blockIdx < 0 || len(groups) == 0 {
  321. return clean
  322. }
  323. managed := make([]map[string]any, 0, len(groups))
  324. for _, g := range groups {
  325. managed = append(managed, map[string]any{
  326. "type": "field",
  327. "ip": g.ips,
  328. "port": strconv.Itoa(g.port),
  329. "outboundTag": "direct",
  330. })
  331. }
  332. // Capacity hint uses len(clean) alone (not len(clean)+len(managed)):
  333. // summing two independent lengths for a make() size risks overflow on
  334. // pathological input per static analysis, and clean's length already
  335. // covers most of the eventual size on its own.
  336. out := make([]map[string]any, 0, len(clean))
  337. out = append(out, clean[:blockIdx]...)
  338. out = append(out, managed...)
  339. out = append(out, clean[blockIdx:]...)
  340. return out
  341. }
  342. // jsonEqual reports whether a and b decode to structurally identical
  343. // values. Used instead of comparing raw bytes (key order, whitespace) or
  344. // reflect.DeepEqual on already-parsed Go values (which is type-sensitive
  345. // to []any vs []string and would misreport identical content as changed).
  346. func jsonEqual(a, b json.RawMessage) bool {
  347. var av, bv any
  348. if err := json.Unmarshal(a, &av); err != nil {
  349. return false
  350. }
  351. if err := json.Unmarshal(b, &bv); err != nil {
  352. return false
  353. }
  354. return reflect.DeepEqual(av, bv)
  355. }