client_wireguard_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. package service
  2. import (
  3. "fmt"
  4. "strings"
  5. "testing"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  7. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  8. )
  9. func TestAllocateWireguardAddress(t *testing.T) {
  10. tests := []struct {
  11. name string
  12. used []string
  13. base string
  14. want string
  15. err bool
  16. }{
  17. {name: "empty starts at .2", used: nil, base: "10.0.0.0/24", want: "10.0.0.2/32"},
  18. {name: "skips used", used: []string{"10.0.0.2/32"}, base: "10.0.0.0/24", want: "10.0.0.3/32"},
  19. {name: "fills gap", used: []string{"10.0.0.3/32", "10.0.0.4/32"}, base: "10.0.0.0/24", want: "10.0.0.2/32"},
  20. {name: "ignores catch-all", used: []string{"0.0.0.0/0", "::/0"}, base: "10.0.0.0/24", want: "10.0.0.2/32"},
  21. {name: "default base when empty", used: nil, base: "", want: "10.0.0.2/32"},
  22. {name: "full ipv4 scope widens instead of failing", used: []string{"10.9.0.2/32", "10.9.0.3/32"}, base: "10.9.0.0/30", want: "10.9.0.4/32"},
  23. {name: "exhausted ipv6 scope errors", used: []string{"fd00::2/128", "fd00::3/128"}, base: "fd00::/126", err: true},
  24. }
  25. for _, tt := range tests {
  26. t.Run(tt.name, func(t *testing.T) {
  27. got, err := allocateWireguardAddress(tt.used, tt.base, true)
  28. if tt.err {
  29. if err == nil {
  30. t.Fatalf("expected error, got %q", got)
  31. }
  32. return
  33. }
  34. if err != nil {
  35. t.Fatalf("unexpected error: %v", err)
  36. }
  37. if got != tt.want {
  38. t.Fatalf("got %q, want %q", got, tt.want)
  39. }
  40. })
  41. }
  42. }
  43. func TestDefaultWireguardClientsGeneratesKeypair(t *testing.T) {
  44. clients := []model.Client{{Email: "a@wg"}}
  45. ifaces := []any{map[string]any{"email": "a@wg"}}
  46. if err := defaultWireguardClients("", nil, clients, ifaces, nil); err != nil {
  47. t.Fatalf("defaultWireguardClients: %v", err)
  48. }
  49. c := clients[0]
  50. if c.PrivateKey == "" || c.PublicKey == "" {
  51. t.Fatalf("keypair not generated: priv=%q pub=%q", c.PrivateKey, c.PublicKey)
  52. }
  53. if len(c.AllowedIPs) != 1 || c.AllowedIPs[0] != "10.0.0.2/32" {
  54. t.Fatalf("allowedIPs not allocated: %v", c.AllowedIPs)
  55. }
  56. m := ifaces[0].(map[string]any)
  57. if m["privateKey"] != c.PrivateKey || m["publicKey"] != c.PublicKey {
  58. t.Fatalf("interface map not updated: %v", m)
  59. }
  60. }
  61. func TestDefaultWireguardClientsDerivesPublicKey(t *testing.T) {
  62. priv, _, err := wgutil.GenerateWireguardKeypair()
  63. if err != nil {
  64. t.Fatal(err)
  65. }
  66. wantPub, err := wgutil.PublicKeyFromPrivate(priv)
  67. if err != nil {
  68. t.Fatal(err)
  69. }
  70. clients := []model.Client{{Email: "b@wg", PrivateKey: priv}}
  71. ifaces := []any{map[string]any{"email": "b@wg"}}
  72. if err := defaultWireguardClients("", nil, clients, ifaces, nil); err != nil {
  73. t.Fatalf("defaultWireguardClients: %v", err)
  74. }
  75. if clients[0].PublicKey != wantPub {
  76. t.Fatalf("derived public key = %q, want %q", clients[0].PublicKey, wantPub)
  77. }
  78. }
  79. func TestDefaultWireguardClientsPreservesProvided(t *testing.T) {
  80. clients := []model.Client{{
  81. Email: "c@wg",
  82. PrivateKey: "keep-priv",
  83. PublicKey: "keep-pub",
  84. AllowedIPs: []string{"10.0.0.50/32"},
  85. }}
  86. ifaces := []any{map[string]any{"email": "c@wg"}}
  87. if err := defaultWireguardClients("", nil, clients, ifaces, nil); err != nil {
  88. t.Fatalf("defaultWireguardClients: %v", err)
  89. }
  90. if clients[0].PrivateKey != "keep-priv" || clients[0].PublicKey != "keep-pub" {
  91. t.Fatalf("provided keys were rotated: %+v", clients[0])
  92. }
  93. if clients[0].AllowedIPs[0] != "10.0.0.50/32" {
  94. t.Fatalf("provided allowedIPs changed: %v", clients[0].AllowedIPs)
  95. }
  96. }
  97. func TestWireguardAllocationBase(t *testing.T) {
  98. tests := []struct {
  99. name string
  100. used []string
  101. fallback string
  102. want string
  103. }{
  104. {name: "no peers uses fallback", used: nil, fallback: "10.0.0.0/24", want: "10.0.0.0/24"},
  105. {name: "derives subnet from existing peer", used: []string{"172.16.0.2/32"}, fallback: "10.0.0.0/24", want: "172.16.0.0/24"},
  106. {name: "skips catch-all and ipv6", used: []string{"0.0.0.0/0", "::/0", "fd00::2/128", "192.168.5.7/32"}, fallback: "10.0.0.0/24", want: "192.168.5.0/24"},
  107. }
  108. for _, tt := range tests {
  109. t.Run(tt.name, func(t *testing.T) {
  110. if got := wireguardAllocationBase(tt.used, tt.fallback); got != tt.want {
  111. t.Fatalf("got %q, want %q", got, tt.want)
  112. }
  113. })
  114. }
  115. }
  116. func TestDefaultWireguardClientsHonorsExistingSubnet(t *testing.T) {
  117. existing := []model.Client{{Email: "old@wg", AllowedIPs: []string{"172.16.0.2/32"}}}
  118. clients := []model.Client{{Email: "new@wg"}}
  119. ifaces := []any{map[string]any{"email": "new@wg"}}
  120. if err := defaultWireguardClients("", existing, clients, ifaces, nil); err != nil {
  121. t.Fatalf("defaultWireguardClients: %v", err)
  122. }
  123. if got := clients[0].AllowedIPs[0]; got != "172.16.0.3/32" {
  124. t.Fatalf("new client address = %q, want 172.16.0.3/32 in existing subnet", got)
  125. }
  126. }
  127. func TestAllocateWireguardAddressWidensPastFullSlash24(t *testing.T) {
  128. used := make([]string, 0, 254)
  129. for i := 2; i <= 255; i++ {
  130. used = append(used, fmt.Sprintf("10.0.0.%d/32", i))
  131. }
  132. got, err := allocateWireguardAddress(used, "10.0.0.0/24", true)
  133. if err != nil {
  134. t.Fatalf("allocate with a full /24: %v", err)
  135. }
  136. if got != "10.0.1.0/32" {
  137. t.Fatalf("address after a full /24 = %q, want 10.0.1.0/32", got)
  138. }
  139. used = append(used, got)
  140. next, err := allocateWireguardAddress(used, "10.0.0.0/24", true)
  141. if err != nil {
  142. t.Fatalf("allocate after widening: %v", err)
  143. }
  144. if next != "10.0.1.1/32" {
  145. t.Fatalf("second widened address = %q, want 10.0.1.1/32", next)
  146. }
  147. }
  148. func TestAllocateWireguardAddressFillsItsOwnSlash24First(t *testing.T) {
  149. got, err := allocateWireguardAddress([]string{"172.16.0.2/32"}, "172.16.0.0/24", true)
  150. if err != nil {
  151. t.Fatalf("allocateWireguardAddress: %v", err)
  152. }
  153. if got != "172.16.0.3/32" {
  154. t.Fatalf("address = %q, want 172.16.0.3/32 — the inbound's own /24 comes first", got)
  155. }
  156. }
  157. func TestAllocateWireguardAddressNoWideningFailsWhenPoolExhausted(t *testing.T) {
  158. used := make([]string, 0, 254)
  159. for i := 2; i <= 255; i++ {
  160. used = append(used, fmt.Sprintf("10.0.0.%d/32", i))
  161. }
  162. // allowWidening=false: AmneziaWG's own call. A full /24 must fail loudly
  163. // instead of handing out an address from the containing /16 that the
  164. // kernel interface's own Address never routes (PR #6105 Finding 12).
  165. if _, err := allocateWireguardAddress(used, "10.0.0.0/24", false); err == nil {
  166. t.Fatal("a full /24 with widening disabled must fail, not widen")
  167. }
  168. }
  169. func TestDefaultWireguardClientsAllocatesDistinctIPs(t *testing.T) {
  170. clients := []model.Client{{Email: "x@wg"}, {Email: "y@wg"}}
  171. ifaces := []any{map[string]any{"email": "x@wg"}, map[string]any{"email": "y@wg"}}
  172. if err := defaultWireguardClients("", nil, clients, ifaces, nil); err != nil {
  173. t.Fatalf("defaultWireguardClients: %v", err)
  174. }
  175. if clients[0].AllowedIPs[0] == clients[1].AllowedIPs[0] {
  176. t.Fatalf("two clients got the same address: %v", clients[0].AllowedIPs)
  177. }
  178. }
  179. func TestNormalizeWireguardAllowedIPs(t *testing.T) {
  180. tests := []struct {
  181. name string
  182. in []string
  183. want []string
  184. err bool
  185. }{
  186. {name: "cidr passes through", in: []string{"10.0.0.5/32"}, want: []string{"10.0.0.5/32"}},
  187. {name: "bare ipv4 becomes /32", in: []string{"10.0.0.5"}, want: []string{"10.0.0.5/32"}},
  188. {name: "bare ipv6 becomes /128", in: []string{"fd00::5"}, want: []string{"fd00::5/128"}},
  189. {name: "trims and drops empties", in: []string{" 10.0.0.5/32 ", "", " "}, want: []string{"10.0.0.5/32"}},
  190. {name: "dedupes", in: []string{"10.0.0.5/32", "10.0.0.5/32"}, want: []string{"10.0.0.5/32"}},
  191. {name: "routed subnet allowed", in: []string{"10.0.0.5/32", "192.168.1.0/24"}, want: []string{"10.0.0.5/32", "192.168.1.0/24"}},
  192. {name: "garbage rejected", in: []string{"not-an-ip"}, err: true},
  193. {name: "bad prefix rejected", in: []string{"10.0.0.5/99"}, err: true},
  194. }
  195. for _, tt := range tests {
  196. t.Run(tt.name, func(t *testing.T) {
  197. got, err := normalizeWireguardAllowedIPs(tt.in)
  198. if tt.err {
  199. if err == nil {
  200. t.Fatalf("expected error, got %v", got)
  201. }
  202. return
  203. }
  204. if err != nil {
  205. t.Fatalf("unexpected error: %v", err)
  206. }
  207. if len(got) != len(tt.want) {
  208. t.Fatalf("got %v, want %v", got, tt.want)
  209. }
  210. for i := range got {
  211. if got[i] != tt.want[i] {
  212. t.Fatalf("got %v, want %v", got, tt.want)
  213. }
  214. }
  215. })
  216. }
  217. }
  218. func TestDefaultWireguardClientsHonorsAndValidatesSuppliedAllowedIPs(t *testing.T) {
  219. existing := []model.Client{{Email: "old@wg", AllowedIPs: []string{"10.0.0.2/32"}}}
  220. clients := []model.Client{{Email: "c@wg", AllowedIPs: []string{"10.0.0.9"}}}
  221. ifaces := []any{map[string]any{"email": "c@wg"}}
  222. if err := defaultWireguardClients("", existing, clients, ifaces, nil); err != nil {
  223. t.Fatalf("defaultWireguardClients: %v", err)
  224. }
  225. if len(clients[0].AllowedIPs) != 1 || clients[0].AllowedIPs[0] != "10.0.0.9/32" {
  226. t.Fatalf("supplied allowedIPs not normalized: %v", clients[0].AllowedIPs)
  227. }
  228. dup := []model.Client{{Email: "d@wg", AllowedIPs: []string{"10.0.0.2/32"}}}
  229. err := defaultWireguardClients("", existing, dup, []any{map[string]any{"email": "d@wg"}}, nil)
  230. if err == nil {
  231. t.Fatal("duplicate allowedIPs across clients must be rejected")
  232. }
  233. bad := []model.Client{{Email: "e@wg", AllowedIPs: []string{"not-an-ip"}}}
  234. if err := defaultWireguardClients("", existing, bad, []any{map[string]any{"email": "e@wg"}}, nil); err == nil {
  235. t.Fatal("invalid allowedIPs entry must be rejected")
  236. }
  237. }
  238. // A duplicate manually-typed address is rejected even when the OTHER holder
  239. // lives on a completely different inbound (e.g. a WireGuard client and an
  240. // AmneziaWG peer given the same address by habit) -- this is the exact
  241. // real-world scenario that motivated crossInboundUsed: two inbounds sharing
  242. // a subnet must not be able to silently hand out or accept the same address.
  243. func TestDefaultWireguardClientsRejectsCrossInboundDuplicate(t *testing.T) {
  244. crossUsed := map[string]string{"10.8.1.21/32": "inbound 'awg' (#10)"}
  245. dup := []model.Client{{Email: "d@wg", AllowedIPs: []string{"10.8.1.21/32"}}}
  246. err := defaultWireguardClients("", nil, dup, []any{map[string]any{"email": "d@wg"}}, crossUsed)
  247. if err == nil {
  248. t.Fatal("allowedIPs already used on another inbound must be rejected")
  249. }
  250. if !strings.Contains(err.Error(), "inbound 'awg' (#10)") {
  251. t.Fatalf("error should name the other inbound holding the address, got: %v", err)
  252. }
  253. }
  254. // Auto-allocation (no AllowedIPs supplied) must also skip addresses already
  255. // claimed on another inbound, not just ones used on this one.
  256. func TestDefaultWireguardClientsAutoAllocateSkipsCrossInboundUsed(t *testing.T) {
  257. crossUsed := map[string]string{"10.0.0.2/32": "inbound 'other-wg' (#7)"}
  258. clients := []model.Client{{Email: "f@wg"}}
  259. ifaces := []any{map[string]any{"email": "f@wg"}}
  260. if err := defaultWireguardClients("", nil, clients, ifaces, crossUsed); err != nil {
  261. t.Fatalf("defaultWireguardClients: %v", err)
  262. }
  263. if clients[0].AllowedIPs[0] != "10.0.0.3/32" {
  264. t.Fatalf("auto-allocation should skip the cross-inbound-used .2 and pick .3, got %v", clients[0].AllowedIPs)
  265. }
  266. }
  267. // crossInboundUsed must never influence which subnet THIS inbound's own new
  268. // clients get allocated from -- only existing (this inbound's own clients)
  269. // may do that. Otherwise a brand-new WireGuard inbound on a panel that
  270. // already has an unrelated AmneziaWG inbound would infer the wrong base
  271. // subnet purely from the other inbound's addresses.
  272. func TestDefaultWireguardClientsCrossInboundUsedDoesNotSkewSubnetInference(t *testing.T) {
  273. crossUsed := map[string]string{"10.8.1.21/32": "inbound 'awg' (#10)"}
  274. clients := []model.Client{{Email: "g@wg"}}
  275. ifaces := []any{map[string]any{"email": "g@wg"}}
  276. if err := defaultWireguardClients("", nil, clients, ifaces, crossUsed); err != nil {
  277. t.Fatalf("defaultWireguardClients: %v", err)
  278. }
  279. if got := clients[0].AllowedIPs[0]; got != "10.0.0.2/32" {
  280. t.Fatalf("base subnet must stay the default 10.0.0.0/24, not be skewed by a cross-inbound address; got %v", got)
  281. }
  282. }
  283. func TestExplicitWireguardSubnetBase(t *testing.T) {
  284. tests := []struct {
  285. name string
  286. settingsJSON string
  287. want string
  288. }{
  289. {name: "unset settings", settingsJSON: `{"secretKey":"x"}`, want: ""},
  290. {name: "empty subnetIp", settingsJSON: `{"subnetIp":"","subnetCidr":24}`, want: ""},
  291. {name: "zero cidr", settingsJSON: `{"subnetIp":"10.8.1.0","subnetCidr":0}`, want: ""},
  292. {name: "invalid ip", settingsJSON: `{"subnetIp":"not-an-ip","subnetCidr":24}`, want: ""},
  293. {name: "invalid json", settingsJSON: `not json`, want: ""},
  294. {name: "configured subnet", settingsJSON: `{"subnetIp":"10.8.1.0","subnetCidr":24}`, want: "10.8.1.0/24"},
  295. }
  296. for _, tt := range tests {
  297. t.Run(tt.name, func(t *testing.T) {
  298. if got := explicitWireguardSubnetBase(tt.settingsJSON); got != tt.want {
  299. t.Fatalf("got %q, want %q", got, tt.want)
  300. }
  301. })
  302. }
  303. }
  304. // TestDefaultWireguardClientsPrefersExplicitSubnetOverInference is the
  305. // backend half of a user-requested feature: WireGuard previously had no
  306. // admin-configurable subnet at all, only an implicit one (inferred from
  307. // existing clients' own addresses, or a hardcoded 10.0.0.0/24 fallback when
  308. // none exist yet) -- unlike AmneziaWG, which has always had a real
  309. // server.subnetIp/subnetCidr field. An explicit subnetIp/subnetCidr in the
  310. // inbound's own settings must now win outright, even when existing clients
  311. // would otherwise suggest a different base via wireguardAllocationBase.
  312. func TestDefaultWireguardClientsPrefersExplicitSubnetOverInference(t *testing.T) {
  313. existing := []model.Client{{Email: "old@wg", AllowedIPs: []string{"172.16.0.2/32"}}}
  314. clients := []model.Client{{Email: "new@wg"}}
  315. ifaces := []any{map[string]any{"email": "new@wg"}}
  316. settingsJSON := `{"subnetIp":"10.8.1.0","subnetCidr":24}`
  317. if err := defaultWireguardClients(settingsJSON, existing, clients, ifaces, nil); err != nil {
  318. t.Fatalf("defaultWireguardClients: %v", err)
  319. }
  320. if got := clients[0].AllowedIPs[0]; got != "10.8.1.2/32" {
  321. t.Fatalf("explicit subnet must win over inference from existing clients (172.16.0.0/24); got %v", got)
  322. }
  323. }
  324. // TestDefaultWireguardClientsFallsBackWhenNoExplicitSubnet locks in the
  325. // backward-compat half of the same feature: an inbound saved before this
  326. // field existed (settingsJSON carries no subnetIp/subnetCidr at all) must
  327. // keep allocating exactly as it always has.
  328. func TestDefaultWireguardClientsFallsBackWhenNoExplicitSubnet(t *testing.T) {
  329. existing := []model.Client{{Email: "old@wg", AllowedIPs: []string{"172.16.0.2/32"}}}
  330. clients := []model.Client{{Email: "new@wg"}}
  331. ifaces := []any{map[string]any{"email": "new@wg"}}
  332. settingsJSON := `{"secretKey":"x","peers":[],"clients":[]}`
  333. if err := defaultWireguardClients(settingsJSON, existing, clients, ifaces, nil); err != nil {
  334. t.Fatalf("defaultWireguardClients: %v", err)
  335. }
  336. if got := clients[0].AllowedIPs[0]; got != "172.16.0.3/32" {
  337. t.Fatalf("with no explicit subnet, inference from existing clients must still apply; got %v", got)
  338. }
  339. }