conf.go 10 KB

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