conf.go 9.2 KB

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