inbound_amneziawg_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. package service
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "strings"
  7. "testing"
  8. "github.com/op/go-logging"
  9. "github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
  10. "github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  13. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  14. )
  15. func TestCheckForwardedPortsConflict_EmptySpecNoConflict(t *testing.T) {
  16. setupConflictDB(t)
  17. svc := &InboundService{}
  18. ctx, err := svc.loadPortConflictContext(database.GetDB())
  19. if err != nil {
  20. t.Fatalf("loadPortConflictContext: %v", err)
  21. }
  22. if hit := svc.checkForwardedPortsConflict(ctx, ""); hit != "" {
  23. t.Fatalf("an empty spec must never conflict; got hit=%q", hit)
  24. }
  25. }
  26. func TestCheckForwardedPortsConflict_CollidesWithPanelPort(t *testing.T) {
  27. setupConflictDB(t)
  28. svc := &InboundService{}
  29. ctx, err := svc.loadPortConflictContext(database.GetDB())
  30. if err != nil {
  31. t.Fatalf("loadPortConflictContext: %v", err)
  32. }
  33. // getString falls back to defaultValueMap's "webPort": "2053" on a fresh
  34. // DB with no explicit setting row.
  35. hit := svc.checkForwardedPortsConflict(ctx, "2053")
  36. if !strings.Contains(hit, "panel") {
  37. t.Fatalf("expected a collision naming the panel's own port, got %q", hit)
  38. }
  39. }
  40. func TestCheckForwardedPortsConflict_CollidesWithEnabledInboundPort(t *testing.T) {
  41. setupConflictDB(t)
  42. seedInboundConflict(t, "vless-8080", "0.0.0.0", 8080, model.VLESS, `{"network":"tcp"}`, `{}`)
  43. svc := &InboundService{}
  44. ctx, err := svc.loadPortConflictContext(database.GetDB())
  45. if err != nil {
  46. t.Fatalf("loadPortConflictContext: %v", err)
  47. }
  48. hit := svc.checkForwardedPortsConflict(ctx, "8075-8085")
  49. if !strings.Contains(hit, "vless-8080") {
  50. t.Fatalf("expected a collision naming the colliding inbound, got %q", hit)
  51. }
  52. }
  53. func TestCheckForwardedPortsConflict_IgnoresDisabledInboundPort(t *testing.T) {
  54. setupConflictDB(t)
  55. disabled := &model.Inbound{Tag: "vless-8080-off", Enable: false, Listen: "0.0.0.0", Port: 8080, Protocol: model.VLESS, StreamSettings: `{"network":"tcp"}`}
  56. if err := database.GetDB().Create(disabled).Error; err != nil {
  57. t.Fatalf("seed disabled inbound: %v", err)
  58. }
  59. svc := &InboundService{}
  60. ctx, err := svc.loadPortConflictContext(database.GetDB())
  61. if err != nil {
  62. t.Fatalf("loadPortConflictContext: %v", err)
  63. }
  64. if hit := svc.checkForwardedPortsConflict(ctx, "8080"); hit != "" {
  65. t.Fatalf("a disabled inbound's port must not be reserved; got hit=%q", hit)
  66. }
  67. }
  68. func TestCheckForwardedPortsConflict_NoCollisionWhenPortsDontOverlap(t *testing.T) {
  69. setupConflictDB(t)
  70. seedInboundConflict(t, "vless-8080", "0.0.0.0", 8080, model.VLESS, `{"network":"tcp"}`, `{}`)
  71. svc := &InboundService{}
  72. ctx, err := svc.loadPortConflictContext(database.GetDB())
  73. if err != nil {
  74. t.Fatalf("loadPortConflictContext: %v", err)
  75. }
  76. if hit := svc.checkForwardedPortsConflict(ctx, "9075-9085"); hit != "" {
  77. t.Fatalf("unrelated ports must not conflict; got hit=%q", hit)
  78. }
  79. }
  80. // A port-forward spec matching a port used only by an inbound hosted on a
  81. // DIFFERENT node must not conflict: that inbound's DNAT/listen socket lives
  82. // on the node's own host, never on this panel's, so there is nothing here
  83. // for the forwarded port to actually collide with. Mirrors
  84. // TestCheckPortConflict_NodeScope's own reasoning for the general port-
  85. // conflict check.
  86. func TestCheckForwardedPortsConflict_IgnoresPortOnDifferentNode(t *testing.T) {
  87. setupConflictDB(t)
  88. seedInboundConflictNode(t, "node1-8080", "0.0.0.0", 8080, model.VLESS, `{"network":"tcp"}`, `{}`, new(1))
  89. svc := &InboundService{}
  90. ctx, err := svc.loadPortConflictContext(database.GetDB())
  91. if err != nil {
  92. t.Fatalf("loadPortConflictContext: %v", err)
  93. }
  94. if hit := svc.checkForwardedPortsConflict(ctx, "8080"); hit != "" {
  95. t.Fatalf("a port used only on a different node must not conflict; got hit=%q", hit)
  96. }
  97. }
  98. // inboundAmneziaWGServer is pure (no DB), so it needs neither setupConflictDB
  99. // nor CGO/sqlite -- it can run in any Go environment.
  100. func TestInboundAmneziaWGServer_RedactsPrivateKey(t *testing.T) {
  101. settings := `{"server":{"privateKey":"super-secret","publicKey":"pub","mtu":1420,"headerProtectionKey":"MCPfRGcDGotJ6TcnIdDqsemj2cMIiGHnPUHM5ivXN18="},"clients":[]}`
  102. got := inboundAmneziaWGServer(string(model.AmneziaWG), settings)
  103. if got == nil {
  104. t.Fatal("expected a non-nil server block")
  105. }
  106. if got.PrivateKey != "" {
  107. t.Fatalf("PrivateKey must be redacted, got %q", got.PrivateKey)
  108. }
  109. if got.PublicKey != "pub" || got.MTU != 1420 {
  110. t.Fatalf("non-secret fields must still come through unchanged, got %+v", got)
  111. }
  112. // Unlike the private key, the header-protection key is shared with every
  113. // client config, so the clients page must receive it.
  114. if got.HeaderProtectionKey != "MCPfRGcDGotJ6TcnIdDqsemj2cMIiGHnPUHM5ivXN18=" {
  115. t.Fatalf("HeaderProtectionKey must NOT be redacted, got %q", got.HeaderProtectionKey)
  116. }
  117. }
  118. func TestNormalizeAmneziaWGSettings_GeneratesFull31Set(t *testing.T) {
  119. setupConflictDB(t)
  120. svc := &InboundService{}
  121. inbound := &model.Inbound{Protocol: model.AmneziaWG, Port: 51820, Settings: ""}
  122. if err := svc.normalizeAmneziaWGSettings(inbound); err != nil {
  123. t.Fatalf("normalize empty settings: %v", err)
  124. }
  125. var parsed amneziawg.InboundSettings
  126. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed.Server == nil {
  127. t.Fatalf("normalized settings must carry a server block (err=%v): %s", err, inbound.Settings)
  128. }
  129. srv := parsed.Server
  130. key, err := base64.StdEncoding.DecodeString(srv.HeaderProtectionKey)
  131. if err != nil || len(key) != 32 {
  132. t.Fatalf("headerProtectionKey = %q, must be base64 of 32 bytes (err=%v)", srv.HeaderProtectionKey, err)
  133. }
  134. for field, v := range map[string]string{
  135. "contentPaddingAddition": srv.ContentPaddingAddition,
  136. "rekeyAfterTime": srv.RekeyAfterTime,
  137. "rekeyTimeout": srv.RekeyTimeout,
  138. "rejectAfterTime": srv.RejectAfterTime,
  139. "keepaliveTimeout": srv.KeepaliveTimeout,
  140. "maxHandshakeAttempts": srv.MaxHandshakeAttempts,
  141. "i1": srv.I1,
  142. } {
  143. if v == "" {
  144. t.Errorf("fresh server block must fill %s", field)
  145. }
  146. }
  147. if !srv.RandomTrailers || !srv.DisableCookies {
  148. t.Errorf("fresh server block defaults RandomTrailers/DisableCookies on, got %v/%v", srv.RandomTrailers, srv.DisableCookies)
  149. }
  150. if srv.I2 != "" || srv.I3 != "" || srv.I4 != "" || srv.I5 != "" {
  151. t.Errorf("generated sets must leave I2-I5 empty, got %q/%q/%q/%q", srv.I2, srv.I3, srv.I4, srv.I5)
  152. }
  153. }
  154. func TestNormalizeAmneziaWGSettings_RejectsBad31Values(t *testing.T) {
  155. setupConflictDB(t)
  156. svc := &InboundService{}
  157. cases := []struct {
  158. name string
  159. snippet string
  160. }{
  161. {"bad headerProtectionKey", `"headerProtectionKey":"short"`},
  162. {"zero rekeyTimeout", `"rekeyTimeout":"0"`},
  163. {"rekey overlapping reject", `"rekeyAfterTime":"100-200","rejectAfterTime":"150-300"`},
  164. {"control chars in i2", `"i2":"<r 64>\nPostUp = evil"`},
  165. {"line-wrapped headerProtectionKey", `"headerProtectionKey":"MCPfRGcDGotJ6Tcn\r\nIdDqsemj2cMIiGHnPUHM5ivXN18="`},
  166. }
  167. for _, c := range cases {
  168. inbound := &model.Inbound{
  169. Protocol: model.AmneziaWG,
  170. Port: 51820,
  171. Settings: `{"server":{"privateKey":"x","publicKey":"y","subnetIp":"10.8.1.0","subnetCidr":24,` + c.snippet + `},"clients":[]}`,
  172. }
  173. if err := svc.normalizeAmneziaWGSettings(inbound); err == nil {
  174. t.Errorf("%s must be rejected", c.name)
  175. }
  176. }
  177. }
  178. func TestNormalizeAmneziaWGSettings_CanonicalizesRangeValues(t *testing.T) {
  179. setupConflictDB(t)
  180. svc := &InboundService{}
  181. inbound := &model.Inbound{
  182. Protocol: model.AmneziaWG,
  183. Port: 51820,
  184. Settings: `{"server":{"privateKey":"x","publicKey":"y","subnetIp":"10.8.1.0","subnetCidr":24,` +
  185. `"rekeyAfterTime":"110 - 140","rejectAfterTime":"190-250","keepaliveTimeout":" "},"clients":[]}`,
  186. }
  187. if err := svc.normalizeAmneziaWGSettings(inbound); err != nil {
  188. t.Fatalf("normalize: %v", err)
  189. }
  190. var parsed amneziawg.InboundSettings
  191. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed.Server == nil {
  192. t.Fatalf("re-parse normalized settings (err=%v): %s", err, inbound.Settings)
  193. }
  194. if parsed.Server.RekeyAfterTime != "110-140" {
  195. t.Errorf("rekeyAfterTime = %q, want canonical \"110-140\"", parsed.Server.RekeyAfterTime)
  196. }
  197. // A whitespace-only value must collapse to "feature off", not be stored
  198. // as a value the server emitter renders into an invalid blank line.
  199. if parsed.Server.KeepaliveTimeout != "" {
  200. t.Errorf("keepaliveTimeout = %q, want collapsed to empty", parsed.Server.KeepaliveTimeout)
  201. }
  202. }
  203. func TestInboundAmneziaWGServer_NonAmneziaWGReturnsNil(t *testing.T) {
  204. if got := inboundAmneziaWGServer(string(model.VLESS), `{"server":{"privateKey":"x"}}`); got != nil {
  205. t.Fatalf("a non-AmneziaWG protocol must return nil, got %+v", got)
  206. }
  207. }
  208. func TestInboundAmneziaWGServer_MissingServerBlockReturnsNil(t *testing.T) {
  209. if got := inboundAmneziaWGServer(string(model.AmneziaWG), `{"clients":[]}`); got != nil {
  210. t.Fatalf("settings with no server block must return nil, got %+v", got)
  211. }
  212. }
  213. // A newline inside a client's allowedIPs used to reach the rendered .conf,
  214. // where a following "[Interface]\nPostUp = ..." runs as root the moment
  215. // whoever applies that config (client app, or awg-quick directly) does so.
  216. func TestNormalizeAmneziaWGSettings_RejectsInjectedClientAllowedIPs(t *testing.T) {
  217. setupConflictDB(t)
  218. svc := &InboundService{}
  219. inbound := &model.Inbound{
  220. Protocol: model.AmneziaWG,
  221. Port: 51820,
  222. Settings: `{"server":{"privateKey":"x","publicKey":"y","subnetIp":"10.8.1.0","subnetCidr":24},` +
  223. `"clients":[{"email":"a@x","enable":true,"publicKey":"pk",` +
  224. `"allowedIPs":["10.8.1.2/32\n[Interface]\nPostUp = touch /tmp/pwned"]}]}`,
  225. }
  226. err := svc.normalizeAmneziaWGSettings(inbound)
  227. if err == nil {
  228. t.Fatalf("an allowedIPs entry carrying a config-injection payload must be rejected; settings became:\n%s", inbound.Settings)
  229. }
  230. if !strings.Contains(err.Error(), "allowedIPs") {
  231. t.Errorf("error should name the offending field, got %q", err)
  232. }
  233. }
  234. func TestNormalizeAmneziaWGSettings_CanonicalizesClientAllowedIPs(t *testing.T) {
  235. setupConflictDB(t)
  236. svc := &InboundService{}
  237. inbound := &model.Inbound{
  238. Protocol: model.AmneziaWG,
  239. Port: 51820,
  240. Settings: `{"server":{"privateKey":"x","publicKey":"y","subnetIp":"10.8.1.0","subnetCidr":24},` +
  241. `"clients":[{"email":"a@x","enable":true,"publicKey":"pk","allowedIPs":[" 10.8.1.2 "]}]}`,
  242. }
  243. if err := svc.normalizeAmneziaWGSettings(inbound); err != nil {
  244. t.Fatalf("normalize: %v", err)
  245. }
  246. var parsed amneziawg.InboundSettings
  247. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  248. t.Fatalf("re-parse normalized settings: %v", err)
  249. }
  250. if len(parsed.Clients) != 1 || len(parsed.Clients[0].AllowedIPs) != 1 || parsed.Clients[0].AllowedIPs[0] != "10.8.1.2/32" {
  251. t.Fatalf("allowedIPs = %v, want [\"10.8.1.2/32\"]", parsed.Clients)
  252. }
  253. }
  254. func TestGetAmneziaWGLogs_ClampsCountAndFiltersEvents(t *testing.T) {
  255. logger.InitLogger(logging.DEBUG)
  256. logger.Info("amneziawg: started interface awg1 for inbound 1")
  257. logger.Info("xray: unrelated line that must never show up here")
  258. logger.Warning("amneziawgnet: reconcile failed for inbound 2: handshake timeout")
  259. svc := &ServerService{}
  260. logs := svc.GetAmneziaWGLogs("not-a-number", "")
  261. if logs == nil {
  262. t.Fatal("GetAmneziaWGLogs must never return nil")
  263. }
  264. for _, line := range logs.Events {
  265. if !strings.Contains(strings.ToLower(line), "amneziawg") {
  266. t.Fatalf("non-AmneziaWG line leaked into the event list: %q", line)
  267. }
  268. }
  269. if len(logs.Events) < 2 {
  270. t.Fatalf("both AmneziaWG lines should be present, got %v", logs.Events)
  271. }
  272. // count caps the event list, so an operator asking for 1 gets 1.
  273. if one := svc.GetAmneziaWGLogs("1", ""); len(one.Events) != 1 {
  274. t.Fatalf("count=1 must cap the event list, got %d", len(one.Events))
  275. }
  276. // filter narrows further, case-insensitively.
  277. filtered := svc.GetAmneziaWGLogs("100", "RECONCILE")
  278. if len(filtered.Events) != 1 || !strings.Contains(filtered.Events[0], "reconcile") {
  279. t.Fatalf("filter must narrow to the matching line, got %v", filtered.Events)
  280. }
  281. }
  282. func TestCheckForwardedPortsConflict_RejectsSpecOverCap(t *testing.T) {
  283. setupConflictDB(t)
  284. svc := &InboundService{}
  285. ctx, err := svc.loadPortConflictContext(database.GetDB())
  286. if err != nil {
  287. t.Fatalf("loadPortConflictContext: %v", err)
  288. }
  289. spec := fmt.Sprintf("20000-%d", 20000+amneziawg.MaxForwardedPorts)
  290. hit := svc.checkForwardedPortsConflict(ctx, spec)
  291. if !strings.Contains(hit, fmt.Sprintf("%d", amneziawg.MaxForwardedPorts)) {
  292. t.Fatalf("expected a collision naming the %d-port cap, got %q", amneziawg.MaxForwardedPorts, hit)
  293. }
  294. }
  295. // A spec covering exactly MaxForwardedPorts ports is AT the cap, not over
  296. // it, and must be accepted -- ExpandForwardedPorts truncates there by
  297. // design, so a naive len(...) >= cap comparison can't tell the two apart.
  298. func TestCheckForwardedPortsConflict_AcceptsSpecExactlyAtCap(t *testing.T) {
  299. setupConflictDB(t)
  300. svc := &InboundService{}
  301. ctx, err := svc.loadPortConflictContext(database.GetDB())
  302. if err != nil {
  303. t.Fatalf("loadPortConflictContext: %v", err)
  304. }
  305. spec := fmt.Sprintf("20000-%d", 20000+amneziawg.MaxForwardedPorts-1)
  306. if hit := svc.checkForwardedPortsConflict(ctx, spec); hit != "" {
  307. t.Fatalf("a spec covering exactly %d ports must be accepted, got collision %q", amneziawg.MaxForwardedPorts, hit)
  308. }
  309. }
  310. // The SOCKS5 relay port an enabled AmneziaWG inbound gets (SOCKSPortForInbound)
  311. // is a phantom, non-DB-row port -- ctx.inbounds alone can't see it, so
  312. // checkForwardedPortsConflict must check it explicitly.
  313. func TestCheckForwardedPortsConflict_CollidesWithAmneziawgnetSocksPort(t *testing.T) {
  314. setupConflictDB(t)
  315. seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, `{}`)
  316. var awgInbound model.Inbound
  317. if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
  318. t.Fatalf("read seeded row: %v", err)
  319. }
  320. relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
  321. svc := &InboundService{}
  322. ctx, err := svc.loadPortConflictContext(database.GetDB())
  323. if err != nil {
  324. t.Fatalf("loadPortConflictContext: %v", err)
  325. }
  326. hit := svc.checkForwardedPortsConflict(ctx, fmt.Sprintf("%d", relayPort))
  327. if !strings.Contains(hit, "SOCKS5") {
  328. t.Fatalf("expected a collision naming the AmneziaWG inbound's SOCKS5 relay port, got %q", hit)
  329. }
  330. }
  331. // A cleared DNS field is meaningful (no DNS line in client configs) and must
  332. // survive the save round-trip instead of resurrecting the frontend defaults.
  333. func TestNormalizeAmneziaWGSettingsKeepsClearedDNS(t *testing.T) {
  334. setupConflictDB(t)
  335. server, err := defaultAmneziaWGServer()
  336. if err != nil {
  337. t.Fatalf("defaultAmneziaWGServer: %v", err)
  338. }
  339. server.PrimaryDNS = ""
  340. server.SecondaryDNS = ""
  341. bs, err := json.Marshal(amneziawg.InboundSettings{Server: server, Clients: []model.Client{}})
  342. if err != nil {
  343. t.Fatalf("marshal settings: %v", err)
  344. }
  345. inbound := &model.Inbound{Protocol: model.AmneziaWG, Settings: string(bs)}
  346. if err := (&InboundService{}).normalizeAmneziaWGSettings(inbound); err != nil {
  347. t.Fatalf("normalizeAmneziaWGSettings: %v", err)
  348. }
  349. for _, key := range []string{`"primaryDns"`, `"secondaryDns"`} {
  350. if !strings.Contains(inbound.Settings, key) {
  351. t.Fatalf("cleared %s dropped from persisted settings:\n%s", key, inbound.Settings)
  352. }
  353. }
  354. }