xray_setting.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. package service
  2. import (
  3. _ "embed"
  4. "encoding/base64"
  5. "encoding/json"
  6. "slices"
  7. "strconv"
  8. "strings"
  9. "github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database"
  11. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  12. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  13. )
  14. // XraySettingService provides business logic for Xray configuration management.
  15. // It handles validation and storage of Xray template configurations.
  16. type XraySettingService struct {
  17. SettingService
  18. }
  19. const (
  20. unencryptedOutboundProhibitedError = "without TLS or other encryption is prohibited unless the server address is a private IP or domain"
  21. unencryptedOutboundMinimumVersion = "26.7.11"
  22. )
  23. func (s *XraySettingService) SaveXraySetting(newXraySettings string) error {
  24. // The frontend round-trips the whole getXraySetting response back
  25. // through the textarea, so if it has ever received a wrapped
  26. // payload (see UnwrapXrayTemplateConfig) it sends that same wrapper
  27. // back here. Strip it before validation/storage, otherwise we save
  28. // garbage the next read can't recover from without this same call.
  29. newXraySettings = UnwrapXrayTemplateConfig(newXraySettings)
  30. if err := s.CheckXrayConfig(newXraySettings); err != nil {
  31. return err
  32. }
  33. if hoisted, err := EnsureStatsRouting(newXraySettings); err == nil {
  34. newXraySettings = hoisted
  35. }
  36. if synced, err := EnsureDnsServerRouting(newXraySettings); err == nil {
  37. newXraySettings = synced
  38. }
  39. if spelled, changed, err := database.RewriteDNSOutboundQTypeZero(newXraySettings); err == nil && changed {
  40. newXraySettings = spelled
  41. }
  42. return s.saveSetting("xrayTemplateConfig", newXraySettings)
  43. }
  44. func (s *XraySettingService) CheckXrayConfig(XrayTemplateConfig string) error {
  45. xrayConfig := &xray.Config{}
  46. err := json.Unmarshal([]byte(XrayTemplateConfig), xrayConfig)
  47. if err != nil {
  48. return common.NewError("xray template config invalid:", err)
  49. }
  50. if len(xrayConfig.OutboundConfigs) > 0 {
  51. var outbounds []json.RawMessage
  52. if err := json.Unmarshal(xrayConfig.OutboundConfigs, &outbounds); err != nil {
  53. return common.NewError("xray template config invalid: outbounds is not an array:", err)
  54. }
  55. coreVersion := "Unknown"
  56. if process := currentXrayProcess(); process != nil {
  57. coreVersion = process.GetXrayVersion()
  58. }
  59. for _, outbound := range outbounds {
  60. // Panel pseudo-protocol: validated panel-side because the core's
  61. // loader would reject it outright.
  62. if amneziawg.IsAmneziaWGOutbound(outbound) {
  63. var probe struct {
  64. Tag string `json:"tag"`
  65. }
  66. if err := json.Unmarshal(outbound, &probe); err != nil {
  67. return common.NewError("xray template config invalid: amneziawg outbound tag unreadable:", err)
  68. }
  69. if err := amneziawg.ValidateAmneziaWGOutbound(probe.Tag, outbound); err != nil {
  70. return err
  71. }
  72. continue
  73. }
  74. if err := xray.ValidateOutboundConfig(outbound); err != nil {
  75. if shouldSkipLegacyUnencryptedOutboundRejection(coreVersion, err) {
  76. continue
  77. }
  78. tagged := struct {
  79. Tag string `json:"tag"`
  80. }{}
  81. _ = json.Unmarshal(outbound, &tagged)
  82. return common.NewError("xray core rejects outbound \""+tagged.Tag+"\":", err)
  83. }
  84. }
  85. }
  86. return nil
  87. }
  88. // shouldSkipLegacyUnencryptedOutboundRejection lets an older running Xray
  89. // core accept an outbound that the newer embedded validator rejects solely
  90. // because it is unencrypted and targets a public address. Unknown or malformed
  91. // versions preserve the embedded validator's strict behavior.
  92. func shouldSkipLegacyUnencryptedOutboundRejection(coreVersion string, err error) bool {
  93. if err == nil || !strings.Contains(err.Error(), unencryptedOutboundProhibitedError) {
  94. return false
  95. }
  96. comparison, ok := compareXrayCoreVersions(coreVersion, unencryptedOutboundMinimumVersion)
  97. return ok && comparison < 0
  98. }
  99. func compareXrayCoreVersions(a, b string) (int, bool) {
  100. aParts, okA := parseXrayCoreVersionParts(a)
  101. bParts, okB := parseXrayCoreVersionParts(b)
  102. if !okA || !okB {
  103. return 0, false
  104. }
  105. for i := range len(aParts) {
  106. if aParts[i] > bParts[i] {
  107. return 1, true
  108. }
  109. if aParts[i] < bParts[i] {
  110. return -1, true
  111. }
  112. }
  113. return 0, true
  114. }
  115. func parseXrayCoreVersionParts(version string) ([3]int, bool) {
  116. var result [3]int
  117. parts := strings.Split(strings.TrimPrefix(strings.TrimSpace(version), "v"), ".")
  118. if len(parts) != len(result) {
  119. return result, false
  120. }
  121. for i, part := range parts {
  122. n, err := strconv.Atoi(part)
  123. if err != nil {
  124. return result, false
  125. }
  126. result[i] = n
  127. }
  128. return result, true
  129. }
  130. func (s *XraySettingService) UpdateWarpXraySetting(warpData map[string]string, warpConfig map[string]any) error {
  131. template, err := s.GetXrayConfigTemplate()
  132. if err != nil {
  133. return err
  134. }
  135. var cfg map[string]any
  136. if err := json.Unmarshal([]byte(template), &cfg); err != nil {
  137. return err
  138. }
  139. outbounds, ok := cfg["outbounds"].([]any)
  140. if !ok {
  141. return nil
  142. }
  143. updated := false
  144. for _, outIface := range outbounds {
  145. out, ok := outIface.(map[string]any)
  146. if !ok {
  147. continue
  148. }
  149. if tag, ok := out["tag"].(string); ok && tag == "warp" {
  150. settings, ok := out["settings"].(map[string]any)
  151. if !ok {
  152. continue
  153. }
  154. settings["secretKey"] = warpData["private_key"]
  155. if conf, ok := warpConfig["config"].(map[string]any); ok {
  156. if iface, ok := conf["interface"].(map[string]any); ok {
  157. if addrs, ok := iface["addresses"].(map[string]any); ok {
  158. var addrList []string
  159. if v4, ok := addrs["v4"].(string); ok && v4 != "" {
  160. addrList = append(addrList, v4+"/32")
  161. }
  162. if v6, ok := addrs["v6"].(string); ok && v6 != "" {
  163. addrList = append(addrList, v6+"/128")
  164. }
  165. settings["address"] = addrList
  166. }
  167. }
  168. var clientId string
  169. if id, ok := conf["client_id"].(string); ok {
  170. clientId = id
  171. } else if id, ok := warpData["client_id"]; ok {
  172. clientId = id
  173. }
  174. if clientId != "" {
  175. decoded, _ := base64.StdEncoding.DecodeString(clientId)
  176. var res []int
  177. for _, b := range decoded {
  178. res = append(res, int(b))
  179. }
  180. settings["reserved"] = res
  181. }
  182. if peers, ok := conf["peers"].([]any); ok && len(peers) > 0 {
  183. if peer, ok := peers[0].(map[string]any); ok {
  184. if pSettings, ok := settings["peers"].([]any); ok && len(pSettings) > 0 {
  185. if pSet, ok := pSettings[0].(map[string]any); ok {
  186. pSet["publicKey"] = peer["public_key"]
  187. if endpoint, ok := peer["endpoint"].(map[string]any); ok {
  188. pSet["endpoint"] = endpoint["host"]
  189. }
  190. }
  191. }
  192. }
  193. }
  194. }
  195. updated = true
  196. break
  197. }
  198. }
  199. if updated {
  200. outJSON, err := json.MarshalIndent(cfg, "", " ")
  201. if err != nil {
  202. return err
  203. }
  204. return s.SaveXraySetting(string(outJSON))
  205. }
  206. return nil
  207. }
  208. // UnwrapXrayTemplateConfig returns the raw xray config JSON from `raw`,
  209. // peeling off any number of `{ "inboundTags": ..., "outboundTestUrl": ...,
  210. // "xraySetting": <real config> }` response-shaped wrappers that may have
  211. // ended up in the database.
  212. //
  213. // How it got there: getXraySetting used to embed the raw DB value as
  214. // `xraySetting` in its response without checking whether the stored
  215. // value was already that exact response shape. If the frontend then
  216. // saved it verbatim (the textarea is a round-trip of the JSON it was
  217. // handed), the wrapper got persisted — and each subsequent save nested
  218. // another layer, producing the blank Xray Settings page reported in
  219. // issue #4059.
  220. //
  221. // If `raw` does not look like a wrapper, it is returned unchanged.
  222. func UnwrapXrayTemplateConfig(raw string) string {
  223. const maxDepth = 8 // defensive cap against pathological multi-nest values
  224. for range maxDepth {
  225. var top map[string]json.RawMessage
  226. if err := json.Unmarshal([]byte(raw), &top); err != nil {
  227. return raw
  228. }
  229. inner, ok := top["xraySetting"]
  230. if !ok {
  231. return raw
  232. }
  233. // Real xray configs never contain a top-level "xraySetting" key,
  234. // but they do contain things like "inbounds"/"outbounds"/"api".
  235. // If any of those are present, we're already at the real config
  236. // and the "xraySetting" field is either user data or coincidence
  237. // — don't touch it.
  238. for _, k := range []string{"inbounds", "outbounds", "routing", "api", "dns", "log", "policy", "stats"} {
  239. if _, hit := top[k]; hit {
  240. return raw
  241. }
  242. }
  243. // Peel off one layer.
  244. unwrapped := string(inner)
  245. // `xraySetting` may be stored either as a JSON object or as a
  246. // JSON-encoded string of an object. Handle both.
  247. var asStr string
  248. if err := json.Unmarshal(inner, &asStr); err == nil {
  249. unwrapped = asStr
  250. }
  251. raw = unwrapped
  252. }
  253. return raw
  254. }
  255. // EnsureStatsRouting hoists the `api -> api` routing rule to the front
  256. // of routing.rules so the stats query path is never starved by a
  257. // catch-all rule the admin may have added or reordered above it.
  258. //
  259. // Why this matters (#4113, #2818): an admin who adds a cascade outbound
  260. // (e.g. vless to another server) and a routing rule sending all inbound
  261. // traffic to it ends up sending the internal stats inbound's traffic to
  262. // that cascade too, since rules are evaluated top-to-bottom and the
  263. // catch-all matches first. The panel's gRPC stats query then can't reach
  264. // the running xray instance, GetTraffic returns nothing, and every
  265. // client appears offline with zero traffic even though the actual proxy
  266. // path works fine.
  267. //
  268. // The api inbound is special-cased internal infrastructure for the
  269. // panel, not something the admin should ever route to a real outbound.
  270. // Keeping its rule pinned at index 0 is the only correct configuration.
  271. //
  272. // If the api rule is already at index 0 the input is returned unchanged.
  273. // If it exists somewhere else it is moved. If it is missing entirely a
  274. // default rule (`type=field, inboundTag=[api], outboundTag=api`) is
  275. // inserted at the front. Other routing entries keep their relative order.
  276. func EnsureStatsRouting(raw string) (string, error) {
  277. var cfg map[string]json.RawMessage
  278. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  279. return raw, err
  280. }
  281. var routing map[string]json.RawMessage
  282. if r, ok := cfg["routing"]; ok && len(r) > 0 {
  283. if err := json.Unmarshal(r, &routing); err != nil {
  284. return raw, err
  285. }
  286. }
  287. if routing == nil {
  288. routing = make(map[string]json.RawMessage)
  289. }
  290. var rules []map[string]any
  291. if r, ok := routing["rules"]; ok && len(r) > 0 {
  292. if err := json.Unmarshal(r, &rules); err != nil {
  293. return raw, err
  294. }
  295. }
  296. apiIdx := findApiRule(rules)
  297. if apiIdx == 0 {
  298. return raw, nil // already correct, don't churn the JSON
  299. }
  300. var apiRule map[string]any
  301. if apiIdx > 0 {
  302. apiRule = rules[apiIdx]
  303. rules = append(rules[:apiIdx], rules[apiIdx+1:]...)
  304. } else {
  305. apiRule = map[string]any{
  306. "type": "field",
  307. "inboundTag": []string{"api"},
  308. "outboundTag": "api",
  309. }
  310. }
  311. delete(apiRule, "enabled")
  312. rules = append([]map[string]any{apiRule}, rules...)
  313. rulesJSON, err := json.Marshal(rules)
  314. if err != nil {
  315. return raw, err
  316. }
  317. routing["rules"] = rulesJSON
  318. routingJSON, err := json.Marshal(routing)
  319. if err != nil {
  320. return raw, err
  321. }
  322. cfg["routing"] = routingJSON
  323. out, err := json.Marshal(cfg)
  324. if err != nil {
  325. return raw, err
  326. }
  327. return string(out), nil
  328. }
  329. // isApiRule reports whether a routing rule targets the internal api inbound
  330. // (inboundTag contains "api" and outboundTag is "api").
  331. func isApiRule(rule map[string]any) bool {
  332. if outTag, _ := rule["outboundTag"].(string); outTag != "api" {
  333. return false
  334. }
  335. raw, ok := rule["inboundTag"]
  336. if !ok {
  337. return false
  338. }
  339. // inboundTag is usually []string but can come as []any from a
  340. // roundtrip through map[string]any. Accept both shapes.
  341. switch tags := raw.(type) {
  342. case []any:
  343. for _, t := range tags {
  344. if s, ok := t.(string); ok && s == "api" {
  345. return true
  346. }
  347. }
  348. case []string:
  349. if slices.Contains(tags, "api") {
  350. return true
  351. }
  352. case string:
  353. if tags == "api" {
  354. return true
  355. }
  356. }
  357. return false
  358. }
  359. // findApiRule returns the index of the routing rule that targets the
  360. // internal api inbound, or -1 if no such rule exists.
  361. func findApiRule(rules []map[string]any) int {
  362. for i, rule := range rules {
  363. if isApiRule(rule) {
  364. return i
  365. }
  366. }
  367. return -1
  368. }