showconf.go 9.2 KB

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