1
0

params.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. package amneziawg
  2. import (
  3. "crypto/rand"
  4. "encoding/base64"
  5. "fmt"
  6. "math"
  7. "math/big"
  8. "net/netip"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. )
  13. // awgHMax caps generated H values at 2^31-1: the spec allows the full uint32,
  14. // but the amneziawg-windows-client config editor rejects anything above.
  15. const awgHMax = 2147483647
  16. // hMaxValid is the largest value ValidateObfuscation accepts for an H
  17. // parameter: uint32 max, the kernel's own limit.
  18. const hMaxValid int64 = 4294967295
  19. // randInt returns a uniform random int in [min, max] using crypto/rand. Falls
  20. // back to min on the (practically impossible) RNG error.
  21. func randInt(min, max int) int {
  22. if max <= min {
  23. return min
  24. }
  25. n, err := rand.Int(rand.Reader, big.NewInt(int64(max-min)+1))
  26. if err != nil {
  27. return min
  28. }
  29. return min + int(n.Int64())
  30. }
  31. // DefaultMTU is WireGuard/AmneziaWG's usual tunnel MTU on a 1500-byte host
  32. // link, before AmneziaWG's own S4 transport junk is prepended.
  33. const DefaultMTU = 1420
  34. // EffectiveMTU is the admin's value when set, else DefaultMTU minus S4: s4 junk
  35. // is prepended to every transport packet and never clamped against the MTU.
  36. func EffectiveMTU(configuredMTU, s4 int) int {
  37. if configuredMTU > 0 {
  38. return configuredMTU
  39. }
  40. return max(DefaultMTU-max(s4, 0), 1280)
  41. }
  42. // GenerateObfuscation31 produces a randomized AmneziaWG 3.1 parameter set: a
  43. // static value gets profiled by DPI, defeating the point.
  44. func GenerateObfuscation31() Obfuscation31 {
  45. var o Obfuscation31
  46. o.Jc = randInt(3, 6)
  47. o.Jmin = randInt(40, 89)
  48. o.Jmax = o.Jmin + randInt(50, 250)
  49. o.S1 = randInt(15, 150)
  50. o.S2 = randInt(15, 150)
  51. // Kernel constraint: S1+56 != S2, else init and response handshake
  52. // packets end up the same size after padding.
  53. for o.S1+56 == o.S2 {
  54. o.S2 = randInt(15, 150)
  55. }
  56. // Floored at 12: HeaderProtectionKey is always generated below, and IpcSet
  57. // rejects header protection unless every S1-S4 is >= 12.
  58. o.S3 = randInt(12, 55) // cookie padding
  59. o.S4 = randInt(12, 27) // transport padding (max 32)
  60. h := generateHValues()
  61. o.H1, o.H2, o.H3, o.H4 = h[0], h[1], h[2], h[3]
  62. // CPS signature packet, N random bytes before each handshake. I2-I5 stay
  63. // empty, matching Amnezia's own generator.
  64. o.I1 = fmt.Sprintf("<r %d>", randInt(32, 256))
  65. o.HeaderProtectionKey = generateHeaderProtectionKey()
  66. // Total padding stays <= 64: it rides on full-size transport packets, the
  67. // same MTU headroom that caps S4 at 32.
  68. cpLo := randInt(8, 24)
  69. o.ContentPaddingAddition = fmt.Sprintf("%d-%d", cpLo, cpLo+randInt(8, 40))
  70. // Timing windows bracket WireGuard's own constants (rekey 120s, reject
  71. // 180s) so sessions still renew before expiry.
  72. rkLo := randInt(100, 120)
  73. rkHi := rkLo + randInt(10, 40)
  74. o.RekeyAfterTime = fmt.Sprintf("%d-%d", rkLo, rkHi)
  75. // Every reject value exceeds every rekey value by >= 30s by construction.
  76. rjLo := rkHi + randInt(30, 60)
  77. o.RejectAfterTime = fmt.Sprintf("%d-%d", rjLo, rjLo+randInt(30, 90))
  78. rtLo := randInt(3, 6)
  79. o.RekeyTimeout = fmt.Sprintf("%d-%d", rtLo, rtLo+randInt(1, 4))
  80. // Max 20s: under clients' typical 25s PersistentKeepalive and ~30s NAT UDP
  81. // timeouts, or idle links lose their NAT mapping.
  82. kaLo := randInt(8, 12)
  83. o.KeepaliveTimeout = fmt.Sprintf("%d-%d", kaLo, kaLo+randInt(2, 8))
  84. haLo := randInt(15, 25)
  85. o.MaxHandshakeAttempts = fmt.Sprintf("%d-%d", haLo, haLo+randInt(5, 25))
  86. o.RandomTrailers = true
  87. // Cookie replies are DPI-fingerprintable; this stealth default trades away
  88. // WG's handshake-flood mitigation and is toggleable per inbound.
  89. o.DisableCookies = true
  90. return o
  91. }
  92. // generateHeaderProtectionKey returns base64 of 32 crypto/rand bytes, the
  93. // format amneziawg-tools' HeaderProtectionKey parser expects.
  94. func generateHeaderProtectionKey() string {
  95. key := make([]byte, 32)
  96. if _, err := rand.Read(key); err != nil {
  97. return ""
  98. }
  99. return base64.StdEncoding.EncodeToString(key)
  100. }
  101. // generateHValues returns one distinct value per H1-H4 band; low bound >= 5 (1-4 are vanilla WG message types).
  102. // Single values, not ranges: with RandomTrailers on, a wide range misclassifies transport packets as handshakes (amnezia-vpn/amneziawg-go#183).
  103. func generateHValues() [4]string {
  104. const lo = 5
  105. bandSize := (awgHMax - lo + 1) / 4
  106. var out [4]string
  107. for i := range 4 {
  108. bandLo := lo + i*bandSize
  109. bandHi := bandLo + bandSize - 1
  110. out[i] = fmt.Sprintf("%d", randInt(bandLo, bandHi))
  111. }
  112. return out
  113. }
  114. // Padded handshake messages (148+S1, 92+S2, 64+S3 bytes) must fit the smallest receive
  115. // buffer amneziawg-go has: MaxSegmentSize 1700 on iOS (device/queueconstants_ios.go).
  116. const (
  117. maxServerS1 = 1700 - 148
  118. maxServerS2 = 1700 - 92
  119. maxServerS3 = 1700 - 64
  120. )
  121. // ValidateServerObfuscation adds the receive-buffer bounds to ValidateObfuscation:
  122. // an inbound's peers may be iOS clients, which cannot receive a larger handshake.
  123. func ValidateServerObfuscation(o Obfuscation31) error {
  124. if err := ValidateObfuscation(o); err != nil {
  125. return err
  126. }
  127. for _, f := range []struct {
  128. name string
  129. v, max int
  130. }{{"S1", o.S1, maxServerS1}, {"S2", o.S2, maxServerS2}, {"S3", o.S3, maxServerS3}} {
  131. if f.v > f.max {
  132. return fmt.Errorf("invalid %s value %d (must be 0..%d so every client can receive it)", f.name, f.v, f.max)
  133. }
  134. }
  135. return nil
  136. }
  137. // ValidateObfuscation rejects malformed parameters before they are saved, so
  138. // a bad manual entry can't break the embedded amneziawg-go device's own
  139. // UAPI config apply (internal/amneziawgnet's buildUAPIConfig/IpcSet) or
  140. // produce a client config the official app rejects outright. Blank H values
  141. // are allowed (they fall back to a default); each accepts an integer or a
  142. // "100-800" range.
  143. func ValidateObfuscation(o Obfuscation31) error {
  144. if o.Jmin > o.Jmax {
  145. return fmt.Errorf("invalid Jmin/Jmax: %d must not exceed %d", o.Jmin, o.Jmax)
  146. }
  147. // amneziawg-go parses jc/jmin/jmax as uint32 and s1-s3 as uint16 (device/uapi.go);
  148. // a wider value makes IpcSet reject the whole device.
  149. for _, f := range []struct {
  150. name string
  151. v int
  152. max int64
  153. }{
  154. {"Jc", o.Jc, math.MaxUint32},
  155. {"Jmin", o.Jmin, math.MaxUint32},
  156. {"Jmax", o.Jmax, math.MaxUint32},
  157. {"S1", o.S1, math.MaxUint16},
  158. {"S2", o.S2, math.MaxUint16},
  159. {"S3", o.S3, math.MaxUint16},
  160. } {
  161. if int64(f.v) < 0 || int64(f.v) > f.max {
  162. return fmt.Errorf("invalid %s value %d (must be 0..%d)", f.name, f.v, f.max)
  163. }
  164. }
  165. for i, spec := range []string{o.I1, o.I2, o.I3, o.I4, o.I5} {
  166. if err := validateObfChain(spec); err != nil {
  167. return fmt.Errorf("invalid I%d: %w", i+1, err)
  168. }
  169. }
  170. if o.S4 < 0 || o.S4 > 32 {
  171. return fmt.Errorf("invalid S4 value %d (must be 0..32)", o.S4)
  172. }
  173. if o.S1+56 == o.S2 {
  174. return fmt.Errorf("invalid S1/S2: S1+56 must not equal S2 (%d+56 == %d)", o.S1, o.S2)
  175. }
  176. for i, h := range []string{o.H1, o.H2, o.H3, o.H4} {
  177. if err := validateUintRange(h, 0); err != nil {
  178. return fmt.Errorf("invalid H%d: %w", i+1, err)
  179. }
  180. }
  181. if err := validateHNoOverlap([4]string{o.H1, o.H2, o.H3, o.H4}); err != nil {
  182. return err
  183. }
  184. if err := validateHeaderProtectionKey(o.HeaderProtectionKey); err != nil {
  185. return err
  186. }
  187. if o.HeaderProtectionKey != "" {
  188. for i, s := range []int{o.S1, o.S2, o.S3, o.S4} {
  189. if s < 12 {
  190. return fmt.Errorf("invalid S%d value %d: header protection requires S1-S4 >= 12", i+1, s)
  191. }
  192. }
  193. }
  194. if err := validateUintRange(o.ContentPaddingAddition, 0); err != nil {
  195. return fmt.Errorf("invalid contentPaddingAddition: %w", err)
  196. }
  197. timing := []struct{ field, v string }{
  198. {"rekeyAfterTime", o.RekeyAfterTime},
  199. {"rekeyTimeout", o.RekeyTimeout},
  200. {"rejectAfterTime", o.RejectAfterTime},
  201. {"keepaliveTimeout", o.KeepaliveTimeout},
  202. {"maxHandshakeAttempts", o.MaxHandshakeAttempts},
  203. }
  204. for _, tf := range timing {
  205. // Zero would disable the timer or retry loop outright, so min is 1.
  206. if err := validateUintRange(tf.v, 1); err != nil {
  207. return fmt.Errorf("invalid %s: %w", tf.field, err)
  208. }
  209. }
  210. // Sessions must renew before hard expiry, so every possible rekey fires
  211. // before the earliest reject. A blank side means WireGuard's own default.
  212. if o.RekeyAfterTime != "" || o.RejectAfterTime != "" {
  213. rekeyHi, rejectLo := int64(120), int64(180)
  214. if o.RekeyAfterTime != "" {
  215. _, rekeyHi, _ = parseUintRange(o.RekeyAfterTime)
  216. }
  217. if o.RejectAfterTime != "" {
  218. rejectLo, _, _ = parseUintRange(o.RejectAfterTime)
  219. }
  220. if rekeyHi >= rejectLo {
  221. return fmt.Errorf("invalid rekeyAfterTime/rejectAfterTime: max rekey %d must be below min reject %d", rekeyHi, rejectLo)
  222. }
  223. }
  224. return nil
  225. }
  226. // obfChainTags mirrors amneziawg-go's own obfBuilders map (device/obf.go): an
  227. // unknown tag makes newObfChain fail, and IpcSet then rejects the whole device.
  228. var obfChainTags = map[string]bool{
  229. "b": true, "t": true, "r": true, "rc": true,
  230. "rd": true, "d": true, "ds": true, "dz": true,
  231. }
  232. // validateObfChain checks an I1-I5 signature-packet spec's "<tag value>"
  233. // structure. Each tag's own value grammar stays amneziawg-go's to enforce.
  234. func validateObfChain(spec string) error {
  235. if strings.TrimSpace(spec) == "" {
  236. return nil
  237. }
  238. remaining := spec
  239. for {
  240. start := strings.IndexByte(remaining, '<')
  241. if start == -1 {
  242. return nil
  243. }
  244. end := strings.IndexByte(remaining[start:], '>')
  245. if end == -1 {
  246. return fmt.Errorf("spec %q is missing an enclosing '>'", spec)
  247. }
  248. fields := strings.Fields(remaining[start+1 : start+end])
  249. if len(fields) == 0 {
  250. return fmt.Errorf("spec %q has an empty <> tag", spec)
  251. }
  252. if !obfChainTags[fields[0]] {
  253. return fmt.Errorf("spec %q uses unknown tag <%s>", spec, fields[0])
  254. }
  255. remaining = remaining[start+end+1:]
  256. }
  257. }
  258. // CanonicalizeUintRange stores a pasted "110 - 140" as "110-140", and
  259. // collapses a whitespace-only value back to "feature off".
  260. func CanonicalizeUintRange(v string) string {
  261. return strings.ReplaceAll(strings.TrimSpace(v), " ", "")
  262. }
  263. // validateHeaderProtectionKey accepts blank (feature off) or a base64 32-byte
  264. // key. Control chars are rejected up front: DecodeString silently ignores
  265. // \r\n, so a line-wrapped pasted key would pass and then split client configs.
  266. func validateHeaderProtectionKey(v string) error {
  267. if v == "" {
  268. return nil
  269. }
  270. if err := ValidateConfigValue("headerProtectionKey", v); err != nil {
  271. return err
  272. }
  273. key, err := base64.StdEncoding.DecodeString(v)
  274. if err != nil {
  275. return fmt.Errorf("invalid headerProtectionKey: not base64: %w", err)
  276. }
  277. if len(key) != 32 {
  278. return fmt.Errorf("invalid headerProtectionKey: got %d bytes, want 32", len(key))
  279. }
  280. return nil
  281. }
  282. // ValidateIPv6Subnet rejects a malformed subnet before it's saved. A blank
  283. // value is only valid when IPv6 itself is disabled.
  284. func ValidateIPv6Subnet(enabled bool, subnet string) error {
  285. if !enabled {
  286. return nil
  287. }
  288. if strings.TrimSpace(subnet) == "" {
  289. return fmt.Errorf("ipv6Subnet is required when IPv6 is enabled")
  290. }
  291. prefix, err := netip.ParsePrefix(subnet)
  292. if err != nil {
  293. return fmt.Errorf("invalid ipv6Subnet %q: %w", subnet, err)
  294. }
  295. if !prefix.Addr().Is6() {
  296. return fmt.Errorf("invalid ipv6Subnet %q: not an IPv6 prefix", subnet)
  297. }
  298. return nil
  299. }
  300. // interfaceNamePattern matches a plausible Linux device name (eth0, br-lan,
  301. // eno1.100, eth0:0), capped at 15 bytes (IFNAMSIZ-1).
  302. var interfaceNamePattern = regexp.MustCompile(`^[A-Za-z0-9_.@:-]{1,15}$`)
  303. // ValidateInterfaceName guards the NIC names generateServerConfig interpolates
  304. // unescaped into a root-executed PostUp/PostDown line. Blank is allowed and
  305. // means auto-detect (or, for IPv6ExternalInterface, reuse the IPv4 one).
  306. func ValidateInterfaceName(name string) error {
  307. if name == "" {
  308. return nil
  309. }
  310. if !interfaceNamePattern.MatchString(name) {
  311. return fmt.Errorf("invalid interface name %q: must be 1-15 characters of letters, digits, '.', '_', '@', ':' or '-'", name)
  312. }
  313. return nil
  314. }
  315. // ValidateSubnetIPv4 guards subnetIP, which lands in the MASQUERADE rule the
  316. // same way ExternalInterface does. subnetCIDR <= 0 means unset, mirroring
  317. // serverAddress's own default-to-/24 leniency.
  318. func ValidateSubnetIPv4(subnetIP string, subnetCIDR int) error {
  319. cidr := subnetCIDR
  320. if cidr <= 0 {
  321. cidr = 24
  322. }
  323. if cidr > 32 {
  324. return fmt.Errorf("invalid subnetCidr %d: must be 0..32", subnetCIDR)
  325. }
  326. prefix, err := netip.ParsePrefix(fmt.Sprintf("%s/%d", subnetIP, cidr))
  327. if err != nil {
  328. return fmt.Errorf("invalid subnetIp %q: %w", subnetIP, err)
  329. }
  330. if !prefix.Addr().Is4() {
  331. return fmt.Errorf("invalid subnetIp %q: not an IPv4 address", subnetIP)
  332. }
  333. return nil
  334. }
  335. // ValidateConfigValue rejects control characters in any value interpolated
  336. // verbatim into a rendered .conf: a newline re-opens an [Interface] section
  337. // whose "PostUp = ..." runs as root the moment whoever downloaded that
  338. // config -- the client app, or an admin importing it into the official
  339. // awg-quick CLI directly -- applies it. The panel's own server side never
  340. // runs awg-quick itself (internal/amneziawgnet applies config via
  341. // amneziawg-go's UAPI, not a parsed text file), but this exact value still
  342. // reaches a real text-based config downstream. field names the value.
  343. func ValidateConfigValue(field, v string) error {
  344. for _, r := range v {
  345. if r == '\n' || r == '\r' || r < 0x20 || r == 0x7f {
  346. return fmt.Errorf("invalid %s: control characters are not allowed", field)
  347. }
  348. }
  349. return nil
  350. }
  351. // validateUintRange checks a uint32-range parameter (H1-H4, the 3.x padding
  352. // and timing fields): blank, an integer, or "low-high" within the bounds.
  353. func validateUintRange(v string, minAllowed int64) error {
  354. if strings.TrimSpace(v) == "" {
  355. return nil
  356. }
  357. // parseUintRange trims each half, so "110\n-140" would otherwise pass and
  358. // then split a rendered config line in two.
  359. if err := ValidateConfigValue("range", v); err != nil {
  360. return fmt.Errorf("value %q must not contain control characters", v)
  361. }
  362. lo, hi, ok := parseUintRange(v)
  363. if !ok {
  364. return fmt.Errorf("value %q must be an integer or a low-high range", v)
  365. }
  366. if lo < minAllowed || hi > hMaxValid || lo > hi {
  367. return fmt.Errorf("range %q must satisfy %d <= low <= high <= %d", v, minAllowed, hMaxValid)
  368. }
  369. return nil
  370. }
  371. // validateHNoOverlap mirrors amneziawg-go's "headers must not overlap" (device/uapi.go).
  372. // A blank Hn is never sent, so the engine keeps its default: WireGuard's own type n.
  373. func validateHNoOverlap(hs [4]string) error {
  374. var lo, hi [4]int64
  375. for i, h := range hs {
  376. l, u, ok := parseUintRange(h)
  377. if !ok {
  378. l, u = int64(i+1), int64(i+1)
  379. }
  380. lo[i], hi[i] = l, u
  381. }
  382. for i := range 4 {
  383. for j := i + 1; j < 4; j++ {
  384. if lo[i] <= hi[j] && lo[j] <= hi[i] {
  385. return fmt.Errorf("invalid H%d/H%d: %d-%d and %d-%d overlap", i+1, j+1, lo[i], hi[i], lo[j], hi[j])
  386. }
  387. }
  388. }
  389. return nil
  390. }
  391. // parseUintRange parses "N" (lo == hi) or "low-high"; ok is false when blank
  392. // or non-numeric. Bounds are NOT checked here.
  393. func parseUintRange(v string) (lo, hi int64, ok bool) {
  394. v = strings.TrimSpace(v)
  395. if v == "" {
  396. return 0, 0, false
  397. }
  398. if loS, hiS, isRange := strings.Cut(v, "-"); isRange {
  399. l, err1 := strconv.ParseInt(strings.TrimSpace(loS), 10, 64)
  400. h, err2 := strconv.ParseInt(strings.TrimSpace(hiS), 10, 64)
  401. if err1 != nil || err2 != nil {
  402. return 0, 0, false
  403. }
  404. return l, h, true
  405. }
  406. n, err := strconv.ParseInt(v, 10, 64)
  407. if err != nil {
  408. return 0, 0, false
  409. }
  410. return n, n, true
  411. }