device.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. package amneziawgnet
  2. import (
  3. "fmt"
  4. "net/netip"
  5. "strings"
  6. awgconn "github.com/amnezia-vpn/amneziawg-go/v3/conn"
  7. "github.com/amnezia-vpn/amneziawg-go/v3/device"
  8. "gvisor.dev/gvisor/pkg/tcpip/stack"
  9. "github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
  10. "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  11. )
  12. // DeviceOptions carries AmneziaWG 3.0's device-wide fields (header
  13. // protection, content padding, and the five session-timing knobs) --
  14. // mirrored from amneziawg.Instance's identically named fields by every
  15. // caller (see the 3 Desired{} call sites), not read from Instance
  16. // directly, since amneziawgnet has no dependency on internal/amneziawg
  17. // beyond the plain data types it already imports. Zero-value DeviceOptions
  18. // means amneziawg-go's own real-protocol defaults throughout: classic
  19. // (non-3.0) obfuscation, and its built-in session timings (120s/5s/180s/
  20. // 10s/18 attempts -- device/constants.go).
  21. type DeviceOptions struct {
  22. // HeaderProtectionKey is a base64 32-byte key. Empty disables AWG 3.0
  23. // header protection entirely. Non-empty requires every one of
  24. // Obfuscation31.S1-S4 to be >= 12 (amneziawg-go's own HeaderCipherNonceSize
  25. // requirement) -- IpcSet will reject the config otherwise.
  26. HeaderProtectionKey string
  27. // ContentPaddingAddition, RekeyAfterTime, RekeyTimeout, RejectAfterTime,
  28. // KeepaliveTimeout, and MaxHandshakeAttempts are each a "low-high" range
  29. // (or a bare integer), amneziawg-go's own UintRange.FromString grammar
  30. // (confirmed directly against v3.0.3's device/uapi.go -- all six share
  31. // the identical parser). Empty leaves that one field at amneziawg-go's
  32. // own default.
  33. ContentPaddingAddition string
  34. RekeyAfterTime string
  35. RekeyTimeout string
  36. RejectAfterTime string
  37. KeepaliveTimeout string
  38. MaxHandshakeAttempts string
  39. // RandomTrailers and DisableCookies are AmneziaWG 3.1's two device-wide
  40. // bool toggles (confirmed against amneziawg-go v3.1.20260814's
  41. // device/uapi.go: "random_trailers"/"disable_cookies", both
  42. // strconv.ParseBool). Unlike the string fields above, buildUAPIConfig
  43. // emits these unconditionally on every call -- a bool has no "absent"
  44. // value to gate on, and always emitting both means the reconfigure-
  45. // in-place diff correctly notices a true->false edit, not just
  46. // false->true. RandomTrailers requires the peer to also run AmneziaWG
  47. // 3.1+ with it enabled: amneziawg-go's own receive path only accepts
  48. // an oversized (trailer-padded) packet when the RECEIVING side's own
  49. // RandomTrailers is also true, so a one-sided setting makes that
  50. // side's packets start getting silently dropped by the other.
  51. // DisableCookies is purely local (no peer-side coordination needed)
  52. // but trades away WireGuard's handshake-flood DoS-protection cookie
  53. // replies for a less distinctive packet shape during a flood.
  54. RandomTrailers bool
  55. DisableCookies bool
  56. // Logger is passed to device.NewDevice as-is; nil uses a silent logger
  57. // (device.NewLogger(device.LogLevelSilent, "")).
  58. Logger *device.Logger
  59. }
  60. // Device is one running embedded AmneziaWG interface: an amneziawg-go
  61. // Device over a gVisor netstack, plus the raw *stack.Stack a caller needs to
  62. // attach a TCP/UDP forwarder (see forwarder.go / udp.go). Closing it tears
  63. // down both the WireGuard device and the underlying tun/stack.
  64. type Device struct {
  65. *device.Device
  66. Stack *stack.Stack
  67. }
  68. // NewDevice constructs, configures, and brings up an embedded AmneziaWG
  69. // interface for inst in one call: a gVisor-backed tun.Device sized to
  70. // amneziawg.EffectiveMTU, addressed with inst.Address, configured via
  71. // UAPI with inst.Obfuscation, inst.PrivateKey, opts' AWG 3.0 fields, and one
  72. // UAPI peer per inst.Peers entry. It does not attach a forwarder or start
  73. // relaying traffic -- that's the caller's job (see AttachTCPForwarder /
  74. // AttachUDPHandler) -- which is exactly why a caller that will relay real
  75. // traffic must NOT use this function: see newUnconfiguredDevice's doc
  76. // comment for why, and use newUnconfiguredDevice + Configure instead.
  77. func NewDevice(inst amneziawg.Instance, opts DeviceOptions) (*Device, error) {
  78. dev, err := newUnconfiguredDevice(inst, opts)
  79. if err != nil {
  80. return nil, err
  81. }
  82. if err := dev.Configure(inst, opts); err != nil {
  83. return nil, err
  84. }
  85. return dev, nil
  86. }
  87. // newUnconfiguredDevice builds the tun/netstack/device trio but does not
  88. // configure any peers or bring the interface up -- a caller that will relay
  89. // real traffic MUST attach its TCP/UDP handlers (AttachTCPForwarder /
  90. // AttachUDPHandler) against the returned Device.Stack BEFORE calling
  91. // Configure, not after.
  92. //
  93. // This ordering is not a style preference: Configure's IpcSet is what
  94. // starts each configured peer's receive goroutine (amneziawg-go's
  95. // Peer.Start, called from handlePostConfig), and a peer whose handshake
  96. // completes fast enough (e.g. an already-connected client reconnecting
  97. // right as an MTU/address change forces this package's own Manager to
  98. // rebuild the Device) can begin delivering packets into the stack
  99. // immediately -- concurrently with a caller that only calls
  100. // gstack.SetTransportProtocolHandler (AttachTCPForwarder/AttachUDPHandler)
  101. // after Configure returns. A -race CI run caught exactly this as a real
  102. // WARNING: DATA RACE between stack.(*nic).DeliverTransportPacket (the
  103. // peer's receive goroutine, reading the handler table) and
  104. // stack.(*Stack).SetTransportProtocolHandler (the attaching goroutine,
  105. // writing it). See manager.go's ensureLocked rebuild branch for the real
  106. // call order this function exists to support.
  107. func newUnconfiguredDevice(inst amneziawg.Instance, opts DeviceOptions) (*Device, error) {
  108. addrs, err := hostAddresses(inst.Address)
  109. if err != nil {
  110. return nil, fmt.Errorf("amneziawgnet: %w", err)
  111. }
  112. mtu := amneziawg.EffectiveMTU(inst.MTU, inst.Obfuscation.S4)
  113. tun, gstack, err := createNetTUNWithStack(addrs, mtu)
  114. if err != nil {
  115. return nil, fmt.Errorf("amneziawgnet: create netstack: %w", err)
  116. }
  117. logger := opts.Logger
  118. if logger == nil {
  119. logger = device.NewLogger(device.LogLevelSilent, "")
  120. }
  121. dev := device.NewDevice(tun, awgconn.NewDefaultBind(), logger)
  122. return &Device{Device: dev, Stack: gstack}, nil
  123. }
  124. // Configure applies inst/opts to d via UAPI and brings the interface up.
  125. // Call at most once per Device, and -- for any caller relaying real
  126. // traffic -- only after any AttachTCPForwarder/AttachUDPHandler
  127. // registration against d.Stack (see newUnconfiguredDevice's doc comment
  128. // for why the order matters). Closes d and returns an error if either step
  129. // fails; the caller owns closing anything else it already built against
  130. // d.Stack in that case (e.g. a UDP relay or port-forward set).
  131. func (d *Device) Configure(inst amneziawg.Instance, opts DeviceOptions) error {
  132. conf, err := buildUAPIConfig(inst, opts)
  133. if err != nil {
  134. d.Close()
  135. return fmt.Errorf("amneziawgnet: %w", err)
  136. }
  137. if err := d.IpcSet(conf); err != nil {
  138. d.Close()
  139. return fmt.Errorf("amneziawgnet: IpcSet for inbound %d: %w", inst.Id, err)
  140. }
  141. if err := d.Up(); err != nil {
  142. d.Close()
  143. return fmt.Errorf("amneziawgnet: bring up inbound %d: %w", inst.Id, err)
  144. }
  145. return nil
  146. }
  147. // hostAddresses parses each of inst.Address's CIDR strings (e.g.
  148. // "10.8.1.1/24") down to the bare host address the netstack's NIC gets
  149. // configured with -- the interface's own address, not the subnet it routes.
  150. func hostAddresses(addresses []string) ([]netip.Addr, error) {
  151. out := make([]netip.Addr, 0, len(addresses))
  152. for _, a := range addresses {
  153. prefix, err := netip.ParsePrefix(a)
  154. if err != nil {
  155. return nil, fmt.Errorf("invalid interface address %q: %w", a, err)
  156. }
  157. out = append(out, prefix.Addr())
  158. }
  159. return out, nil
  160. }
  161. // buildUAPIConfig renders inst (plus opts' AWG 3.0 fields) as a WireGuard
  162. // UAPI "set" configuration string -- private_key/listen_port/jc.../s1-s4/
  163. // h1-h4/i1-i5 device lines, the AWG 3.0 device lines when opts asks for them,
  164. // then one public_key/preshared_key/allowed_ip block per peer. Field names
  165. // and format match amneziawg-go v3.0.3's device/uapi.go exactly (confirmed
  166. // against its real source during Phase 0 spiking, not just its docs).
  167. func buildUAPIConfig(inst amneziawg.Instance, opts DeviceOptions) (string, error) {
  168. var b strings.Builder
  169. privHex, err := wireguard.KeyToHex(inst.PrivateKey)
  170. if err != nil {
  171. return "", fmt.Errorf("invalid server private key: %w", err)
  172. }
  173. fmt.Fprintf(&b, "private_key=%s\n", privHex)
  174. fmt.Fprintf(&b, "listen_port=%d\n", inst.ListenPort)
  175. // replace_peers makes every apply a full resync (matches this package's
  176. // own Manager.Ensure semantics): peers no longer in inst.Peers are
  177. // dropped instead of lingering from a previous IpcSet call.
  178. b.WriteString("replace_peers=true\n")
  179. o := inst.Obfuscation
  180. fmt.Fprintf(&b, "jc=%d\njmin=%d\njmax=%d\n", o.Jc, o.Jmin, o.Jmax)
  181. fmt.Fprintf(&b, "s1=%d\ns2=%d\ns3=%d\ns4=%d\n", o.S1, o.S2, o.S3, o.S4)
  182. writeOptionalLine(&b, "h1", o.H1)
  183. writeOptionalLine(&b, "h2", o.H2)
  184. writeOptionalLine(&b, "h3", o.H3)
  185. writeOptionalLine(&b, "h4", o.H4)
  186. writeOptionalLine(&b, "i1", o.I1)
  187. writeOptionalLine(&b, "i2", o.I2)
  188. writeOptionalLine(&b, "i3", o.I3)
  189. writeOptionalLine(&b, "i4", o.I4)
  190. writeOptionalLine(&b, "i5", o.I5)
  191. if opts.HeaderProtectionKey != "" {
  192. hpHex, err := wireguard.KeyToHex(opts.HeaderProtectionKey)
  193. if err != nil {
  194. return "", fmt.Errorf("invalid header protection key: %w", err)
  195. }
  196. fmt.Fprintf(&b, "header_protection_key=%s\n", hpHex)
  197. }
  198. if opts.ContentPaddingAddition != "" {
  199. fmt.Fprintf(&b, "content_padding_addition=%s\n", opts.ContentPaddingAddition)
  200. }
  201. if opts.RekeyAfterTime != "" {
  202. fmt.Fprintf(&b, "rekey_after_time=%s\n", opts.RekeyAfterTime)
  203. }
  204. if opts.RekeyTimeout != "" {
  205. fmt.Fprintf(&b, "rekey_timeout=%s\n", opts.RekeyTimeout)
  206. }
  207. if opts.RejectAfterTime != "" {
  208. fmt.Fprintf(&b, "reject_after_time=%s\n", opts.RejectAfterTime)
  209. }
  210. if opts.KeepaliveTimeout != "" {
  211. fmt.Fprintf(&b, "keepalive_timeout=%s\n", opts.KeepaliveTimeout)
  212. }
  213. if opts.MaxHandshakeAttempts != "" {
  214. fmt.Fprintf(&b, "max_handshake_attempts=%s\n", opts.MaxHandshakeAttempts)
  215. }
  216. fmt.Fprintf(&b, "random_trailers=%t\n", opts.RandomTrailers)
  217. fmt.Fprintf(&b, "disable_cookies=%t\n", opts.DisableCookies)
  218. for _, p := range inst.Peers {
  219. pubHex, err := wireguard.KeyToHex(p.PublicKey)
  220. if err != nil {
  221. return "", fmt.Errorf("peer %q: invalid public key: %w", p.Email, err)
  222. }
  223. fmt.Fprintf(&b, "public_key=%s\n", pubHex)
  224. if p.PresharedKey != "" {
  225. pskHex, err := wireguard.KeyToHex(p.PresharedKey)
  226. if err != nil {
  227. return "", fmt.Errorf("peer %q: invalid preshared key: %w", p.Email, err)
  228. }
  229. fmt.Fprintf(&b, "preshared_key=%s\n", pskHex)
  230. }
  231. for _, allowedIP := range p.AllowedIPs {
  232. fmt.Fprintf(&b, "allowed_ip=%s\n", allowedIP)
  233. }
  234. }
  235. return b.String(), nil
  236. }
  237. // writeOptionalLine writes a "name=v" UAPI line only when v is set -- used for
  238. // h1-h4 and i1-i5, whose empty value means "let amneziawg-go fall back to its
  239. // own default," mirroring how internal/amneziawg's generateServerConfig
  240. // treats the same optional fields.
  241. func writeOptionalLine(b *strings.Builder, name, v string) {
  242. if v == "" {
  243. return
  244. }
  245. fmt.Fprintf(b, "%s=%s\n", name, v)
  246. }