1
0

params.go 11 KB

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