params.go 13 KB

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