params.go 11 KB

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