conf.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. // Equal compares two endpoints.
  87. func (e *Endpoint) Equal(b *Endpoint, DNSFirst bool) bool {
  88. if (e == nil) != (b == nil) {
  89. return false
  90. }
  91. if e != nil {
  92. if e.Port != b.Port {
  93. return false
  94. }
  95. if DNSFirst {
  96. // Check the DNS name first if it was resolved.
  97. if e.DNS != b.DNS {
  98. return false
  99. }
  100. if e.DNS == "" && !e.IP.Equal(b.IP) {
  101. return false
  102. }
  103. } else {
  104. // IPs take priority, so check them first.
  105. if !e.IP.Equal(b.IP) {
  106. return false
  107. }
  108. // Only check the DNS name if the IP is empty.
  109. if e.IP == nil && e.DNS != b.DNS {
  110. return false
  111. }
  112. }
  113. }
  114. return true
  115. }
  116. // DNSOrIP represents either a DNS name or an IP address.
  117. // IPs, as they are more specific, are preferred.
  118. type DNSOrIP struct {
  119. DNS string
  120. IP net.IP
  121. }
  122. // String prints the string representation of the struct.
  123. func (d DNSOrIP) String() string {
  124. if d.IP != nil {
  125. return d.IP.String()
  126. }
  127. return d.DNS
  128. }
  129. // Parse parses a given WireGuard configuration file and produces a Conf struct.
  130. func Parse(buf []byte) *Conf {
  131. var (
  132. active section
  133. ai *net.IPNet
  134. kv []string
  135. c Conf
  136. err error
  137. iface *Interface
  138. i int
  139. ip, ip4 net.IP
  140. k key
  141. line, v string
  142. peer *Peer
  143. port uint64
  144. )
  145. s := bufio.NewScanner(bytes.NewBuffer(buf))
  146. for s.Scan() {
  147. line = strings.TrimSpace(s.Text())
  148. // Skip comments.
  149. if strings.HasPrefix(line, "#") {
  150. continue
  151. }
  152. // Line is a section title.
  153. if strings.HasPrefix(line, "[") {
  154. if peer != nil {
  155. c.Peers = append(c.Peers, peer)
  156. peer = nil
  157. }
  158. if iface != nil {
  159. c.Interface = iface
  160. iface = nil
  161. }
  162. active = section(strings.TrimSpace(strings.Trim(line, "[]")))
  163. switch active {
  164. case interfaceSection:
  165. iface = new(Interface)
  166. case peerSection:
  167. peer = new(Peer)
  168. }
  169. continue
  170. }
  171. kv = strings.SplitN(line, separator, 2)
  172. if len(kv) != 2 {
  173. continue
  174. }
  175. k = key(strings.TrimSpace(kv[0]))
  176. v = strings.TrimSpace(kv[1])
  177. switch active {
  178. case interfaceSection:
  179. switch k {
  180. case listenPortKey:
  181. port, err = strconv.ParseUint(v, 10, 32)
  182. if err != nil {
  183. continue
  184. }
  185. iface.ListenPort = uint32(port)
  186. case privateKeyKey:
  187. iface.PrivateKey = []byte(v)
  188. }
  189. case peerSection:
  190. switch k {
  191. case allowedIPsKey:
  192. // Reuse string slice.
  193. kv = strings.Split(v, ",")
  194. for i = range kv {
  195. ip, ai, err = net.ParseCIDR(strings.TrimSpace(kv[i]))
  196. if err != nil {
  197. continue
  198. }
  199. if ip4 = ip.To4(); ip4 != nil {
  200. ip = ip4
  201. } else {
  202. ip = ip.To16()
  203. }
  204. ai.IP = ip
  205. peer.AllowedIPs = append(peer.AllowedIPs, ai)
  206. }
  207. case endpointKey:
  208. // Reuse string slice.
  209. kv = strings.Split(v, ":")
  210. if len(kv) < 2 {
  211. continue
  212. }
  213. port, err = strconv.ParseUint(kv[len(kv)-1], 10, 32)
  214. if err != nil {
  215. continue
  216. }
  217. d := DNSOrIP{}
  218. ip = net.ParseIP(strings.Trim(strings.Join(kv[:len(kv)-1], ":"), "[]"))
  219. if ip == nil {
  220. if len(validation.IsDNS1123Subdomain(kv[0])) != 0 {
  221. continue
  222. }
  223. d.DNS = kv[0]
  224. } else {
  225. if ip4 = ip.To4(); ip4 != nil {
  226. d.IP = ip4
  227. } else {
  228. d.IP = ip.To16()
  229. }
  230. }
  231. peer.Endpoint = &Endpoint{
  232. DNSOrIP: d,
  233. Port: uint32(port),
  234. }
  235. case persistentKeepaliveKey:
  236. i, err = strconv.Atoi(v)
  237. if err != nil {
  238. continue
  239. }
  240. peer.PersistentKeepalive = i
  241. case presharedKeyKey:
  242. peer.PresharedKey = []byte(v)
  243. case publicKeyKey:
  244. peer.PublicKey = []byte(v)
  245. }
  246. }
  247. }
  248. if peer != nil {
  249. c.Peers = append(c.Peers, peer)
  250. }
  251. if iface != nil {
  252. c.Interface = iface
  253. }
  254. return &c
  255. }
  256. // Bytes renders a WireGuard configuration to bytes.
  257. func (c *Conf) Bytes() ([]byte, error) {
  258. var err error
  259. buf := bytes.NewBuffer(make([]byte, 0, 512))
  260. if c.Interface != nil {
  261. if err = writeSection(buf, interfaceSection); err != nil {
  262. return nil, fmt.Errorf("failed to write interface: %v", err)
  263. }
  264. if err = writePKey(buf, privateKeyKey, c.Interface.PrivateKey); err != nil {
  265. return nil, fmt.Errorf("failed to write private key: %v", err)
  266. }
  267. if err = writeValue(buf, listenPortKey, strconv.FormatUint(uint64(c.Interface.ListenPort), 10)); err != nil {
  268. return nil, fmt.Errorf("failed to write listen port: %v", err)
  269. }
  270. }
  271. for i, p := range c.Peers {
  272. // Add newlines to make the formatting nicer.
  273. if i == 0 && c.Interface != nil || i != 0 {
  274. if err = buf.WriteByte('\n'); err != nil {
  275. return nil, err
  276. }
  277. }
  278. if err = writeSection(buf, peerSection); err != nil {
  279. return nil, fmt.Errorf("failed to write interface: %v", err)
  280. }
  281. if err = writeAllowedIPs(buf, p.AllowedIPs); err != nil {
  282. return nil, fmt.Errorf("failed to write allowed IPs: %v", err)
  283. }
  284. if err = writeEndpoint(buf, p.Endpoint); err != nil {
  285. return nil, fmt.Errorf("failed to write endpoint: %v", err)
  286. }
  287. if err = writeValue(buf, persistentKeepaliveKey, strconv.Itoa(p.PersistentKeepalive)); err != nil {
  288. return nil, fmt.Errorf("failed to write persistent keepalive: %v", err)
  289. }
  290. if err = writePKey(buf, presharedKeyKey, p.PresharedKey); err != nil {
  291. return nil, fmt.Errorf("failed to write preshared key: %v", err)
  292. }
  293. if err = writePKey(buf, publicKeyKey, p.PublicKey); err != nil {
  294. return nil, fmt.Errorf("failed to write public key: %v", err)
  295. }
  296. }
  297. return buf.Bytes(), nil
  298. }
  299. // Equal checks if two WireGuard configurations are equivalent.
  300. func (c *Conf) Equal(b *Conf) bool {
  301. if (c.Interface == nil) != (b.Interface == nil) {
  302. return false
  303. }
  304. if c.Interface != nil {
  305. if c.Interface.ListenPort != b.Interface.ListenPort || !bytes.Equal(c.Interface.PrivateKey, b.Interface.PrivateKey) {
  306. return false
  307. }
  308. }
  309. if len(c.Peers) != len(b.Peers) {
  310. return false
  311. }
  312. sortPeers(c.Peers)
  313. sortPeers(b.Peers)
  314. for i := range c.Peers {
  315. if len(c.Peers[i].AllowedIPs) != len(b.Peers[i].AllowedIPs) {
  316. return false
  317. }
  318. sortCIDRs(c.Peers[i].AllowedIPs)
  319. sortCIDRs(b.Peers[i].AllowedIPs)
  320. for j := range c.Peers[i].AllowedIPs {
  321. if c.Peers[i].AllowedIPs[j].String() != b.Peers[i].AllowedIPs[j].String() {
  322. return false
  323. }
  324. }
  325. if !c.Peers[i].Endpoint.Equal(b.Peers[i].Endpoint, false) {
  326. return false
  327. }
  328. 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) {
  329. return false
  330. }
  331. }
  332. return true
  333. }
  334. func sortPeers(peers []*Peer) {
  335. sort.Slice(peers, func(i, j int) bool {
  336. if bytes.Compare(peers[i].PublicKey, peers[j].PublicKey) < 0 {
  337. return true
  338. }
  339. return false
  340. })
  341. }
  342. func sortCIDRs(cidrs []*net.IPNet) {
  343. sort.Slice(cidrs, func(i, j int) bool {
  344. return cidrs[i].String() < cidrs[j].String()
  345. })
  346. }
  347. func writeAllowedIPs(buf *bytes.Buffer, ais []*net.IPNet) error {
  348. if len(ais) == 0 {
  349. return nil
  350. }
  351. var err error
  352. if err = writeKey(buf, allowedIPsKey); err != nil {
  353. return err
  354. }
  355. for i := range ais {
  356. if i != 0 {
  357. if _, err = buf.WriteString(", "); err != nil {
  358. return err
  359. }
  360. }
  361. if _, err = buf.WriteString(ais[i].String()); err != nil {
  362. return err
  363. }
  364. }
  365. return buf.WriteByte('\n')
  366. }
  367. func writePKey(buf *bytes.Buffer, k key, b []byte) error {
  368. if len(b) == 0 {
  369. return nil
  370. }
  371. var err error
  372. if err = writeKey(buf, k); err != nil {
  373. return err
  374. }
  375. if _, err = buf.Write(b); err != nil {
  376. return err
  377. }
  378. return buf.WriteByte('\n')
  379. }
  380. func writeValue(buf *bytes.Buffer, k key, v string) error {
  381. var err error
  382. if err = writeKey(buf, k); err != nil {
  383. return err
  384. }
  385. if _, err = buf.WriteString(v); err != nil {
  386. return err
  387. }
  388. return buf.WriteByte('\n')
  389. }
  390. func writeEndpoint(buf *bytes.Buffer, e *Endpoint) error {
  391. if e == nil {
  392. return nil
  393. }
  394. var err error
  395. if err = writeKey(buf, endpointKey); err != nil {
  396. return err
  397. }
  398. if _, err = buf.WriteString(e.String()); err != nil {
  399. return err
  400. }
  401. return buf.WriteByte('\n')
  402. }
  403. func writeSection(buf *bytes.Buffer, s section) error {
  404. var err error
  405. if err = buf.WriteByte('['); err != nil {
  406. return err
  407. }
  408. if _, err = buf.WriteString(string(s)); err != nil {
  409. return err
  410. }
  411. if err = buf.WriteByte(']'); err != nil {
  412. return err
  413. }
  414. return buf.WriteByte('\n')
  415. }
  416. func writeKey(buf *bytes.Buffer, k key) error {
  417. var err error
  418. if _, err = buf.WriteString(string(k)); err != nil {
  419. return err
  420. }
  421. _, err = buf.WriteString(" = ")
  422. return err
  423. }