conf.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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. "errors"
  19. "fmt"
  20. "net"
  21. "sort"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "k8s.io/apimachinery/pkg/util/validation"
  26. )
  27. type section string
  28. type key string
  29. const (
  30. separator = "="
  31. dumpSeparator = "\t"
  32. dumpNone = "(none)"
  33. dumpOff = "off"
  34. interfaceSection section = "Interface"
  35. peerSection section = "Peer"
  36. listenPortKey key = "ListenPort"
  37. allowedIPsKey key = "AllowedIPs"
  38. endpointKey key = "Endpoint"
  39. persistentKeepaliveKey key = "PersistentKeepalive"
  40. presharedKeyKey key = "PresharedKey"
  41. privateKeyKey key = "PrivateKey"
  42. publicKeyKey key = "PublicKey"
  43. )
  44. type dumpInterfaceIndex int
  45. const (
  46. dumpInterfacePrivateKeyIndex = iota
  47. dumpInterfacePublicKeyIndex
  48. dumpInterfaceListenPortIndex
  49. dumpInterfaceFWMarkIndex
  50. dumpInterfaceLen
  51. )
  52. type dumpPeerIndex int
  53. const (
  54. dumpPeerPublicKeyIndex = iota
  55. dumpPeerPresharedKeyIndex
  56. dumpPeerEndpointIndex
  57. dumpPeerAllowedIPsIndex
  58. dumpPeerLatestHandshakeIndex
  59. dumpPeerTransferRXIndex
  60. dumpPeerTransferTXIndex
  61. dumpPeerPersistentKeepaliveIndex
  62. dumpPeerLen
  63. )
  64. // Conf represents a WireGuard configuration file.
  65. type Conf struct {
  66. Interface *Interface
  67. Peers []*Peer
  68. }
  69. // Interface represents the `interface` section of a WireGuard configuration.
  70. type Interface struct {
  71. ListenPort uint32
  72. PrivateKey []byte
  73. }
  74. // Peer represents a `peer` section of a WireGuard configuration.
  75. type Peer struct {
  76. AllowedIPs []*net.IPNet
  77. Endpoint *Endpoint
  78. PersistentKeepalive int
  79. PresharedKey []byte
  80. PublicKey []byte
  81. // The following fields are part of the runtime information, not the configuration.
  82. LatestHandshake time.Time
  83. }
  84. // DeduplicateIPs eliminates duplicate allowed IPs.
  85. func (p *Peer) DeduplicateIPs() {
  86. var ips []*net.IPNet
  87. seen := make(map[string]struct{})
  88. for _, ip := range p.AllowedIPs {
  89. if _, ok := seen[ip.String()]; ok {
  90. continue
  91. }
  92. ips = append(ips, ip)
  93. seen[ip.String()] = struct{}{}
  94. }
  95. p.AllowedIPs = ips
  96. }
  97. // Endpoint represents an `endpoint` key of a `peer` section.
  98. type Endpoint struct {
  99. DNSOrIP
  100. Port uint32
  101. }
  102. // String prints the string representation of the endpoint.
  103. func (e *Endpoint) String() string {
  104. if e == nil {
  105. return ""
  106. }
  107. dnsOrIP := e.DNSOrIP.String()
  108. if e.IP != nil && len(e.IP) == net.IPv6len {
  109. dnsOrIP = "[" + dnsOrIP + "]"
  110. }
  111. return dnsOrIP + ":" + strconv.FormatUint(uint64(e.Port), 10)
  112. }
  113. // Equal compares two endpoints.
  114. func (e *Endpoint) Equal(b *Endpoint, DNSFirst bool) bool {
  115. if (e == nil) != (b == nil) {
  116. return false
  117. }
  118. if e != nil {
  119. if e.Port != b.Port {
  120. return false
  121. }
  122. if DNSFirst {
  123. // Check the DNS name first if it was resolved.
  124. if e.DNS != b.DNS {
  125. return false
  126. }
  127. if e.DNS == "" && !e.IP.Equal(b.IP) {
  128. return false
  129. }
  130. } else {
  131. // IPs take priority, so check them first.
  132. if !e.IP.Equal(b.IP) {
  133. return false
  134. }
  135. // Only check the DNS name if the IP is empty.
  136. if e.IP == nil && e.DNS != b.DNS {
  137. return false
  138. }
  139. }
  140. }
  141. return true
  142. }
  143. // DNSOrIP represents either a DNS name or an IP address.
  144. // IPs, as they are more specific, are preferred.
  145. type DNSOrIP struct {
  146. DNS string
  147. IP net.IP
  148. }
  149. // String prints the string representation of the struct.
  150. func (d DNSOrIP) String() string {
  151. if d.IP != nil {
  152. return d.IP.String()
  153. }
  154. return d.DNS
  155. }
  156. // Parse parses a given WireGuard configuration file and produces a Conf struct.
  157. func Parse(buf []byte) *Conf {
  158. var (
  159. active section
  160. kv []string
  161. c Conf
  162. err error
  163. iface *Interface
  164. i int
  165. k key
  166. line, v string
  167. peer *Peer
  168. port uint64
  169. )
  170. s := bufio.NewScanner(bytes.NewBuffer(buf))
  171. for s.Scan() {
  172. line = strings.TrimSpace(s.Text())
  173. // Skip comments.
  174. if strings.HasPrefix(line, "#") {
  175. continue
  176. }
  177. // Line is a section title.
  178. if strings.HasPrefix(line, "[") {
  179. if peer != nil {
  180. c.Peers = append(c.Peers, peer)
  181. peer = nil
  182. }
  183. if iface != nil {
  184. c.Interface = iface
  185. iface = nil
  186. }
  187. active = section(strings.TrimSpace(strings.Trim(line, "[]")))
  188. switch active {
  189. case interfaceSection:
  190. iface = new(Interface)
  191. case peerSection:
  192. peer = new(Peer)
  193. }
  194. continue
  195. }
  196. kv = strings.SplitN(line, separator, 2)
  197. if len(kv) != 2 {
  198. continue
  199. }
  200. k = key(strings.TrimSpace(kv[0]))
  201. v = strings.TrimSpace(kv[1])
  202. switch active {
  203. case interfaceSection:
  204. switch k {
  205. case listenPortKey:
  206. port, err = strconv.ParseUint(v, 10, 32)
  207. if err != nil {
  208. continue
  209. }
  210. iface.ListenPort = uint32(port)
  211. case privateKeyKey:
  212. iface.PrivateKey = []byte(v)
  213. }
  214. case peerSection:
  215. switch k {
  216. case allowedIPsKey:
  217. err = peer.parseAllowedIPs(v)
  218. if err != nil {
  219. continue
  220. }
  221. case endpointKey:
  222. err = peer.parseEndpoint(v)
  223. if err != nil {
  224. continue
  225. }
  226. case persistentKeepaliveKey:
  227. i, err = strconv.Atoi(v)
  228. if err != nil {
  229. continue
  230. }
  231. peer.PersistentKeepalive = i
  232. case presharedKeyKey:
  233. peer.PresharedKey = []byte(v)
  234. case publicKeyKey:
  235. peer.PublicKey = []byte(v)
  236. }
  237. }
  238. }
  239. if peer != nil {
  240. c.Peers = append(c.Peers, peer)
  241. }
  242. if iface != nil {
  243. c.Interface = iface
  244. }
  245. return &c
  246. }
  247. // Bytes renders a WireGuard configuration to bytes.
  248. func (c *Conf) Bytes() ([]byte, error) {
  249. var err error
  250. buf := bytes.NewBuffer(make([]byte, 0, 512))
  251. if c.Interface != nil {
  252. if err = writeSection(buf, interfaceSection); err != nil {
  253. return nil, fmt.Errorf("failed to write interface: %v", err)
  254. }
  255. if err = writePKey(buf, privateKeyKey, c.Interface.PrivateKey); err != nil {
  256. return nil, fmt.Errorf("failed to write private key: %v", err)
  257. }
  258. if err = writeValue(buf, listenPortKey, strconv.FormatUint(uint64(c.Interface.ListenPort), 10)); err != nil {
  259. return nil, fmt.Errorf("failed to write listen port: %v", err)
  260. }
  261. }
  262. for i, p := range c.Peers {
  263. // Add newlines to make the formatting nicer.
  264. if i == 0 && c.Interface != nil || i != 0 {
  265. if err = buf.WriteByte('\n'); err != nil {
  266. return nil, err
  267. }
  268. }
  269. if err = writeSection(buf, peerSection); err != nil {
  270. return nil, fmt.Errorf("failed to write interface: %v", err)
  271. }
  272. if err = writeAllowedIPs(buf, p.AllowedIPs); err != nil {
  273. return nil, fmt.Errorf("failed to write allowed IPs: %v", err)
  274. }
  275. if err = writeEndpoint(buf, p.Endpoint); err != nil {
  276. return nil, fmt.Errorf("failed to write endpoint: %v", err)
  277. }
  278. if err = writeValue(buf, persistentKeepaliveKey, strconv.Itoa(p.PersistentKeepalive)); err != nil {
  279. return nil, fmt.Errorf("failed to write persistent keepalive: %v", err)
  280. }
  281. if err = writePKey(buf, presharedKeyKey, p.PresharedKey); err != nil {
  282. return nil, fmt.Errorf("failed to write preshared key: %v", err)
  283. }
  284. if err = writePKey(buf, publicKeyKey, p.PublicKey); err != nil {
  285. return nil, fmt.Errorf("failed to write public key: %v", err)
  286. }
  287. }
  288. return buf.Bytes(), nil
  289. }
  290. // Equal checks if two WireGuard configurations are equivalent.
  291. func (c *Conf) Equal(b *Conf) bool {
  292. if (c.Interface == nil) != (b.Interface == nil) {
  293. return false
  294. }
  295. if c.Interface != nil {
  296. if c.Interface.ListenPort != b.Interface.ListenPort || !bytes.Equal(c.Interface.PrivateKey, b.Interface.PrivateKey) {
  297. return false
  298. }
  299. }
  300. if len(c.Peers) != len(b.Peers) {
  301. return false
  302. }
  303. sortPeers(c.Peers)
  304. sortPeers(b.Peers)
  305. for i := range c.Peers {
  306. if len(c.Peers[i].AllowedIPs) != len(b.Peers[i].AllowedIPs) {
  307. return false
  308. }
  309. sortCIDRs(c.Peers[i].AllowedIPs)
  310. sortCIDRs(b.Peers[i].AllowedIPs)
  311. for j := range c.Peers[i].AllowedIPs {
  312. if c.Peers[i].AllowedIPs[j].String() != b.Peers[i].AllowedIPs[j].String() {
  313. return false
  314. }
  315. }
  316. if !c.Peers[i].Endpoint.Equal(b.Peers[i].Endpoint, false) {
  317. return false
  318. }
  319. 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) {
  320. return false
  321. }
  322. }
  323. return true
  324. }
  325. func sortPeers(peers []*Peer) {
  326. sort.Slice(peers, func(i, j int) bool {
  327. if bytes.Compare(peers[i].PublicKey, peers[j].PublicKey) < 0 {
  328. return true
  329. }
  330. return false
  331. })
  332. }
  333. func sortCIDRs(cidrs []*net.IPNet) {
  334. sort.Slice(cidrs, func(i, j int) bool {
  335. return cidrs[i].String() < cidrs[j].String()
  336. })
  337. }
  338. func writeAllowedIPs(buf *bytes.Buffer, ais []*net.IPNet) error {
  339. if len(ais) == 0 {
  340. return nil
  341. }
  342. var err error
  343. if err = writeKey(buf, allowedIPsKey); err != nil {
  344. return err
  345. }
  346. for i := range ais {
  347. if i != 0 {
  348. if _, err = buf.WriteString(", "); err != nil {
  349. return err
  350. }
  351. }
  352. if _, err = buf.WriteString(ais[i].String()); err != nil {
  353. return err
  354. }
  355. }
  356. return buf.WriteByte('\n')
  357. }
  358. func writePKey(buf *bytes.Buffer, k key, b []byte) error {
  359. if len(b) == 0 {
  360. return nil
  361. }
  362. var err error
  363. if err = writeKey(buf, k); err != nil {
  364. return err
  365. }
  366. if _, err = buf.Write(b); err != nil {
  367. return err
  368. }
  369. return buf.WriteByte('\n')
  370. }
  371. func writeValue(buf *bytes.Buffer, k key, v string) error {
  372. var err error
  373. if err = writeKey(buf, k); err != nil {
  374. return err
  375. }
  376. if _, err = buf.WriteString(v); err != nil {
  377. return err
  378. }
  379. return buf.WriteByte('\n')
  380. }
  381. func writeEndpoint(buf *bytes.Buffer, e *Endpoint) error {
  382. if e == nil {
  383. return nil
  384. }
  385. var err error
  386. if err = writeKey(buf, endpointKey); err != nil {
  387. return err
  388. }
  389. if _, err = buf.WriteString(e.String()); err != nil {
  390. return err
  391. }
  392. return buf.WriteByte('\n')
  393. }
  394. func writeSection(buf *bytes.Buffer, s section) error {
  395. var err error
  396. if err = buf.WriteByte('['); err != nil {
  397. return err
  398. }
  399. if _, err = buf.WriteString(string(s)); err != nil {
  400. return err
  401. }
  402. if err = buf.WriteByte(']'); err != nil {
  403. return err
  404. }
  405. return buf.WriteByte('\n')
  406. }
  407. func writeKey(buf *bytes.Buffer, k key) error {
  408. var err error
  409. if _, err = buf.WriteString(string(k)); err != nil {
  410. return err
  411. }
  412. _, err = buf.WriteString(" = ")
  413. return err
  414. }
  415. var (
  416. errParseEndpoint = errors.New("could not parse Endpoint")
  417. )
  418. func (p *Peer) parseEndpoint(v string) error {
  419. var (
  420. kv []string
  421. err error
  422. ip, ip4 net.IP
  423. port uint64
  424. )
  425. kv = strings.Split(v, ":")
  426. if len(kv) < 2 {
  427. return errParseEndpoint
  428. }
  429. port, err = strconv.ParseUint(kv[len(kv)-1], 10, 32)
  430. if err != nil {
  431. return err
  432. }
  433. d := DNSOrIP{}
  434. ip = net.ParseIP(strings.Trim(strings.Join(kv[:len(kv)-1], ":"), "[]"))
  435. if ip == nil {
  436. if len(validation.IsDNS1123Subdomain(kv[0])) != 0 {
  437. return errParseEndpoint
  438. }
  439. d.DNS = kv[0]
  440. } else {
  441. if ip4 = ip.To4(); ip4 != nil {
  442. d.IP = ip4
  443. } else {
  444. d.IP = ip.To16()
  445. }
  446. }
  447. p.Endpoint = &Endpoint{
  448. DNSOrIP: d,
  449. Port: uint32(port),
  450. }
  451. return nil
  452. }
  453. func (p *Peer) parseAllowedIPs(v string) error {
  454. var (
  455. ai *net.IPNet
  456. kv []string
  457. err error
  458. i int
  459. ip, ip4 net.IP
  460. )
  461. kv = strings.Split(v, ",")
  462. for i = range kv {
  463. ip, ai, err = net.ParseCIDR(strings.TrimSpace(kv[i]))
  464. if err != nil {
  465. return err
  466. }
  467. if ip4 = ip.To4(); ip4 != nil {
  468. ip = ip4
  469. } else {
  470. ip = ip.To16()
  471. }
  472. ai.IP = ip
  473. p.AllowedIPs = append(p.AllowedIPs, ai)
  474. }
  475. return nil
  476. }
  477. // ParseDump parses a given WireGuard dump and produces a Conf struct.
  478. func ParseDump(buf []byte) (*Conf, error) {
  479. // from man wg, show section:
  480. // If dump is specified, then several lines are printed;
  481. // the first contains in order separated by tab: private-key, public-key, listen-port, fw‐mark.
  482. // Subsequent lines are printed for each peer and contain in order separated by tab:
  483. // public-key, preshared-key, endpoint, allowed-ips, latest-handshake, transfer-rx, transfer-tx, persistent-keepalive.
  484. var (
  485. active section
  486. values []string
  487. c Conf
  488. err error
  489. iface *Interface
  490. peer *Peer
  491. port uint64
  492. sec int64
  493. pka int
  494. line int
  495. )
  496. // First line is Interface
  497. active = interfaceSection
  498. s := bufio.NewScanner(bytes.NewBuffer(buf))
  499. for s.Scan() {
  500. values = strings.Split(s.Text(), dumpSeparator)
  501. switch active {
  502. case interfaceSection:
  503. if len(values) < dumpInterfaceLen {
  504. return nil, fmt.Errorf("invalid interface line: missing fields (%d < %d)", len(values), dumpInterfaceLen)
  505. }
  506. iface = new(Interface)
  507. for i := range values {
  508. switch i {
  509. case dumpInterfacePrivateKeyIndex:
  510. iface.PrivateKey = []byte(values[i])
  511. case dumpInterfaceListenPortIndex:
  512. port, err = strconv.ParseUint(values[i], 10, 32)
  513. if err != nil {
  514. return nil, fmt.Errorf("invalid interface line: error parsing listen-port: %w", err)
  515. }
  516. iface.ListenPort = uint32(port)
  517. }
  518. }
  519. c.Interface = iface
  520. // Next lines are Peers
  521. active = peerSection
  522. case peerSection:
  523. if len(values) < dumpPeerLen {
  524. return nil, fmt.Errorf("invalid peer line %d: missing fields (%d < %d)", line, len(values), dumpPeerLen)
  525. }
  526. peer = new(Peer)
  527. for i := range values {
  528. switch i {
  529. case dumpPeerPublicKeyIndex:
  530. peer.PublicKey = []byte(values[i])
  531. case dumpPeerPresharedKeyIndex:
  532. if values[i] == dumpNone {
  533. continue
  534. }
  535. peer.PresharedKey = []byte(values[i])
  536. case dumpPeerEndpointIndex:
  537. if values[i] == dumpNone {
  538. continue
  539. }
  540. err = peer.parseEndpoint(values[i])
  541. if err != nil {
  542. return nil, fmt.Errorf("invalid peer line %d: error parsing endpoint: %w", line, err)
  543. }
  544. case dumpPeerAllowedIPsIndex:
  545. if values[i] == dumpNone {
  546. continue
  547. }
  548. err = peer.parseAllowedIPs(values[i])
  549. if err != nil {
  550. return nil, fmt.Errorf("invalid peer line %d: error parsing allowed-ips: %w", line, err)
  551. }
  552. case dumpPeerLatestHandshakeIndex:
  553. if values[i] == "0" {
  554. // Use go zero value, not unix 0 timestamp.
  555. peer.LatestHandshake = time.Time{}
  556. continue
  557. }
  558. sec, err = strconv.ParseInt(values[i], 10, 64)
  559. if err != nil {
  560. return nil, fmt.Errorf("invalid peer line %d: error parsing latest-handshake: %w", line, err)
  561. }
  562. peer.LatestHandshake = time.Unix(sec, 0)
  563. case dumpPeerPersistentKeepaliveIndex:
  564. if values[i] == dumpOff {
  565. continue
  566. }
  567. pka, err = strconv.Atoi(values[i])
  568. if err != nil {
  569. return nil, fmt.Errorf("invalid peer line %d: error parsing persistent-keepalive: %w", line, err)
  570. }
  571. peer.PersistentKeepalive = pka
  572. }
  573. }
  574. c.Peers = append(c.Peers, peer)
  575. peer = nil
  576. }
  577. line++
  578. }
  579. return &c, nil
  580. }