showconf.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. // Copyright 2021 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 main
  15. import (
  16. "errors"
  17. "fmt"
  18. "net"
  19. "os"
  20. "strings"
  21. "time"
  22. "github.com/spf13/cobra"
  23. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/apimachinery/pkg/runtime"
  26. "k8s.io/apimachinery/pkg/runtime/schema"
  27. "k8s.io/apimachinery/pkg/runtime/serializer/json"
  28. "github.com/squat/kilo/pkg/k8s/apis/kilo/v1alpha1"
  29. "github.com/squat/kilo/pkg/mesh"
  30. "github.com/squat/kilo/pkg/wireguard"
  31. )
  32. const (
  33. outputFormatJSON = "json"
  34. outputFormatWireGuard = "wireguard"
  35. outputFormatYAML = "yaml"
  36. )
  37. var (
  38. availableOutputFormats = strings.Join([]string{
  39. outputFormatJSON,
  40. outputFormatWireGuard,
  41. outputFormatYAML,
  42. }, ", ")
  43. allowedIPs []string
  44. showConfOpts struct {
  45. allowedIPs []net.IPNet
  46. serializer *json.Serializer
  47. output string
  48. asPeer bool
  49. }
  50. )
  51. func showConf() *cobra.Command {
  52. cmd := &cobra.Command{
  53. Use: "showconf",
  54. Short: "Show the WireGuard configuration for a node or peer in the Kilo network",
  55. PersistentPreRunE: runShowConf,
  56. }
  57. for _, subCmd := range []*cobra.Command{
  58. showConfNode(),
  59. showConfPeer(),
  60. } {
  61. cmd.AddCommand(subCmd)
  62. }
  63. cmd.PersistentFlags().BoolVar(&showConfOpts.asPeer, "as-peer", false, "Should the resource be shown as a peer? Useful to configure this resource as a peer of another WireGuard interface.")
  64. cmd.PersistentFlags().StringVarP(&showConfOpts.output, "output", "o", "wireguard", fmt.Sprintf("The output format of the resource. Only valid when combined with 'as-peer'. Possible values: %s", availableOutputFormats))
  65. cmd.PersistentFlags().StringSliceVar(&allowedIPs, "allowed-ips", []string{}, "Add the given IPs to the allowed IPs of the configuration. Only valid when combined with 'as-peer'.")
  66. return cmd
  67. }
  68. func runShowConf(c *cobra.Command, args []string) error {
  69. switch showConfOpts.output {
  70. case outputFormatJSON:
  71. showConfOpts.serializer = json.NewSerializer(json.DefaultMetaFactory, peerCreatorTyper{}, peerCreatorTyper{}, true)
  72. case outputFormatWireGuard:
  73. case outputFormatYAML:
  74. showConfOpts.serializer = json.NewYAMLSerializer(json.DefaultMetaFactory, peerCreatorTyper{}, peerCreatorTyper{})
  75. default:
  76. return fmt.Errorf("output format %s unknown; posible values are: %s", showConfOpts.output, availableOutputFormats)
  77. }
  78. for i := range allowedIPs {
  79. _, aip, err := net.ParseCIDR(allowedIPs[i])
  80. if err != nil {
  81. return fmt.Errorf("allowed-ips must contain only valid CIDRs; got %q", allowedIPs[i])
  82. }
  83. showConfOpts.allowedIPs = append(showConfOpts.allowedIPs, *aip)
  84. }
  85. return runRoot(c, args)
  86. }
  87. func showConfNode() *cobra.Command {
  88. return &cobra.Command{
  89. Use: "node [name]",
  90. Short: "Show the WireGuard configuration for a node in the Kilo network",
  91. RunE: runShowConfNode,
  92. Args: cobra.ExactArgs(1),
  93. }
  94. }
  95. func showConfPeer() *cobra.Command {
  96. return &cobra.Command{
  97. Use: "peer [name]",
  98. Short: "Show the WireGuard configuration for a peer in the Kilo network",
  99. RunE: runShowConfPeer,
  100. Args: cobra.ExactArgs(1),
  101. }
  102. }
  103. func runShowConfNode(_ *cobra.Command, args []string) error {
  104. ns, err := opts.backend.Nodes().List()
  105. if err != nil {
  106. return fmt.Errorf("failed to list nodes: %w", err)
  107. }
  108. ps, err := opts.backend.Peers().List()
  109. if err != nil {
  110. return fmt.Errorf("failed to list peers: %w", err)
  111. }
  112. // Obtain the Granularity by looking at the annotation of the first node.
  113. if opts.granularity, err = determineGranularity(opts.granularity, ns); err != nil {
  114. return fmt.Errorf("failed to determine granularity: %w", err)
  115. }
  116. hostname := args[0]
  117. subnet := mesh.DefaultKiloSubnet
  118. nodes := make(map[string]*mesh.Node)
  119. for _, n := range ns {
  120. if n.Ready() {
  121. nodes[n.Name] = n
  122. }
  123. if n.WireGuardIP != nil {
  124. subnet = n.WireGuardIP
  125. }
  126. }
  127. subnet.IP = subnet.IP.Mask(subnet.Mask)
  128. if len(nodes) == 0 {
  129. return errors.New("did not find any valid Kilo nodes in the cluster")
  130. }
  131. if _, ok := nodes[hostname]; !ok {
  132. return fmt.Errorf("did not find any node named %q in the cluster", hostname)
  133. }
  134. peers := make(map[string]*mesh.Peer)
  135. for _, p := range ps {
  136. if p.Ready() {
  137. peers[p.Name] = p
  138. }
  139. }
  140. t, err := mesh.NewTopology(nodes, peers, opts.granularity, hostname, int(opts.port), wgtypes.Key{}, subnet, nil, nodes[hostname].PersistentKeepalive, nil)
  141. if err != nil {
  142. return fmt.Errorf("failed to create topology: %w", err)
  143. }
  144. var found bool
  145. for _, p := range t.PeerConf("").Peers {
  146. if p.PublicKey == nodes[hostname].Key {
  147. found = true
  148. break
  149. }
  150. }
  151. if !found {
  152. _, err := os.Stderr.WriteString(fmt.Sprintf("Node %q is not a leader node\n", hostname))
  153. return err
  154. }
  155. if !showConfOpts.asPeer {
  156. c, err := t.Conf().Bytes()
  157. if err != nil {
  158. return fmt.Errorf("failed to generate configuration: %w", err)
  159. }
  160. _, err = os.Stdout.Write(c)
  161. return err
  162. }
  163. switch showConfOpts.output {
  164. case outputFormatJSON:
  165. fallthrough
  166. case outputFormatYAML:
  167. p := t.AsPeer()
  168. if p == nil {
  169. return errors.New("cannot generate config from nil peer")
  170. }
  171. p.AllowedIPs = append(p.AllowedIPs, showConfOpts.allowedIPs...)
  172. p.DeduplicateIPs()
  173. k8sp := translatePeer(p)
  174. k8sp.Name = hostname
  175. return showConfOpts.serializer.Encode(k8sp, os.Stdout)
  176. case outputFormatWireGuard:
  177. p := t.AsPeer()
  178. if p == nil {
  179. return errors.New("cannot generate config from nil peer")
  180. }
  181. p.AllowedIPs = append(p.AllowedIPs, showConfOpts.allowedIPs...)
  182. p.DeduplicateIPs()
  183. c, err := (&wireguard.Conf{
  184. Peers: []wireguard.Peer{*p},
  185. }).Bytes()
  186. if err != nil {
  187. return fmt.Errorf("failed to generate configuration: %w", err)
  188. }
  189. _, err = os.Stdout.Write(c)
  190. return err
  191. }
  192. return nil
  193. }
  194. func runShowConfPeer(_ *cobra.Command, args []string) error {
  195. ns, err := opts.backend.Nodes().List()
  196. if err != nil {
  197. return fmt.Errorf("failed to list nodes: %w", err)
  198. }
  199. ps, err := opts.backend.Peers().List()
  200. if err != nil {
  201. return fmt.Errorf("failed to list peers: %w", err)
  202. }
  203. // Obtain the Granularity by looking at the annotation of the first node.
  204. if opts.granularity, err = determineGranularity(opts.granularity, ns); err != nil {
  205. return fmt.Errorf("failed to determine granularity: %w", err)
  206. }
  207. var hostname string
  208. subnet := mesh.DefaultKiloSubnet
  209. nodes := make(map[string]*mesh.Node)
  210. for _, n := range ns {
  211. if n.Ready() {
  212. nodes[n.Name] = n
  213. hostname = n.Name
  214. }
  215. if n.WireGuardIP != nil {
  216. subnet = n.WireGuardIP
  217. }
  218. }
  219. subnet.IP = subnet.IP.Mask(subnet.Mask)
  220. if len(nodes) == 0 {
  221. return errors.New("did not find any valid Kilo nodes in the cluster")
  222. }
  223. peer := args[0]
  224. peers := make(map[string]*mesh.Peer)
  225. for _, p := range ps {
  226. if p.Ready() {
  227. peers[p.Name] = p
  228. }
  229. }
  230. if _, ok := peers[peer]; !ok {
  231. return fmt.Errorf("did not find any peer named %q in the cluster", peer)
  232. }
  233. pka := time.Duration(0)
  234. if p := peers[peer].PersistentKeepaliveInterval; p != nil {
  235. pka = *p
  236. }
  237. t, err := mesh.NewTopology(nodes, peers, opts.granularity, hostname, mesh.DefaultKiloPort, wgtypes.Key{}, subnet, nil, pka, nil)
  238. if err != nil {
  239. return fmt.Errorf("failed to create topology: %w", err)
  240. }
  241. if !showConfOpts.asPeer {
  242. c, err := t.PeerConf(peer).Bytes()
  243. if err != nil {
  244. return fmt.Errorf("failed to generate configuration: %w", err)
  245. }
  246. _, err = os.Stdout.Write(c)
  247. return err
  248. }
  249. switch showConfOpts.output {
  250. case outputFormatJSON:
  251. fallthrough
  252. case outputFormatYAML:
  253. p := peers[peer]
  254. p.AllowedIPs = append(p.AllowedIPs, showConfOpts.allowedIPs...)
  255. p.DeduplicateIPs()
  256. k8sp := translatePeer(&p.Peer)
  257. k8sp.Name = peer
  258. return showConfOpts.serializer.Encode(k8sp, os.Stdout)
  259. case outputFormatWireGuard:
  260. p := &peers[peer].Peer
  261. p.AllowedIPs = append(p.AllowedIPs, showConfOpts.allowedIPs...)
  262. p.DeduplicateIPs()
  263. c, err := (&wireguard.Conf{
  264. Peers: []wireguard.Peer{*p},
  265. }).Bytes()
  266. if err != nil {
  267. return fmt.Errorf("failed to generate configuration: %w", err)
  268. }
  269. _, err = os.Stdout.Write(c)
  270. return err
  271. }
  272. return nil
  273. }
  274. // translatePeer translates a wireguard.Peer to a Peer CRD.
  275. // TODO this function has many similarities to peerBackend.Set(name, peer)
  276. func translatePeer(peer *wireguard.Peer) *v1alpha1.Peer {
  277. if peer == nil {
  278. return &v1alpha1.Peer{}
  279. }
  280. var aips []string
  281. for _, aip := range peer.AllowedIPs {
  282. // Skip any invalid IPs.
  283. // TODO all IPs should be valid, so no need to skip here?
  284. if aip.String() == (&net.IPNet{}).String() {
  285. continue
  286. }
  287. aips = append(aips, aip.String())
  288. }
  289. var endpoint *v1alpha1.PeerEndpoint
  290. if peer.Endpoint.Port() > 0 || !peer.Endpoint.HasDNS() {
  291. endpoint = &v1alpha1.PeerEndpoint{
  292. DNSOrIP: v1alpha1.DNSOrIP{
  293. IP: peer.Endpoint.IP().String(),
  294. DNS: peer.Endpoint.DNS(),
  295. },
  296. Port: uint32(peer.Endpoint.Port()),
  297. }
  298. }
  299. var key string
  300. if peer.PublicKey != (wgtypes.Key{}) {
  301. key = peer.PublicKey.String()
  302. }
  303. var psk string
  304. if peer.PresharedKey != nil {
  305. psk = peer.PresharedKey.String()
  306. }
  307. var pka int
  308. if peer.PersistentKeepaliveInterval != nil && *peer.PersistentKeepaliveInterval > time.Duration(0) {
  309. pka = int(*peer.PersistentKeepaliveInterval)
  310. }
  311. return &v1alpha1.Peer{
  312. TypeMeta: metav1.TypeMeta{
  313. Kind: v1alpha1.PeerKind,
  314. APIVersion: v1alpha1.SchemeGroupVersion.String(),
  315. },
  316. Spec: v1alpha1.PeerSpec{
  317. AllowedIPs: aips,
  318. Endpoint: endpoint,
  319. PersistentKeepalive: pka,
  320. PresharedKey: psk,
  321. PublicKey: key,
  322. },
  323. }
  324. }
  325. type peerCreatorTyper struct{}
  326. func (p peerCreatorTyper) New(_ schema.GroupVersionKind) (runtime.Object, error) {
  327. return &v1alpha1.Peer{}, nil
  328. }
  329. func (p peerCreatorTyper) ObjectKinds(_ runtime.Object) ([]schema.GroupVersionKind, bool, error) {
  330. return []schema.GroupVersionKind{v1alpha1.PeerGVK}, false, nil
  331. }
  332. func (p peerCreatorTyper) Recognizes(_ schema.GroupVersionKind) bool {
  333. return true
  334. }