xray_setting.go 12 KB

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