masque_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. package sub
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "reflect"
  8. "strconv"
  9. "testing"
  10. xnet "github.com/xtls/xray-core/common/net"
  11. "github.com/xtls/xray-core/infra/conf"
  12. "github.com/xtls/xray-core/transport/internet"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database"
  14. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  15. )
  16. // MASQUE has no share-link format, so the JSON subscription is the only way a client
  17. // gets one: a masque outbound authenticating with the client's email and password.
  18. func TestSubJsonServiceMasqueClientConfig(t *testing.T) {
  19. inbound := &model.Inbound{
  20. Listen: "203.0.113.9", Port: 8443, Protocol: model.MASQUE, Remark: "masque",
  21. Settings: `{"clients":[{"email":"[email protected]","password":"pw-ivy"}],"address":["10.14.0.1/24"]}`,
  22. StreamSettings: `{"network":"masque","security":"tls",
  23. "masqueSettings":{"path":"/.well-known/masque/ip/*/*/"},
  24. "tlsSettings":{"serverName":"masque.example.test","alpn":["h3"],
  25. "certificates":[{"certificateFile":"/etc/ssl/m.crt","keyFile":"/etc/ssl/m.key"}],
  26. "settings":{"fingerprint":"chrome"}}}`,
  27. }
  28. client := model.Client{Email: "[email protected]", Password: "pw-ivy"}
  29. configs := NewSubJsonService("", "", "", "", nil).getConfig(&SubService{address: "sub.example.com"}, inbound, client, "sub.example.com")
  30. if len(configs) != 1 {
  31. t.Fatalf("got %d configs, want one", len(configs))
  32. }
  33. var config struct {
  34. Outbounds []struct {
  35. Protocol string `json:"protocol"`
  36. Settings map[string]any `json:"settings"`
  37. StreamSettings map[string]any `json:"streamSettings"`
  38. } `json:"outbounds"`
  39. }
  40. if err := json.Unmarshal(configs[0], &config); err != nil {
  41. t.Fatalf("decode config: %v", err)
  42. }
  43. proxy := config.Outbounds[0]
  44. if proxy.Protocol != "masque" {
  45. t.Fatalf("first outbound protocol = %q, want masque", proxy.Protocol)
  46. }
  47. if proxy.Settings["address"] != "203.0.113.9" || proxy.Settings["port"] != float64(8443) {
  48. t.Fatalf("masque settings = %v, want the inbound address and port", proxy.Settings)
  49. }
  50. wantMasque := map[string]any{"path": "/.well-known/masque/ip/*/*/", "user": "[email protected]", "pass": "pw-ivy"}
  51. if got := proxy.StreamSettings["masqueSettings"]; !reflect.DeepEqual(got, wantMasque) {
  52. t.Fatalf("masqueSettings = %v, want %v", got, wantMasque)
  53. }
  54. tls, _ := proxy.StreamSettings["tlsSettings"].(map[string]any)
  55. if proxy.StreamSettings["network"] != "masque" || proxy.StreamSettings["security"] != "tls" ||
  56. tls["serverName"] != "masque.example.test" || tls["certificates"] != nil {
  57. t.Fatalf("stream = %v, want masque over client-side TLS to masque.example.test", proxy.StreamSettings)
  58. }
  59. }
  60. // The subscription SQL allowlist decides which inbounds a subId can see at all; left
  61. // off it, a MASQUE client's JSON subscription would come back empty.
  62. func TestGetInboundsBySubIdIncludesMasque(t *testing.T) {
  63. initSubDB(t)
  64. db := database.GetDB()
  65. in := &model.Inbound{Port: 8443, Protocol: model.MASQUE, Enable: true, Tag: "masque-sub", Settings: `{"clients":[],"address":["10.14.0.1/24"]}`}
  66. if err := db.Create(in).Error; err != nil {
  67. t.Fatalf("create inbound: %v", err)
  68. }
  69. rec := &model.ClientRecord{Email: "u@masque", SubID: "submasque", Enable: true}
  70. if err := db.Create(rec).Error; err != nil {
  71. t.Fatalf("create client: %v", err)
  72. }
  73. if err := db.Create(&model.ClientInbound{ClientId: rec.Id, InboundId: in.Id}).Error; err != nil {
  74. t.Fatalf("create link: %v", err)
  75. }
  76. inbounds, err := (&SubService{}).getInboundsBySubId("submasque")
  77. if err != nil {
  78. t.Fatalf("getInboundsBySubId: %v", err)
  79. }
  80. if len(inbounds) != 1 || inbounds[0].Id != in.Id {
  81. t.Fatalf("masque inbound not returned for subId: %+v", inbounds)
  82. }
  83. }
  84. // An inbound keeps its hop range in quicParams.udpHop (udphop refuses to run on a server),
  85. // but the client config must carry the udphop mask: the core ignores the old key since 26.9.9.
  86. func TestSubJsonServiceTurnsInboundHopIntoClientUDPHopMask(t *testing.T) {
  87. inbound := &model.Inbound{
  88. Listen: "203.0.113.10", Port: 443, Protocol: model.Hysteria, Remark: "hy",
  89. Settings: `{"version":2,"clients":[{"email":"[email protected]","auth":"a"}]}`,
  90. StreamSettings: `{"network":"hysteria","security":"tls",
  91. "hysteriaSettings":{"version":2},
  92. "tlsSettings":{"serverName":"hy.example.test","alpn":["h3"]},
  93. "finalmask":{"quicParams":{"udpHop":{"ports":"20000-30000","interval":"5-10"}}}}`,
  94. }
  95. client := model.Client{Email: "[email protected]", Auth: "a"}
  96. configs := NewSubJsonService("", "", "", "", nil).getConfig(&SubService{address: "sub.example.com"}, inbound, client, "sub.example.com")
  97. if len(configs) != 1 {
  98. t.Fatalf("got %d configs, want one", len(configs))
  99. }
  100. var config struct {
  101. Outbounds []struct {
  102. Protocol string `json:"protocol"`
  103. StreamSettings map[string]any `json:"streamSettings"`
  104. } `json:"outbounds"`
  105. }
  106. if err := json.Unmarshal(configs[0], &config); err != nil {
  107. t.Fatalf("decode config: %v", err)
  108. }
  109. got, _ := json.Marshal(config.Outbounds[0].StreamSettings["finalmask"])
  110. const want = `{"udp":[{"settings":{"interval":"5-10","mode":"intervalRemote","remotePorts":"20000-30000"},"type":"udphop"}]}`
  111. if string(got) != want {
  112. t.Fatalf("client finalmask\n got: %s\nwant: %s", got, want)
  113. }
  114. }
  115. // coreDialsUDP dials a client stream's finalmask the way the core does: it reverses the
  116. // UDP masks and refuses a udphop anywhere but the socket end ("incorrect index").
  117. func coreDialsUDP(t *testing.T, stream map[string]any) {
  118. t.Helper()
  119. listener, err := net.ListenPacket("udp", "127.0.0.1:0")
  120. if err != nil {
  121. t.Fatalf("listen udp: %v", err)
  122. }
  123. defer listener.Close()
  124. raw, _ := json.Marshal(map[string]any{"finalmask": stream["finalmask"]})
  125. var sc conf.StreamConfig
  126. if err := json.Unmarshal(raw, &sc); err != nil {
  127. t.Fatalf("decode stream: %v", err)
  128. }
  129. built, err := sc.Build()
  130. if err != nil {
  131. t.Fatalf("the core refuses the stream: %v", err)
  132. }
  133. mss, err := internet.ToMemoryStreamConfig(built)
  134. if err != nil {
  135. t.Fatalf("memory stream: %v", err)
  136. }
  137. port := listener.LocalAddr().(*net.UDPAddr).Port
  138. conn, err := mss.FinalMask.DialUDP(context.Background(), xnet.UDPDestination(xnet.LocalHostIP, xnet.Port(port)))
  139. if err != nil {
  140. t.Fatalf("the core cannot dial through the finalmask: %v", err)
  141. }
  142. _ = conn.Close()
  143. }
  144. // A client dials through one hopper and the core takes it only last in udp, so the JSON
  145. // subscription keeps the most specific hop range (host, then inbound, then global) at the end.
  146. func TestSubJsonServiceKeepsOneTrailingUDPHopMask(t *testing.T) {
  147. const hop = `{"type":"udphop","settings":{"mode":"intervalRemote","remotePorts":"%s","interval":"5-10"}}`
  148. const salamander = `{"type":"salamander","settings":{"password":"host-pass"}}`
  149. const inboundHop = `"finalmask":{"quicParams":{"udpHop":{"ports":"20000-30000","interval":"5-10"}}},`
  150. tests := []struct {
  151. name, inboundMask, hostMask, global, wantPorts string
  152. }{
  153. {
  154. "a host hop overrides the inbound and the global one", inboundHop,
  155. `{"udp":[` + salamander + `,` + fmt.Sprintf(hop, "40000-41000") + `]}`, fmt.Sprintf(hop, "30000-31000"), "40000-41000",
  156. },
  157. {
  158. "the inbound hop overrides the global one", inboundHop,
  159. `{"udp":[` + salamander + `]}`, fmt.Sprintf(hop, "30000-31000"), "20000-30000",
  160. },
  161. {
  162. "the global hop stays last behind host masks", ``,
  163. `{"udp":[` + salamander + `]}`, fmt.Sprintf(hop, "30000-31000"), "30000-31000",
  164. },
  165. }
  166. for _, tc := range tests {
  167. t.Run(tc.name, func(t *testing.T) {
  168. inbound := &model.Inbound{
  169. Listen: "203.0.113.10", Port: 443, Protocol: model.Hysteria, Remark: "hy",
  170. Settings: `{"version":2,"clients":[{"email":"[email protected]","auth":"a"}]}`,
  171. StreamSettings: `{"network":"hysteria","security":"tls","hysteriaSettings":{"version":2},
  172. "tlsSettings":{"serverName":"hy.example.test","alpn":["h3"]},` + tc.inboundMask + `
  173. "externalProxy":[{"forceTls":"same","dest":"a.example.test","port":443,"remark":"a",
  174. "finalMask":` + strconv.Quote(tc.hostMask) + `}]}`,
  175. }
  176. client := model.Client{Email: "[email protected]", Auth: "a"}
  177. global := `{"udp":[` + tc.global + `]}`
  178. configs := NewSubJsonService("", "", global, "", nil).getConfig(&SubService{address: "sub.example.com"}, inbound, client, "sub.example.com")
  179. if len(configs) != 1 {
  180. t.Fatalf("got %d configs, want one", len(configs))
  181. }
  182. var config struct {
  183. Outbounds []struct {
  184. StreamSettings map[string]any `json:"streamSettings"`
  185. } `json:"outbounds"`
  186. }
  187. if err := json.Unmarshal(configs[0], &config); err != nil {
  188. t.Fatalf("decode config: %v", err)
  189. }
  190. stream := config.Outbounds[0].StreamSettings
  191. finalmask, _ := stream["finalmask"].(map[string]any)
  192. masks, _ := finalmask["udp"].([]any)
  193. var hops []string
  194. for _, entry := range masks {
  195. mask, _ := entry.(map[string]any)
  196. if mask["type"] == "udphop" {
  197. settings, _ := mask["settings"].(map[string]any)
  198. hops = append(hops, fmt.Sprint(settings["remotePorts"]))
  199. }
  200. }
  201. last, _ := masks[len(masks)-1].(map[string]any)
  202. if len(hops) != 1 || hops[0] != tc.wantPorts || last["type"] != "udphop" {
  203. got, _ := json.Marshal(finalmask)
  204. t.Fatalf("client finalmask = %s, want one trailing udphop on %s", got, tc.wantPorts)
  205. }
  206. coreDialsUDP(t, stream)
  207. })
  208. }
  209. }
  210. // Every endpoint's config starts from the same parsed inbound finalmask; a host whose own
  211. // masks are merged in first must not use up the hop range the endpoints after it need.
  212. func TestSubJsonServiceKeepsUDPHopMaskOnEveryEndpoint(t *testing.T) {
  213. inbound := &model.Inbound{
  214. Listen: "203.0.113.10", Port: 443, Protocol: model.Hysteria, Remark: "hy",
  215. Settings: `{"version":2,"clients":[{"email":"[email protected]","auth":"a"}]}`,
  216. StreamSettings: `{"network":"hysteria","security":"tls",
  217. "hysteriaSettings":{"version":2},
  218. "tlsSettings":{"serverName":"hy.example.test","alpn":["h3"]},
  219. "finalmask":{"quicParams":{"udpHop":{"ports":"20000-30000","interval":"5-10"}}},
  220. "externalProxy":[
  221. {"forceTls":"same","dest":"a.example.test","port":443,"remark":"a",
  222. "finalMask":"{\"udp\":[{\"type\":\"salamander\",\"settings\":{\"password\":\"p\"}}]}"},
  223. {"forceTls":"same","dest":"b.example.test","port":443,"remark":"b"}]}`,
  224. }
  225. client := model.Client{Email: "[email protected]", Auth: "a"}
  226. configs := NewSubJsonService("", "", "", "", nil).getConfig(&SubService{address: "sub.example.com"}, inbound, client, "sub.example.com")
  227. if len(configs) != 2 {
  228. t.Fatalf("got %d configs, want one per endpoint", len(configs))
  229. }
  230. const hop = `{"settings":{"interval":"5-10","mode":"intervalRemote","remotePorts":"20000-30000"},"type":"udphop"}`
  231. wants := []string{
  232. `{"udp":[{"settings":{"password":"p"},"type":"salamander"},` + hop + `]}`,
  233. `{"udp":[` + hop + `]}`,
  234. }
  235. for i, want := range wants {
  236. var config struct {
  237. Outbounds []struct {
  238. StreamSettings map[string]any `json:"streamSettings"`
  239. } `json:"outbounds"`
  240. }
  241. if err := json.Unmarshal(configs[i], &config); err != nil {
  242. t.Fatalf("decode config %d: %v", i, err)
  243. }
  244. got, _ := json.Marshal(config.Outbounds[0].StreamSettings["finalmask"])
  245. if string(got) != want {
  246. t.Fatalf("endpoint %d finalmask\n got: %s\nwant: %s", i, got, want)
  247. }
  248. }
  249. }