xray_setting.go 12 KB

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