conf.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. // Copyright 2019 the Kilo authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package wireguard
  15. import (
  16. "bufio"
  17. "bytes"
  18. "fmt"
  19. "net"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "k8s.io/apimachinery/pkg/util/validation"
  24. )
  25. type section string
  26. type key string
  27. const (
  28. separator = "="
  29. interfaceSection section = "Interface"
  30. peerSection section = "Peer"
  31. listenPortKey key = "ListenPort"
  32. allowedIPsKey key = "AllowedIPs"
  33. endpointKey key = "Endpoint"
  34. persistentKeepaliveKey key = "PersistentKeepalive"
  35. presharedKeyKey key = "PresharedKey"
  36. privateKeyKey key = "PrivateKey"
  37. publicKeyKey key = "PublicKey"
  38. )
  39. // Conf represents a WireGuard configuration file.
  40. type Conf struct {
  41. Interface *Interface
  42. Peers []*Peer
  43. }
  44. // Interface represents the `interface` section of a WireGuard configuration.
  45. type Interface struct {
  46. ListenPort uint32
  47. PrivateKey []byte
  48. }
  49. // Peer represents a `peer` section of a WireGuard configuration.
  50. type Peer struct {
  51. AllowedIPs []*net.IPNet
  52. Endpoint *Endpoint
  53. PersistentKeepalive int
  54. PresharedKey []byte
  55. PublicKey []byte
  56. }
  57. // DeduplicateIPs eliminates duplicate allowed IPs.
  58. func (p *Peer) DeduplicateIPs() {
  59. var ips []*net.IPNet
  60. seen := make(map[string]struct{})
  61. for _, ip := range p.AllowedIPs {
  62. if _, ok := seen[ip.String()]; ok {
  63. continue
  64. }
  65. ips = append(ips, ip)
  66. seen[ip.String()] = struct{}{}
  67. }
  68. p.AllowedIPs = ips
  69. }
  70. // Endpoint represents an `endpoint` key of a `peer` section.
  71. type Endpoint struct {
  72. DNSOrIP
  73. Port uint32
  74. }
  75. // String prints the string representation of the endpoint.
  76. func (e *Endpoint) String() string {
  77. if e == nil {
  78. return ""
  79. }
  80. dnsOrIP := e.DNSOrIP.String()
  81. if e.IP != nil && len(e.IP) == net.IPv6len {
  82. dnsOrIP = "[" + dnsOrIP + "]"
  83. }
  84. return dnsOrIP + ":" + strconv.FormatUint(uint64(e.Port), 10)
  85. }
  86. // DNSOrIP represents either a DNS name or an IP address.
  87. // IPs, as they are more specific, are preferred.
  88. type DNSOrIP struct {
  89. DNS string
  90. IP net.IP
  91. }
  92. // String prints the string representation of the struct.
  93. func (d DNSOrIP) String() string {
  94. if d.IP != nil {
  95. return d.IP.String()
  96. }
  97. return d.DNS
  98. }
  99. // Parse parses a given WireGuard configuration file and produces a Conf struct.
  100. func Parse(buf []byte) *Conf {
  101. var (
  102. active section
  103. ai *net.IPNet
  104. kv []string
  105. c Conf
  106. err error
  107. iface *Interface
  108. i int
  109. ip, ip4 net.IP
  110. k key
  111. line, v string
  112. peer *Peer
  113. port uint64
  114. )
  115. s := bufio.NewScanner(bytes.NewBuffer(buf))
  116. for s.Scan() {
  117. line = strings.TrimSpace(s.Text())
  118. // Skip comments.
  119. if strings.HasPrefix(line, "#") {
  120. continue
  121. }
  122. // Line is a section title.
  123. if strings.HasPrefix(line, "[") {
  124. if peer != nil {
  125. c.Peers = append(c.Peers, peer)
  126. peer = nil
  127. }
  128. if iface != nil {
  129. c.Interface = iface
  130. iface = nil
  131. }
  132. active = section(strings.TrimSpace(strings.Trim(line, "[]")))
  133. switch active {
  134. case interfaceSection:
  135. iface = new(Interface)
  136. case peerSection:
  137. peer = new(Peer)
  138. }
  139. continue
  140. }
  141. kv = strings.SplitN(line, separator, 2)
  142. if len(kv) != 2 {
  143. continue
  144. }
  145. k = key(strings.TrimSpace(kv[0]))
  146. v = strings.TrimSpace(kv[1])
  147. switch active {
  148. case interfaceSection:
  149. switch k {
  150. case listenPortKey:
  151. port, err = strconv.ParseUint(v, 10, 32)
  152. if err != nil {
  153. continue
  154. }
  155. iface.ListenPort = uint32(port)
  156. case privateKeyKey:
  157. iface.PrivateKey = []byte(v)
  158. }
  159. case peerSection:
  160. switch k {
  161. case allowedIPsKey:
  162. // Reuse string slice.
  163. kv = strings.Split(v, ",")
  164. for i = range kv {
  165. ip, ai, err = net.ParseCIDR(strings.TrimSpace(kv[i]))
  166. if err != nil {
  167. continue
  168. }
  169. if ip4 = ip.To4(); ip4 != nil {
  170. ip = ip4
  171. } else {
  172. ip = ip.To16()
  173. }
  174. ai.IP = ip
  175. peer.AllowedIPs = append(peer.AllowedIPs, ai)
  176. }
  177. case endpointKey:
  178. // Reuse string slice.
  179. kv = strings.Split(v, ":")
  180. if len(kv) < 2 {
  181. continue
  182. }
  183. port, err = strconv.ParseUint(kv[len(kv)-1], 10, 32)
  184. if err != nil {
  185. continue
  186. }
  187. d := DNSOrIP{}
  188. ip = net.ParseIP(strings.Trim(strings.Join(kv[:len(kv)-1], ":"), "[]"))
  189. if ip == nil {
  190. if len(validation.IsDNS1123Subdomain(kv[0])) != 0 {
  191. continue
  192. }
  193. d.DNS = kv[0]
  194. } else {
  195. if ip4 = ip.To4(); ip4 != nil {
  196. d.IP = ip4
  197. } else {
  198. d.IP = ip.To16()
  199. }
  200. }
  201. peer.Endpoint = &Endpoint{
  202. DNSOrIP: d,
  203. Port: uint32(port),
  204. }
  205. case persistentKeepaliveKey:
  206. i, err = strconv.Atoi(v)
  207. if err != nil {
  208. continue
  209. }
  210. peer.PersistentKeepalive = i
  211. case presharedKeyKey:
  212. peer.PresharedKey = []byte(v)
  213. case publicKeyKey:
  214. peer.PublicKey = []byte(v)
  215. }
  216. }
  217. }
  218. if peer != nil {
  219. c.Peers = append(c.Peers, peer)
  220. }
  221. if iface != nil {
  222. c.Interface = iface
  223. }
  224. return &c
  225. }
  226. // Bytes renders a WireGuard configuration to bytes.
  227. func (c *Conf) Bytes() ([]byte, error) {
  228. var err error
  229. buf := bytes.NewBuffer(make([]byte, 0, 512))
  230. if c.Interface != nil {
  231. if err = writeSection(buf, interfaceSection); err != nil {
  232. return nil, fmt.Errorf("failed to write interface: %v", err)
  233. }
  234. if err = writePKey(buf, privateKeyKey, c.Interface.PrivateKey); err != nil {
  235. return nil, fmt.Errorf("failed to write private key: %v", err)
  236. }
  237. if err = writeValue(buf, listenPortKey, strconv.FormatUint(uint64(c.Interface.ListenPort), 10)); err != nil {
  238. return nil, fmt.Errorf("failed to write listen port: %v", err)
  239. }
  240. }
  241. for i, p := range c.Peers {
  242. // Add newlines to make the formatting nicer.
  243. if i == 0 && c.Interface != nil || i != 0 {
  244. if err = buf.WriteByte('\n'); err != nil {
  245. return nil, err
  246. }
  247. }
  248. if err = writeSection(buf, peerSection); err != nil {
  249. return nil, fmt.Errorf("failed to write interface: %v", err)
  250. }
  251. if err = writeAllowedIPs(buf, p.AllowedIPs); err != nil {
  252. return nil, fmt.Errorf("failed to write allowed IPs: %v", err)
  253. }
  254. if err = writeEndpoint(buf, p.Endpoint); err != nil {
  255. return nil, fmt.Errorf("failed to write endpoint: %v", err)
  256. }
  257. if err = writeValue(buf, persistentKeepaliveKey, strconv.Itoa(p.PersistentKeepalive)); err != nil {
  258. return nil, fmt.Errorf("failed to write persistent keepalive: %v", err)
  259. }
  260. if err = writePKey(buf, presharedKeyKey, p.PresharedKey); err != nil {
  261. return nil, fmt.Errorf("failed to write preshared key: %v", err)
  262. }
  263. if err = writePKey(buf, publicKeyKey, p.PublicKey); err != nil {
  264. return nil, fmt.Errorf("failed to write public key: %v", err)
  265. }
  266. }
  267. return buf.Bytes(), nil
  268. }
  269. // Equal checks if two WireGuard configurations are equivalent.
  270. func (c *Conf) Equal(b *Conf) bool {
  271. if (c.Interface == nil) != (b.Interface == nil) {
  272. return false
  273. }
  274. if c.Interface != nil {
  275. if c.Interface.ListenPort != b.Interface.ListenPort || !bytes.Equal(c.Interface.PrivateKey, b.Interface.PrivateKey) {
  276. return false
  277. }
  278. }
  279. if len(c.Peers) != len(b.Peers) {
  280. return false
  281. }
  282. sortPeers(c.Peers)
  283. sortPeers(b.Peers)
  284. for i := range c.Peers {
  285. if len(c.Peers[i].AllowedIPs) != len(b.Peers[i].AllowedIPs) {
  286. return false
  287. }
  288. sortCIDRs(c.Peers[i].AllowedIPs)
  289. sortCIDRs(b.Peers[i].AllowedIPs)
  290. for j := range c.Peers[i].AllowedIPs {
  291. if c.Peers[i].AllowedIPs[j].String() != b.Peers[i].AllowedIPs[j].String() {
  292. return false
  293. }
  294. }
  295. if (c.Peers[i].Endpoint == nil) != (b.Peers[i].Endpoint == nil) {
  296. return false
  297. }
  298. if c.Peers[i].Endpoint != nil {
  299. if c.Peers[i].Endpoint.Port != b.Peers[i].Endpoint.Port {
  300. return false
  301. }
  302. // IPs take priority, so check them first.
  303. if !c.Peers[i].Endpoint.IP.Equal(b.Peers[i].Endpoint.IP) {
  304. return false
  305. }
  306. // Only check the DNS name if the IP is empty.
  307. if c.Peers[i].Endpoint.IP == nil && c.Peers[i].Endpoint.DNS != b.Peers[i].Endpoint.DNS {
  308. return false
  309. }
  310. }
  311. if c.Peers[i].PersistentKeepalive != b.Peers[i].PersistentKeepalive || !bytes.Equal(c.Peers[i].PresharedKey, b.Peers[i].PresharedKey) || !bytes.Equal(c.Peers[i].PublicKey, b.Peers[i].PublicKey) {
  312. return false
  313. }
  314. }
  315. return true
  316. }
  317. func sortPeers(peers []*Peer) {
  318. sort.Slice(peers, func(i, j int) bool {
  319. if bytes.Compare(peers[i].PublicKey, peers[j].PublicKey) < 0 {
  320. return true
  321. }
  322. return false
  323. })
  324. }
  325. func sortCIDRs(cidrs []*net.IPNet) {
  326. sort.Slice(cidrs, func(i, j int) bool {
  327. return cidrs[i].String() < cidrs[j].String()
  328. })
  329. }
  330. func writeAllowedIPs(buf *bytes.Buffer, ais []*net.IPNet) error {
  331. if len(ais) == 0 {
  332. return nil
  333. }
  334. var err error
  335. if err = writeKey(buf, allowedIPsKey); err != nil {
  336. return err
  337. }
  338. for i := range ais {
  339. if i != 0 {
  340. if _, err = buf.WriteString(", "); err != nil {
  341. return err
  342. }
  343. }
  344. if _, err = buf.WriteString(ais[i].String()); err != nil {
  345. return err
  346. }
  347. }
  348. return buf.WriteByte('\n')
  349. }
  350. func writePKey(buf *bytes.Buffer, k key, b []byte) error {
  351. if len(b) == 0 {
  352. return nil
  353. }
  354. var err error
  355. if err = writeKey(buf, k); err != nil {
  356. return err
  357. }
  358. if _, err = buf.Write(b); err != nil {
  359. return err
  360. }
  361. return buf.WriteByte('\n')
  362. }
  363. func writeValue(buf *bytes.Buffer, k key, v string) error {
  364. var err error
  365. if err = writeKey(buf, k); err != nil {
  366. return err
  367. }
  368. if _, err = buf.WriteString(v); err != nil {
  369. return err
  370. }
  371. return buf.WriteByte('\n')
  372. }
  373. func writeEndpoint(buf *bytes.Buffer, e *Endpoint) error {
  374. if e == nil {
  375. return nil
  376. }
  377. var err error
  378. if err = writeKey(buf, endpointKey); err != nil {
  379. return err
  380. }
  381. if _, err = buf.WriteString(e.String()); err != nil {
  382. return err
  383. }
  384. return buf.WriteByte('\n')
  385. }
  386. func writeSection(buf *bytes.Buffer, s section) error {
  387. var err error
  388. if err = buf.WriteByte('['); err != nil {
  389. return err
  390. }
  391. if _, err = buf.WriteString(string(s)); err != nil {
  392. return err
  393. }
  394. if err = buf.WriteByte(']'); err != nil {
  395. return err
  396. }
  397. return buf.WriteByte('\n')
  398. }
  399. func writeKey(buf *bytes.Buffer, k key) error {
  400. var err error
  401. if _, err = buf.WriteString(string(k)); err != nil {
  402. return err
  403. }
  404. _, err = buf.WriteString(" = ")
  405. return err
  406. }