/
addresses.go
82 lines (67 loc) · 1.87 KB
/
addresses.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// SPDX-FileCopyrightText: 2023 Steffen Vogel <post@steffenvogel.de>
// SPDX-License-Identifier: Apache-2.0
package main
import (
"fmt"
"io"
"net"
"os"
"github.com/spf13/cobra"
"go.uber.org/zap"
"cunicu.li/cunicu/pkg/config"
"cunicu.li/cunicu/pkg/crypto"
"cunicu.li/cunicu/pkg/log"
)
type addressesOptions struct {
mask bool
}
//nolint:gochecknoinits
func init() {
opts := &addressesOptions{}
cmd := &cobra.Command{
Use: "addresses",
Short: "Derive IPv4 and IPv6 addresses from a WireGuard X25519 public key",
Long: `cunīcu auto-configuration feature derives and assigns IPv4 and IPv6 addresses based on the public key of the WireGuard interface.
This sub-command accepts a WireGuard public key on the standard input and prints out the calculated IP addresses on the standard output.
`,
Run: func(cmd *cobra.Command, args []string) {
addresses(cmd, args, opts)
},
Example: `$ wg genkey | wg pubkey | cunicu addresses
fc2f:9a4d:777f:7a97:8197:4a5d:1d1b:ed79
10.237.119.127`,
Args: cobra.ArbitraryArgs,
ValidArgsFunction: cobra.NoFileCompletions,
}
pf := cmd.PersistentFlags()
pf.BoolVarP(&opts.mask, "mask", "m", false, "Print CIDR mask")
rootCmd.AddCommand(cmd)
}
func addresses(_ *cobra.Command, args []string, opts *addressesOptions) {
logger := log.Global
keyB64, err := io.ReadAll(os.Stdin)
if err != nil {
logger.Fatal("Failed to read from stdin", zap.Error(err))
}
key, err := crypto.ParseKey(string(keyB64))
if err != nil {
logger.Fatal("Failed to parse key",
zap.Error(err),
zap.String("key", string(keyB64)))
}
if len(args) == 0 {
args = config.DefaultPrefixes
}
for _, ps := range args {
_, p, err := net.ParseCIDR(ps)
if err != nil {
logger.Fatal("Failed to parse prefix", zap.Error(err))
}
q := key.IPAddress(*p)
if opts.mask {
fmt.Println(q.String())
} else {
fmt.Println(q.IP.String())
}
}
}