device.go 11 KB

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