inbound_amneziawg.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strings"
  7. "gorm.io/gorm"
  8. "github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
  9. "github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  12. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  13. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  14. )
  15. // DesiredAmneziaWGInstances derives the AmneziaWG interfaces this panel
  16. // should be running: one instance per enabled local AmneziaWG inbound,
  17. // serving only the peers of clients that are both enabled in the inbound
  18. // settings and not depletion-disabled in client_traffics. That is the same
  19. // effective peer set buildInboundForLocalRuntime pushes on interactive edits,
  20. // so the reconcile job and the push path agree on one fingerprint — see
  21. // DesiredMtprotoInstances, which this mirrors exactly.
  22. func (s *InboundService) DesiredAmneziaWGInstances() ([]amneziawg.Instance, error) {
  23. db := database.GetDB()
  24. var inbounds []*model.Inbound
  25. err := db.Model(model.Inbound{}).
  26. Where("protocol = ? AND enable = ? AND node_id IS NULL", model.AmneziaWG, true).
  27. Find(&inbounds).Error
  28. if err != nil {
  29. return nil, err
  30. }
  31. if len(inbounds) == 0 {
  32. return nil, nil
  33. }
  34. instances := make([]amneziawg.Instance, 0, len(inbounds))
  35. for _, ib := range inbounds {
  36. inst, ok := amneziawg.InstanceFromInbound(ib)
  37. if !ok {
  38. continue
  39. }
  40. instances = append(instances, inst)
  41. }
  42. emails := make([]string, 0)
  43. for _, inst := range instances {
  44. for _, e := range inst.Peers {
  45. emails = append(emails, e.Email)
  46. }
  47. }
  48. disabled, err := trafficDisabledEmails(db, emails)
  49. if err != nil {
  50. return nil, err
  51. }
  52. served := instances[:0]
  53. for _, inst := range instances {
  54. kept := make([]amneziawg.Peer, 0, len(inst.Peers))
  55. for _, e := range inst.Peers {
  56. if _, off := disabled[e.Email]; !off {
  57. kept = append(kept, e)
  58. }
  59. }
  60. inst.Peers = kept
  61. if len(kept) > 0 {
  62. served = append(served, inst)
  63. }
  64. }
  65. return served, nil
  66. }
  67. // applyLocalAmneziaWG pushes a single local AmneziaWG inbound's current peer
  68. // set to its interface right after a client edit commits, so an add,
  69. // removal, re-key or enable-toggle takes effect immediately instead of
  70. // waiting up to 10s for the reconcile job. It re-reads the inbound so it sees
  71. // the committed settings, filters depleted clients exactly like the
  72. // reconcile job, and is a no-op for node-owned or non-AmneziaWG inbounds.
  73. // Failures are logged and swallowed: the reconcile job is the backstop.
  74. // Mirrors applyLocalMtproto.
  75. func (s *InboundService) applyLocalAmneziaWG(inboundId int) {
  76. inbound, err := s.GetInbound(inboundId)
  77. if err != nil || inbound == nil || inbound.Protocol != model.AmneziaWG || inbound.NodeID != nil {
  78. return
  79. }
  80. rt, err := s.runtimeFor(inbound)
  81. if err != nil {
  82. return
  83. }
  84. payload := inbound
  85. if inbound.Enable {
  86. if built, bErr := s.buildInboundForLocalRuntime(database.GetDB(), inbound); bErr == nil {
  87. payload = built
  88. }
  89. }
  90. if err := rt.UpdateInbound(context.Background(), inbound, payload); err != nil {
  91. logger.Debugf("amneziawg: immediate apply failed for inbound %d: %v", inboundId, err)
  92. }
  93. }
  94. // defaultAmneziaWGServer builds a fresh server block: a random AmneziaWG 3.1
  95. // obfuscation set, the default tunnel subnet/DNS, and a freshly generated
  96. // keypair.
  97. func defaultAmneziaWGServer() (*amneziawg.ServerSettings, error) {
  98. obf := amneziawg.GenerateObfuscation31()
  99. server := &amneziawg.ServerSettings{
  100. SubnetIP: "10.8.1.0",
  101. SubnetCIDR: 24,
  102. PrimaryDNS: "8.8.8.8",
  103. SecondaryDNS: "8.8.4.4",
  104. Jc: obf.Jc,
  105. Jmin: obf.Jmin,
  106. Jmax: obf.Jmax,
  107. S1: obf.S1,
  108. S2: obf.S2,
  109. S3: obf.S3,
  110. S4: obf.S4,
  111. H1: obf.H1,
  112. H2: obf.H2,
  113. H3: obf.H3,
  114. H4: obf.H4,
  115. I1: obf.I1,
  116. HeaderProtectionKey: obf.HeaderProtectionKey,
  117. ContentPaddingAddition: obf.ContentPaddingAddition,
  118. RekeyAfterTime: obf.RekeyAfterTime,
  119. RekeyTimeout: obf.RekeyTimeout,
  120. RejectAfterTime: obf.RejectAfterTime,
  121. KeepaliveTimeout: obf.KeepaliveTimeout,
  122. MaxHandshakeAttempts: obf.MaxHandshakeAttempts,
  123. RandomTrailers: obf.RandomTrailers,
  124. DisableCookies: obf.DisableCookies,
  125. }
  126. if err := fillAmneziaWGServerKeys(server); err != nil {
  127. return nil, err
  128. }
  129. return server, nil
  130. }
  131. // fillAmneziaWGServerKeys generates a real WireGuard-compatible keypair for
  132. // the server block when one is missing.
  133. func fillAmneziaWGServerKeys(server *amneziawg.ServerSettings) error {
  134. priv, pub, err := wgutil.GenerateWireguardKeypair()
  135. if err != nil {
  136. return fmt.Errorf("amneziawg: generate server keypair: %w", err)
  137. }
  138. server.PrivateKey = priv
  139. server.PublicKey = pub
  140. return nil
  141. }
  142. // resolveAmneziaWGServerKeys settles the server keypair for a save. An omitted
  143. // key means "unchanged", never "mint a new one": rotating it silently
  144. // invalidates every client config already handed out.
  145. func resolveAmneziaWGServerKeys(server *amneziawg.ServerSettings, oldSettings string) error {
  146. if server.PrivateKey == "" {
  147. storedPriv, storedPub := storedAmneziaWGServerKeys(oldSettings)
  148. if storedPriv == "" {
  149. return fillAmneziaWGServerKeys(server)
  150. }
  151. server.PrivateKey, server.PublicKey = storedPriv, storedPub
  152. }
  153. if server.PublicKey == "" {
  154. pub, err := wgutil.PublicKeyFromPrivate(server.PrivateKey)
  155. if err != nil {
  156. return fmt.Errorf("amneziawg: derive server public key: %w", err)
  157. }
  158. server.PublicKey = pub
  159. }
  160. return nil
  161. }
  162. // storedAmneziaWGServerKeys returns the keypair already saved for this inbound.
  163. // oldSettings is empty on a first save, and need not be valid AmneziaWG JSON.
  164. func storedAmneziaWGServerKeys(oldSettings string) (priv, pub string) {
  165. if strings.TrimSpace(oldSettings) == "" {
  166. return "", ""
  167. }
  168. var prev amneziawg.InboundSettings
  169. if err := json.Unmarshal([]byte(oldSettings), &prev); err != nil || prev.Server == nil {
  170. return "", ""
  171. }
  172. return prev.Server.PrivateKey, prev.Server.PublicKey
  173. }
  174. // normalizeAmneziaWGSettings ensures an AmneziaWG inbound's settings have a
  175. // valid server block, generating one (fresh obfuscation params + keypair) on
  176. // first save and validating a manually-edited one so a bad entry can't bring
  177. // the interface down on the next apply. A no-op for every other protocol.
  178. func (s *InboundService) normalizeAmneziaWGSettings(inbound *model.Inbound, oldSettings string) error {
  179. if inbound.Protocol != model.AmneziaWG {
  180. return nil
  181. }
  182. trimmed := strings.TrimSpace(inbound.Settings)
  183. if trimmed == "" || trimmed == "null" || trimmed == "{}" {
  184. server, err := defaultAmneziaWGServer()
  185. if err != nil {
  186. return err
  187. }
  188. settings := amneziawg.InboundSettings{Server: server, Clients: []model.Client{}}
  189. bs, err := json.MarshalIndent(settings, "", " ")
  190. if err != nil {
  191. return err
  192. }
  193. inbound.Settings = string(bs)
  194. return nil
  195. }
  196. var parsed amneziawg.InboundSettings
  197. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  198. return fmt.Errorf("amneziawg: invalid settings: %w", err)
  199. }
  200. if parsed.Server == nil {
  201. server, err := defaultAmneziaWGServer()
  202. if err != nil {
  203. return err
  204. }
  205. parsed.Server = server
  206. } else if err := resolveAmneziaWGServerKeys(parsed.Server, oldSettings); err != nil {
  207. return err
  208. }
  209. parsed.Server.HeaderProtectionKey = strings.TrimSpace(parsed.Server.HeaderProtectionKey)
  210. for _, f := range []*string{
  211. &parsed.Server.ContentPaddingAddition, &parsed.Server.RekeyAfterTime,
  212. &parsed.Server.RekeyTimeout, &parsed.Server.RejectAfterTime,
  213. &parsed.Server.KeepaliveTimeout, &parsed.Server.MaxHandshakeAttempts,
  214. } {
  215. *f = amneziawg.CanonicalizeUintRange(*f)
  216. }
  217. if err := amneziawg.ValidateServerObfuscation(parsed.Server.Obfuscation()); err != nil {
  218. return fmt.Errorf("amneziawg: %w", err)
  219. }
  220. if err := amneziawg.ValidateIPv6Subnet(parsed.Server.IPv6Enabled, parsed.Server.IPv6Subnet); err != nil {
  221. return fmt.Errorf("amneziawg: %w", err)
  222. }
  223. if err := amneziawg.ValidateSubnetIPv4(parsed.Server.SubnetIP, parsed.Server.SubnetCIDR); err != nil {
  224. return fmt.Errorf("amneziawg: %w", err)
  225. }
  226. if err := amneziawg.ValidateInterfaceName(parsed.Server.ExternalInterface); err != nil {
  227. return fmt.Errorf("amneziawg: externalInterface: %w", err)
  228. }
  229. if err := amneziawg.ValidateInterfaceName(parsed.Server.IPv6ExternalInterface); err != nil {
  230. return fmt.Errorf("amneziawg: ipv6ExternalInterface: %w", err)
  231. }
  232. if err := amneziawg.ValidateConfigValue("privateKey", parsed.Server.PrivateKey); err != nil {
  233. return fmt.Errorf("amneziawg: %w", err)
  234. }
  235. if err := amneziawg.ValidateConfigValue("publicKey", parsed.Server.PublicKey); err != nil {
  236. return fmt.Errorf("amneziawg: %w", err)
  237. }
  238. signaturePackets := []struct{ field, v string }{
  239. {"i1", parsed.Server.I1},
  240. {"i2", parsed.Server.I2},
  241. {"i3", parsed.Server.I3},
  242. {"i4", parsed.Server.I4},
  243. {"i5", parsed.Server.I5},
  244. }
  245. for _, sp := range signaturePackets {
  246. if err := amneziawg.ValidateConfigValue(sp.field, sp.v); err != nil {
  247. return fmt.Errorf("amneziawg: %w", err)
  248. }
  249. }
  250. portCtx, err := s.loadPortConflictContext(database.GetDB())
  251. if err != nil {
  252. return err
  253. }
  254. for i := range parsed.Clients {
  255. c := &parsed.Clients[i]
  256. if err := s.amneziaWGForwardedPortsConflict(portCtx, c); err != nil {
  257. return err
  258. }
  259. if err := amneziawg.ValidateConfigValue("email", c.Email); err != nil {
  260. return fmt.Errorf("amneziawg: %w", err)
  261. }
  262. if err := amneziawg.ValidateConfigValue("publicKey", c.PublicKey); err != nil {
  263. return fmt.Errorf("amneziawg: client %q: %w", c.Email, err)
  264. }
  265. if err := amneziawg.ValidateConfigValue("preSharedKey", c.PreSharedKey); err != nil {
  266. return fmt.Errorf("amneziawg: client %q: %w", c.Email, err)
  267. }
  268. // AllowedIPs lands verbatim in a rendered [Peer] block, so a newline here
  269. // re-opens an [Interface] section whose PostUp runs as root once the
  270. // downloaded config is applied (client app, or awg-quick directly).
  271. normalized, err := normalizeWireguardAllowedIPs(c.AllowedIPs)
  272. if err != nil {
  273. return fmt.Errorf("amneziawg: client %q: %w", c.Email, err)
  274. }
  275. // An enabled peer with no address is skipped by InstanceFromInbound, and
  276. // if it was the only one the whole inbound never starts, silently.
  277. if c.Enable && len(normalized) == 0 {
  278. return fmt.Errorf("amneziawg: client %q: allowedIPs is required", c.Email)
  279. }
  280. c.AllowedIPs = normalized
  281. }
  282. bs, err := json.MarshalIndent(parsed, "", " ")
  283. if err != nil {
  284. return err
  285. }
  286. inbound.Settings = string(bs)
  287. return nil
  288. }
  289. // portConflictContext caches what checkForwardedPortsConflict needs — the panel's
  290. // own port and this host's enabled rows — so one save costs one query, not N.
  291. type portConflictContext struct {
  292. webPort int
  293. inbounds []*model.Inbound
  294. }
  295. // loadPortConflictContext loads the panel's own port and every enabled inbound
  296. // hosted on THIS panel: a node-hosted one listens on that node's host, not here.
  297. func (s *InboundService) loadPortConflictContext(db *gorm.DB) (portConflictContext, error) {
  298. var ctx portConflictContext
  299. if webPort, err := (&SettingService{}).GetPort(); err == nil {
  300. ctx.webPort = webPort
  301. }
  302. err := db.Model(model.Inbound{}).
  303. Where("enable = ? AND node_id IS NULL", true).
  304. Find(&ctx.inbounds).Error
  305. return ctx, err
  306. }
  307. // amneziaWGForwardedPortsConflict renders one client's ForwardedPorts collision,
  308. // or nil: the single copy both the pre-Save pass and the post-Save re-run use.
  309. func (s *InboundService) amneziaWGForwardedPortsConflict(ctx portConflictContext, c *model.Client) error {
  310. hit := s.checkForwardedPortsConflict(ctx, c.ForwardedPorts)
  311. if hit == "" {
  312. return nil
  313. }
  314. return fmt.Errorf("amneziawg: client %q forwardedPorts collides with %s", c.Email, hit)
  315. }
  316. // checkAmneziaWGForwardedPorts re-runs the guard over one row's stored clients:
  317. // on create it ran before Save, when the row's own ports were not in the context.
  318. func (s *InboundService) checkAmneziaWGForwardedPorts(db *gorm.DB, settings string) error {
  319. var parsed amneziawg.InboundSettings
  320. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  321. return nil
  322. }
  323. ctx, err := s.loadPortConflictContext(db)
  324. if err != nil {
  325. return err
  326. }
  327. for i := range parsed.Clients {
  328. if err := s.amneziaWGForwardedPortsConflict(ctx, &parsed.Clients[i]); err != nil {
  329. return err
  330. }
  331. }
  332. return nil
  333. }
  334. // checkForwardedPortsConflict names the panel, inbound or AmneziaWG relay port a
  335. // client's ForwardedPorts spec would collide with: a lost bind race kills the relay.
  336. func (s *InboundService) checkForwardedPortsConflict(ctx portConflictContext, forwardedPorts string) string {
  337. if forwardedPorts == "" {
  338. return ""
  339. }
  340. if amneziawg.ExceedsForwardedPortsCap(forwardedPorts) {
  341. return fmt.Sprintf("more than %d forwarded ports", amneziawg.MaxForwardedPorts)
  342. }
  343. if ctx.webPort > 0 && amneziawg.ForwardedPortsInclude(forwardedPorts, ctx.webPort) {
  344. return fmt.Sprintf("the panel's own port (%d)", ctx.webPort)
  345. }
  346. for _, ib := range ctx.inbounds {
  347. if amneziawg.ForwardedPortsInclude(forwardedPorts, ib.Port) {
  348. name := ib.Remark
  349. if name == "" {
  350. name = ib.Tag
  351. }
  352. return fmt.Sprintf("inbound '%s' (#%d, port %d)", name, ib.Id, ib.Port)
  353. }
  354. if ib.Protocol != model.AmneziaWG {
  355. continue
  356. }
  357. socksPort := amneziawgnet.SOCKSPortForInbound(ib.Id)
  358. if amneziawg.ForwardedPortsInclude(forwardedPorts, socksPort) {
  359. name := ib.Remark
  360. if name == "" {
  361. name = ib.Tag
  362. }
  363. return fmt.Sprintf("inbound '%s' (#%d)'s own SOCKS5 relay port (%d)", name, ib.Id, socksPort)
  364. }
  365. }
  366. return ""
  367. }
  368. // GetAmneziaWGDiagnostics returns a live diagnostics snapshot for inbound
  369. // id: interface up/down, listen port, and per-client handshake/traffic
  370. // state, read entirely from data amneziawgnet.Manager already tracks --
  371. // gathering it can never itself change anything. Returns an error only
  372. // when id doesn't name an AmneziaWG inbound at all; an inbound that simply
  373. // isn't running right now (disabled, no enabled clients, or reconcile
  374. // hasn't caught up yet) comes back as amneziawgnet.Diagnostics{}
  375. // (Running=false), not an error, since that's a normal state an admin
  376. // might specifically be checking for.
  377. func (s *InboundService) GetAmneziaWGDiagnostics(id int) (amneziawgnet.Diagnostics, error) {
  378. inbound, err := s.GetInbound(id)
  379. if err != nil {
  380. return amneziawgnet.Diagnostics{}, err
  381. }
  382. if inbound.Protocol != model.AmneziaWG {
  383. return amneziawgnet.Diagnostics{}, fmt.Errorf("inbound %d is not an AmneziaWG inbound", id)
  384. }
  385. inst, ok := amneziawg.InstanceFromInbound(inbound)
  386. if !ok {
  387. return amneziawgnet.Diagnostics{}, nil
  388. }
  389. return amneziawgnet.Diagnose(inst.Id, inst.Peers), nil
  390. }