Compare commits

..

41 Commits

Author SHA1 Message Date
amery 7dd3ea8f96 zones: Machine.Zone()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-26 03:33:33 +00:00
amery 07b4a22752 zones: introduce MachineIterator interface
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-26 03:33:33 +00:00
amery 609f48a2d1 wireguard: Config.WriteTo()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-26 03:33:18 +00:00
amery d1f7d225ae zones: fix RingOneAddress()'s generated address
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-26 03:10:37 +00:00
amery dfbb358187 jpictl: introduce write command rewriting all config files
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 21:20:34 +00:00
amery 26c49dff72 jpictl: refactor zones loading
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 21:18:55 +00:00
amery 2043708949 zones: Zones.WriteWireguardKeys() and Zone.WriteWireguardKeys()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 21:18:55 +00:00
amery 311ae572da zones: Zones.PruneWireguardConfig()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 21:18:55 +00:00
amery 4ca77b0ac0 zones: Zone.PruneWireguardConfig()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 21:18:55 +00:00
amery 1859c8e04b zones: inject trailing new lines on Machine.WriteWireguardKeys()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 21:18:55 +00:00
amery 202f2e6dfc jpictl: change dump to default to YAML output
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 16:48:01 +00:00
amery 20484a5061 zones: change toml tags to match yaml and json output
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 16:46:23 +00:00
amery 45b25c63d4 jpictl: refactor dump to support TOML, JSON and YAML
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 16:44:05 +00:00
amery c0e2ae9bf1 zones: annotate Machine for JSON encoding
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 16:32:34 +00:00
amery 080021b427 zones: annotate Machine for YAML encoding
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 16:25:32 +00:00
amery 4514b44211 wireguard: implement MarshalYAML for PrivateKey and PublicKey
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 16:24:17 +00:00
amery 49b82ace71 wireguard: implement MarshalJSON for PrivateKey and PublicKey
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 16:12:27 +00:00
amery 2207e4a4a4 zones: fix New() to handle relative paths on hackpadfs
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 16:02:00 +00:00
amery 7ca01aa1e4 zones: Machine.RemoveWireguardConfig()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 15:36:58 +00:00
amery 8b72667f4d zones: Machine.RemoveWireguardKeys()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 15:20:07 +00:00
amery 49694eb7cb zones: Machine.WriteWireguardKeys()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 14:53:31 +00:00
amery 15a98c05ec zones: Machine.WriteStringFile()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 14:53:24 +00:00
amery a005823d44 zones: Machine.CreateFile() and Machine.CreateTruncFile()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-25 14:53:24 +00:00
amery 7af8484acc zones: introduce Machine.OpenFile()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-24 21:14:33 +00:00
amery 0f1f1ce968 zones: introduce Machine.RemoveFile()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-24 21:14:33 +00:00
amery 5058f286c6 zones: switch to using hackpadfs/os.FS as the standard os.FS is incomplete
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-24 21:14:33 +00:00
amery 86075eb47f zones: move Machine.ReadFile to a dedicated machine_file.go
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-24 21:14:31 +00:00
amery c81b782b26 zones: Machine.IsGateway()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-24 21:07:55 +00:00
amery 0f62ee2e53 zones: rename Machine.RingAddresses to Machine.Rings
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-24 20:52:08 +00:00
amery 30a7bceda3 wireguard: make KeyPairs solid
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-24 19:49:59 +00:00
amery 60e2687d04 wireguard: make keys arrays instead of slices
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-24 19:35:11 +00:00
amery 1419e55d5b zones: remove useless RingInfo.Address
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-24 19:06:33 +00:00
amery ffdacb833b zones: add Port information to RingAddressEncoder
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-24 17:56:19 +00:00
amery aca0a5e834 zones: calculate Machine.ID on init
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-24 17:55:43 +00:00
amery 61374d4cc5 zones: load wireguard key pairs on Machine.init()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-24 14:35:40 +00:00
amery 975e166da7 zones: allow RingInfo.Merge() to enable, but not disable
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-24 14:34:00 +00:00
amery b16c648f2c zones: introduce Machine.GetWireguardKeys()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-23 21:03:03 +00:00
amery 47d79f7576 wireguard: introduce KeyPair.Validate()
it will also set the PublicKey field is empty

Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-23 00:29:15 +00:00
amery e2f831fd6a wireguard: introduce NewKeyPair, NewPrivateKey, and PrivateKey.Public()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-23 00:18:31 +00:00
amery 1d8c818ec4 wireguard: make PrivateKey and PublicKey two distinct types
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-22 23:46:24 +00:00
amery 2f51a463b2 zones: reduce writeEnvZone() complexity
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-22 22:53:13 +00:00
18 changed files with 772 additions and 159 deletions
+7
View File
@@ -1,5 +1,7 @@
package main
import "git.jpi.io/amery/jpictl/pkg/zones"
// Config describes the repository
type Config struct {
Base string
@@ -10,3 +12,8 @@ var cfg = &Config{
Base: "./m",
Domain: "m.jpi.cloud",
}
// LoadZones loads all zones and machines in the config directory
func (cfg *Config) LoadZones() (*zones.Zones, error) {
return zones.New(cfg.Base, cfg.Domain)
}
+54 -5
View File
@@ -2,27 +2,76 @@ package main
import (
"bytes"
"encoding/json"
"io"
"os"
"github.com/burntSushi/toml"
"github.com/spf13/cobra"
"git.jpi.io/amery/jpictl/pkg/zones"
"gopkg.in/yaml.v3"
)
// Encoder represents an object that encodes another internally
type Encoder interface {
Encode(any) error
}
// Encoding represents a type of [Encoder]
type Encoding int
const (
// TOMLEncoding represents TOML encoding
TOMLEncoding Encoding = iota
// JSONEncoding represents JSON encoding
JSONEncoding
// YAMLEncoding represents YAML encoding
YAMLEncoding
)
// NewJSONEncoder returns a JSON [Encoder] to work on the given [io.Writer]
func NewJSONEncoder(w io.Writer) Encoder {
enc := json.NewEncoder(w)
enc.SetIndent(``, ` `)
return enc
}
// NewYAMLEncoder returns a YAML [Encoder] to work on the given [io.Writer]
func NewYAMLEncoder(w io.Writer) Encoder {
enc := yaml.NewEncoder(w)
enc.SetIndent(2)
return enc
}
// NewTOMLEncoder returns a TOML [Encoder] to work on the given [io.Writer]
func NewTOMLEncoder(w io.Writer) Encoder {
enc := toml.NewEncoder(w)
return enc
}
const encoding = YAMLEncoding
// Command
var dumpCmd = &cobra.Command{
Use: "dump",
Short: "generates a toml representation of the config",
Short: "generates a text representation of the config",
RunE: func(_ *cobra.Command, _ []string) error {
var buf bytes.Buffer
var enc Encoder
m, err := zones.New(cfg.Base, cfg.Domain)
m, err := cfg.LoadZones()
if err != nil {
return err
}
enc := toml.NewEncoder(&buf)
switch encoding {
case JSONEncoding:
enc = NewJSONEncoder(&buf)
case YAMLEncoding:
enc = NewYAMLEncoder(&buf)
default:
enc = NewTOMLEncoder(&buf)
}
if err = enc.Encode(m); err != nil {
return err
}
+1 -3
View File
@@ -4,8 +4,6 @@ import (
"os"
"github.com/spf13/cobra"
"git.jpi.io/amery/jpictl/pkg/zones"
)
// Command
@@ -13,7 +11,7 @@ var envCmd = &cobra.Command{
Use: "env",
Short: "generates environment variables for shell scripts",
RunE: func(_ *cobra.Command, _ []string) error {
m, err := zones.New(cfg.Base, cfg.Domain)
m, err := cfg.LoadZones()
if err != nil {
return err
}
+23
View File
@@ -0,0 +1,23 @@
package main
import (
"github.com/spf13/cobra"
)
// Command
var writeCmd = &cobra.Command{
Use: "write",
Short: "rewrites all config files",
RunE: func(_ *cobra.Command, _ []string) error {
m, err := cfg.LoadZones()
if err != nil {
return err
}
return m.SyncAll()
},
}
func init() {
rootCmd.AddCommand(writeCmd)
}
+3
View File
@@ -8,9 +8,12 @@ require (
darvaza.org/sidecar v0.0.0-20230721122716-b9c54b8adbaf
darvaza.org/slog v0.5.2
github.com/burntSushi/toml v0.3.1
github.com/hack-pad/hackpadfs v0.2.1
github.com/mgechev/revive v1.3.2
github.com/spf13/cobra v1.7.0
golang.org/x/crypto v0.12.0
gopkg.in/gcfg.v1 v1.2.3
gopkg.in/yaml.v3 v3.0.1
)
require (
+5
View File
@@ -26,6 +26,8 @@ github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBD
github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4=
github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/hack-pad/hackpadfs v0.2.1 h1:FelFhIhv26gyjujoA/yeFO+6YGlqzmc9la/6iKMIxMw=
github.com/hack-pad/hackpadfs v0.2.1/go.mod h1:khQBuCEwGXWakkmq8ZiFUvUZz84ZkJ2KNwKvChs4OrU=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
@@ -70,6 +72,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
golang.org/x/crypto v0.12.0 h1:tFM/ta59kqch6LlvYnPa0yx5a83cL2nHflFhYKvv9Yk=
golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw=
golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 h1:MGwJjxBy0HJshjDNfLsYO8xppfqWlA5ZT9OhtUUhTNw=
golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
@@ -86,6 +90,7 @@ golang.org/x/text v0.12.0 h1:k+n5B8goJNdU7hSvEtMUz3d1Q6D/XW4COJSJR6fN0mc=
golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/tools v0.12.0 h1:YW6HUoUmYBpwSgyaGaZq1fHjrBjX1rlpZ54T6mu2kss=
golang.org/x/tools v0.12.0/go.mod h1:Sc0INKfu04TlqNoRA1hgpFZbhYXHPr4V5DzpSBTPqQM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/gcfg.v1 v1.2.3 h1:m8OOJ4ccYHnx2f4gQwpno8nAX5OGOh7RLaaz0pj3Ogs=
gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o=
+38 -4
View File
@@ -1,17 +1,40 @@
package wireguard
import (
"bytes"
"errors"
"fmt"
"io"
"net/netip"
"strconv"
"strings"
"text/template"
"darvaza.org/core"
"gopkg.in/gcfg.v1"
)
var configTemplate = template.Must(template.New("config").Funcs(template.FuncMap{
"PrefixJoin": func(a []netip.Prefix, sep string) string {
s := make([]string, len(a))
for i, p := range a {
s[i] = p.String()
}
return strings.Join(s, sep)
},
}).Parse(`[Interface]
Address = {{.Interface.Address}}
PrivateKey = {{.Interface.PrivateKey}}
ListenPort = {{.Interface.ListenPort}}
{{- range .Peer }}
[Peer]
PublicKey = {{.PublicKey}}
Endpoint = {{.Endpoint}}
AllowedIPs = {{ PrefixJoin .AllowedIPs ", "}}
{{- end }}
`))
// Config represents a wgN.conf file
type Config struct {
Interface InterfaceConfig
@@ -28,16 +51,27 @@ func (f *Config) Peers() int {
return len(f.Peer)
}
// WriteTo writes a Wireguard [Config] onto the provided [io.Writer]
func (f *Config) WriteTo(w io.Writer) (int64, error) {
var buf bytes.Buffer
if err := configTemplate.Execute(&buf, f); err != nil {
return 0, err
}
return buf.WriteTo(w)
}
// InterfaceConfig represents the [Interface] section
type InterfaceConfig struct {
Address netip.Addr
PrivateKey BinaryKey
PrivateKey PrivateKey
ListenPort uint16
}
// PeerConfig represents a [Peer] section
type PeerConfig struct {
PublicKey BinaryKey
PublicKey PublicKey
Endpoint EndpointAddress
AllowedIPs []netip.Prefix
}
@@ -135,7 +169,7 @@ func (p interfaceConfig) Export() (InterfaceConfig, error) {
ListenPort: p.ListenPort,
}
out.PrivateKey, err = BinaryKeyFromBase64(p.PrivateKey)
out.PrivateKey, err = PrivateKeyFromBase64(p.PrivateKey)
if err != nil {
err = core.Wrap(err, "PrivateKey")
return InterfaceConfig{}, err
@@ -162,7 +196,7 @@ func (v *intermediateConfig) ExportPeer(i int) (PeerConfig, error) {
}
// PublicKey
out.PublicKey, err = BinaryKeyFromBase64(v.Peer.PublicKey[i])
out.PublicKey, err = PublicKeyFromBase64(v.Peer.PublicKey[i])
if err != nil {
err = core.Wrap(err, "PublicKey")
return out, err
+198 -15
View File
@@ -2,35 +2,218 @@ package wireguard
import (
"bytes"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"golang.org/x/crypto/curve25519"
)
// BinaryKey is a binary blob
type BinaryKey []byte
const (
// PrivateKeySize is the length in bytes of a Wireguard Private Key
PrivateKeySize = 32
// PublicKeySize is the length in bytes of a Wireguard Public Key
PublicKeySize = 32
)
func (k BinaryKey) String() string {
return base64.StdEncoding.EncodeToString(k)
var (
// ErrInvalidKeySize indicates the key size is wrong
ErrInvalidKeySize = errors.New("invalid key size")
// ErrInvalidPrivateKey indicates the private key is invalid
ErrInvalidPrivateKey = errors.New("invalid private key")
// ErrInvalidPublicKey indicates the public key is invalid
ErrInvalidPublicKey = errors.New("invalid public key")
)
type (
// PrivateKey is a binary Wireguard Private Key
PrivateKey [PrivateKeySize]byte
// PublicKey is a binary Wireguard Public Key
PublicKey [PublicKeySize]byte
)
func (key PrivateKey) String() string {
switch {
case key.IsZero():
return ""
default:
return base64.StdEncoding.EncodeToString(key[:])
}
}
func (pub PublicKey) String() string {
switch {
case pub.IsZero():
return ""
default:
return base64.StdEncoding.EncodeToString(pub[:])
}
}
// MarshalJSON encodes the key for JSON, omiting empty.
func (key PrivateKey) MarshalJSON() ([]byte, error) {
return encodeKeyJSON(key.String())
}
// MarshalJSON encodes the key for JSON, omiting empty.
func (pub PublicKey) MarshalJSON() ([]byte, error) {
return encodeKeyJSON(pub.String())
}
func encodeKeyJSON(s string) ([]byte, error) {
var out []byte
if s != "" {
out = []byte(fmt.Sprintf("%q", s))
}
return out, nil
}
// MarshalYAML encodes the key for YAML, omiting empty.
func (key PrivateKey) MarshalYAML() (any, error) {
return encodeKeyYAML(key.String())
}
// MarshalYAML encodes the key for YAML, omiting empty.
func (pub PublicKey) MarshalYAML() (any, error) {
return encodeKeyYAML(pub.String())
}
func encodeKeyYAML(s string) (any, error) {
if s == "" {
return nil, nil
}
return s, nil
}
// IsZero tells if the key hasn't been set
func (k BinaryKey) IsZero() bool {
return len(k) == 0
func (key PrivateKey) IsZero() bool {
var zero PrivateKey
return key.Equal(zero)
}
// Equal checks if two keys are identical
func (k BinaryKey) Equal(alter BinaryKey) bool {
return bytes.Equal(k, alter)
// IsZero tells if the key hasn't been set
func (pub PublicKey) IsZero() bool {
var zero PublicKey
return pub.Equal(zero)
}
// BinaryKeyFromBase64 decodes a base64-based string into
// a [BinaryKey]
func BinaryKeyFromBase64(data string) (BinaryKey, error) {
// Equal checks if two private keys are identical
func (key PrivateKey) Equal(alter PrivateKey) bool {
return bytes.Equal(key[:], alter[:])
}
// Equal checks if two public keys are identical
func (pub PublicKey) Equal(alter PublicKey) bool {
return bytes.Equal(pub[:], alter[:])
}
// PrivateKeyFromBase64 decodes a base64-based string into
// a [PrivateKey]
func PrivateKeyFromBase64(data string) (PrivateKey, error) {
b, err := decodeKey(data, PrivateKeySize)
if err != nil {
var zero PrivateKey
return zero, err
}
return *(*[PrivateKeySize]byte)(b), nil
}
// PublicKeyFromBase64 decodes a base64-based string into
// a [PublicKey]
func PublicKeyFromBase64(data string) (PublicKey, error) {
b, err := decodeKey(data, PublicKeySize)
if err != nil {
var zero PublicKey
return zero, err
}
return *(*[PublicKeySize]byte)(b), nil
}
func decodeKey(data string, size int) ([]byte, error) {
b, err := base64.StdEncoding.DecodeString(data)
return BinaryKey(b), err
switch {
case err != nil:
return []byte{}, err
case len(b) != size:
err = ErrInvalidKeySize
return []byte{}, err
default:
return b, nil
}
}
// NewPrivateKey creates a new PrivateKey
func NewPrivateKey() (PrivateKey, error) {
var s [PrivateKeySize]byte
_, err := rand.Read(s[:])
if err != nil {
var zero PrivateKey
return zero, err
}
// apply same clamping as wireguard-go/device/noise-helpers.go
s[0] &= 0xf8
s[31] = (s[31] & 0x7f) | 0x40
return s, nil
}
// Public generates the corresponding PublicKey
func (key PrivateKey) Public() PublicKey {
var pub PublicKey
if !key.IsZero() {
in := (*[PrivateKeySize]byte)(&key)
out := (*[PublicKeySize]byte)(&pub)
curve25519.ScalarBaseMult(out, in)
}
return pub
}
// KeyPair holds a Key pair
type KeyPair struct {
PrivateKey BinaryKey
PublicKey BinaryKey
PrivateKey PrivateKey
PublicKey PublicKey
}
// Validate checks the PublicKey matches the PrivateKey,
// and sets the PublicKey if missing
func (kp *KeyPair) Validate() error {
keyLen := len(kp.PrivateKey)
pubLen := len(kp.PublicKey)
switch {
case keyLen != PrivateKeySize:
// bad private key
return ErrInvalidPrivateKey
case pubLen == 0:
// no public key, set it
kp.PublicKey = kp.PrivateKey.Public()
return nil
case pubLen != PublicKeySize:
// bad public key
return ErrInvalidPublicKey
case !kp.PrivateKey.Public().Equal(kp.PublicKey):
// wrong public key
return ErrInvalidPublicKey
default:
// correct public key
return nil
}
}
// NewKeyPair creates a new KeyPair for Wireguard
func NewKeyPair() (KeyPair, error) {
var out KeyPair
key, err := NewPrivateKey()
if err == nil {
out.PrivateKey = key
out.PublicKey = key.Public()
}
return out, nil
}
+24 -19
View File
@@ -31,25 +31,7 @@ func (m *Zones) writeEnvZone(w io.Writer, z *Zone) {
m.writeEnvVar(w, z.Name, "ZONE%v_%s", zoneID, "NAME")
// ZONE{zoneID}_GW
firstNodeID := 0
gatewayID := 0
z.ForEachMachine(func(p *Machine) bool {
nodeID := p.ID()
if firstNodeID == 0 {
firstNodeID = nodeID
}
if _, found := p.getRingInfo(0); found {
gatewayID = nodeID
}
return gatewayID != 0
})
if gatewayID == 0 {
gatewayID = firstNodeID
}
gatewayID := getRingZeroGatewayID(z)
m.writeEnvVar(w, fmt.Sprintf("%v", gatewayID), "ZONE%v_%s", zoneID, "GW")
// ZONE{zoneID}_IP
@@ -95,3 +77,26 @@ func genEnvZoneNodes(z *Zone) string {
}
return strings.Join(s, " ")
}
func getRingZeroGatewayID(z *Zone) int {
var firstNodeID, gatewayID int
z.ForEachMachine(func(p *Machine) bool {
if firstNodeID == 0 {
firstNodeID = p.ID
}
if p.IsGateway() {
gatewayID = p.ID
}
return gatewayID != 0
})
switch {
case gatewayID == 0:
return firstNodeID
default:
return gatewayID
}
}
+15 -50
View File
@@ -1,52 +1,28 @@
package zones
import (
"fmt"
"io/fs"
"net/netip"
"path/filepath"
"strconv"
"strings"
"sync"
)
// revive:disable:line-length-limit
// A Machine is a machine on a Zone
type Machine struct {
mu sync.Mutex
zone *Zone
id int
Name string `toml:"name"`
ID int `toml:"id"`
Name string `toml:"-" json:"-" yaml:"-"`
PublicAddresses []netip.Addr `toml:"public,omitempty"`
RingAddresses []*RingInfo `toml:"rings,omitempty"`
PublicAddresses []netip.Addr `toml:"public,omitempty" json:"public,omitempty" yaml:"public,omitempty"`
Rings []*RingInfo `toml:"rings,omitempty" json:"rings,omitempty" yaml:"rings,omitempty"`
}
// revive:enable:line-length-limit
func (m *Machine) String() string {
return m.Name
}
// ID return the index within the [Zone] associated to this [Machine]
func (m *Machine) ID() int {
m.mu.Lock()
defer m.mu.Unlock()
if m.id == 0 {
zoneName := m.zone.Name
s := m.Name[len(zoneName)+1:]
id, err := strconv.ParseInt(s, 10, 8)
if err != nil {
panic(err)
}
m.id = int(id)
}
return m.id
}
// FullName returns the Name of the machine including domain name
func (m *Machine) FullName() string {
if domain := m.zone.zones.domain; domain != "" {
@@ -61,26 +37,15 @@ func (m *Machine) FullName() string {
return m.Name
}
// ReadFile reads a file from the machine's config directory
func (m *Machine) ReadFile(name string, args ...any) ([]byte, error) {
base := m.zone.zones.dir
fullName := m.getFilename(name, args...)
return fs.ReadFile(base, fullName)
// IsGateway tells if the Machine is a ring0 gateway
func (m *Machine) IsGateway() bool {
_, ok := m.getRingInfo(0)
return ok
}
func (m *Machine) getFilename(name string, args ...any) string {
if len(args) > 0 {
name = fmt.Sprintf(name, args...)
}
s := []string{
m.zone.Name,
m.Name,
name,
}
return filepath.Join(s...)
// Zone indicates the [Zone] this machine belongs to
func (m *Machine) Zone() int {
return m.zone.ID
}
func (m *Machine) getPeerByName(name string) (*Machine, bool) {
+87
View File
@@ -0,0 +1,87 @@
package zones
import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
fs "github.com/hack-pad/hackpadfs"
)
// OpenFile opens a file on the machine's config directory with the specified flags
func (m *Machine) OpenFile(name string, flags int, args ...any) (fs.File, error) {
base := m.zone.zones.dir
fullName := m.getFilename(name, args...)
return fs.OpenFile(base, fullName, flags, 0644)
}
// CreateTruncFile creates or truncates a file on the machine's config directory
func (m *Machine) CreateTruncFile(name string, args ...any) (io.WriteCloser, error) {
return m.openWriter(name, os.O_CREATE|os.O_TRUNC, args...)
}
// CreateFile creates a file on the machine's config directory
func (m *Machine) CreateFile(name string, args ...any) (io.WriteCloser, error) {
return m.openWriter(name, os.O_CREATE, args...)
}
func (m *Machine) openWriter(name string, flags int, args ...any) (io.WriteCloser, error) {
f, err := m.OpenFile(name, os.O_WRONLY|flags, args...)
if err != nil {
return nil, err
}
return f.(io.WriteCloser), nil
}
// RemoveFile deletes a file from the machine's config directory
func (m *Machine) RemoveFile(name string, args ...any) error {
base := m.zone.zones.dir
fullName := m.getFilename(name, args...)
err := fs.Remove(base, fullName)
switch {
case os.IsNotExist(err):
return nil
default:
return err
}
}
// ReadFile reads a file from the machine's config directory
func (m *Machine) ReadFile(name string, args ...any) ([]byte, error) {
base := m.zone.zones.dir
fullName := m.getFilename(name, args...)
return fs.ReadFile(base, fullName)
}
// WriteStringFile writes the given content to a file on the machine's config directory
func (m *Machine) WriteStringFile(value string, name string, args ...any) error {
f, err := m.CreateTruncFile(name, args...)
if err != nil {
return err
}
defer f.Close()
buf := bytes.NewBufferString(value)
_, err = buf.WriteTo(f)
return err
}
func (m *Machine) getFilename(name string, args ...any) string {
if len(args) > 0 {
name = fmt.Sprintf(name, args...)
}
s := []string{
m.zone.Name,
m.Name,
name,
}
return filepath.Join(s...)
}
+137 -10
View File
@@ -3,6 +3,7 @@ package zones
import (
"bytes"
"fmt"
"io/fs"
"os"
"darvaza.org/core"
@@ -10,6 +11,122 @@ import (
"git.jpi.io/amery/jpictl/pkg/wireguard"
)
// GetWireguardKeys reads a wgN.key/wgN.pub files
func (m *Machine) GetWireguardKeys(ring int) (wireguard.KeyPair, error) {
var (
data []byte
err error
out wireguard.KeyPair
)
data, err = m.ReadFile("wg%v.key", ring)
if err != nil {
// failed to read
return out, err
}
out.PrivateKey, err = wireguard.PrivateKeyFromBase64(string(data))
if err != nil {
// bad key
err = core.Wrapf(err, "wg%v.key", ring)
return out, err
}
data, err = m.ReadFile("wg%v.pub", ring)
switch {
case os.IsNotExist(err):
// no wgN.pub is fine
case err != nil:
// failed to read
return out, err
default:
// good read
out.PublicKey, err = wireguard.PublicKeyFromBase64(string(data))
if err != nil {
// bad key
err = core.Wrapf(err, "wg%v.pub", ring)
return out, err
}
}
err = out.Validate()
return out, err
}
func (m *Machine) tryReadWireguardKeys(ring int) error {
kp, err := m.GetWireguardKeys(ring)
switch {
case os.IsNotExist(err):
// ignore
return nil
case err != nil:
// something went wrong
return err
default:
// import keys
ri := &RingInfo{
Ring: ring,
Keys: kp,
}
return m.applyRingInfo(ring, ri)
}
}
// WriteWireguardKeys writes the wgN.key/wgN.pub files
func (m *Machine) WriteWireguardKeys(ring int) error {
var err error
var key, pub string
var ri *RingInfo
ri, _ = m.getRingInfo(ring)
if ri != nil {
key = ri.Keys.PrivateKey.String()
pub = ri.Keys.PublicKey.String()
}
switch {
case key == "":
return fs.ErrNotExist
case pub == "":
pub = ri.Keys.PrivateKey.Public().String()
}
err = m.WriteStringFile(key+"\n", "wg%v.key", ring)
if err != nil {
return err
}
err = m.WriteStringFile(pub+"\n", "wg%v.pub", ring)
if err != nil {
return err
}
return nil
}
// RemoveWireguardKeys deletes wgN.key and wgN.pub from
// the machine's config directory
func (m *Machine) RemoveWireguardKeys(ring int) error {
var err error
err = m.RemoveFile("wg%v.pub", ring)
switch {
case os.IsNotExist(err):
// ignore
case err != nil:
return err
}
err = m.RemoveFile("wg%v.key", ring)
if os.IsNotExist(err) {
// ignore
err = nil
}
return err
}
// GetWireguardConfig reads a wgN.conf file
func (m *Machine) GetWireguardConfig(ring int) (*wireguard.Config, error) {
data, err := m.ReadFile("wg%v.conf", ring)
@@ -61,9 +178,9 @@ func (m *Machine) applyWireguardConfig(ring int, wg *wireguard.Config) error {
}
func (m *Machine) getRingInfo(ring int) (*RingInfo, bool) {
for _, ri := range m.RingAddresses {
for _, ri := range m.Rings {
if ri.Ring == ring {
return ri, true
return ri, ri.Enabled
}
}
@@ -71,10 +188,10 @@ func (m *Machine) getRingInfo(ring int) (*RingInfo, bool) {
}
func (m *Machine) applyRingInfo(ring int, new *RingInfo) error {
cur, found := m.getRingInfo(ring)
if !found {
cur, _ := m.getRingInfo(ring)
if cur == nil {
// first, append
m.RingAddresses = append(m.RingAddresses, new)
m.Rings = append(m.Rings, new)
return nil
}
@@ -86,8 +203,7 @@ func (m *Machine) applyWireguardInterfaceConfig(ring int, data wireguard.Interfa
ri := &RingInfo{
Ring: ring,
Enabled: true,
Address: data.Address,
Keys: &wireguard.KeyPair{
Keys: wireguard.KeyPair{
PrivateKey: data.PrivateKey,
},
}
@@ -107,7 +223,7 @@ func (m *Machine) applyWireguardPeerConfig(ring int, pc wireguard.PeerConfig) er
ri := &RingInfo{
Ring: ring,
Enabled: true,
Keys: &wireguard.KeyPair{
Keys: wireguard.KeyPair{
PublicKey: pc.PublicKey,
},
}
@@ -124,8 +240,8 @@ func (m *Machine) applyZoneNodeID(zoneID, nodeID int) error {
return fmt.Errorf("invalid %s", "zoneID")
case nodeID == 0:
return fmt.Errorf("invalid %s", "nodeID")
case m.ID() != nodeID:
return fmt.Errorf("invalid %s: %v ≠ %v", "zoneID", m.ID(), nodeID)
case m.ID != nodeID:
return fmt.Errorf("invalid %s: %v ≠ %v", "zoneID", m.ID, nodeID)
case m.zone.ID != 0 && m.zone.ID != zoneID:
return fmt.Errorf("invalid %s: %v ≠ %v", "zoneID", m.zone.ID, zoneID)
case m.zone.ID == 0:
@@ -134,3 +250,14 @@ func (m *Machine) applyZoneNodeID(zoneID, nodeID int) error {
return nil
}
// RemoveWireguardConfig deletes wgN.conf from the machine's
// config directory.
func (m *Machine) RemoveWireguardConfig(ring int) error {
err := m.RemoveFile("wg%v.conf", ring)
if os.IsNotExist(err) {
err = nil
}
return err
}
+27
View File
@@ -3,6 +3,7 @@ package zones
import (
"context"
"net/netip"
"strconv"
"time"
)
@@ -25,6 +26,32 @@ func (m *Machine) updatePublicAddresses() error {
return nil
}
func (m *Machine) init() error {
if err := m.setID(); err != nil {
return err
}
for i := 0; i < RingsCount; i++ {
if err := m.tryReadWireguardKeys(i); err != nil {
return err
}
}
return nil
}
func (m *Machine) setID() error {
zoneName := m.zone.Name
suffix := m.Name[len(zoneName)+1:]
id, err := strconv.ParseInt(suffix, 10, 8)
if err != nil {
return err
}
m.ID = int(id)
return nil
}
func (m *Machine) scan() error {
for i := 0; i < RingsCount; i++ {
if err := m.tryApplyWireguardConfig(i); err != nil {
+30 -44
View File
@@ -14,75 +14,58 @@ const (
MaxNodeID = 0xff - 1
// RingsCount indicates how many wireguard rings we have
RingsCount = 2
// RingZeroPort is the port wireguard uses for ring0
RingZeroPort = 51800
// RingOnePort is the port wireguard uses for ring1
RingOnePort = 51810
)
// RingInfo contains represents the Wireguard endpoint details
// for a Machine on a particular ring
type RingInfo struct {
Ring int `toml:"ring"`
Enabled bool `toml:"enabled,omitempty"`
Keys *wireguard.KeyPair `toml:"keys,omitempty"`
Address netip.Addr `toml:"address,omitempty"`
Ring int `toml:"ring"`
Enabled bool `toml:"enabled,omitempty"`
Keys wireguard.KeyPair `toml:"keys,omitempty"`
}
// Merge attempts to combine two RingInfo structs
func (ri *RingInfo) Merge(alter *RingInfo) error {
switch {
case alter == nil:
return nil
case ri.Ring != alter.Ring:
// different ring
return fmt.Errorf("invalid %s: %v ≠ %v", "ring", ri.Ring, alter.Ring)
case ri.Enabled != alter.Enabled:
// different state
return fmt.Errorf("invalid %s: %v %v", "enabled", ri.Enabled, alter.Enabled)
case !canMergeAddress(ri.Address, alter.Address):
// different address
return fmt.Errorf("invalid %s: %v ≠ %v", "address", ri.Address, alter.Address)
case ri.Enabled && !alter.Enabled:
// can't disable via Merge
return fmt.Errorf("invalid %s: %v %v", "enabled", ri.Enabled, alter.Enabled)
case !canMergeKeyPairs(ri.Keys, alter.Keys):
// incompatible keypairs
return fmt.Errorf("invalid %s: %s ≠ %s", "keys", ri.Keys, alter.Keys)
}
switch {
case ri.Keys == nil:
// assign keypair
ri.Keys = alter.Keys
case alter.Keys != nil:
// fill the gaps on our keypair
if ri.Keys.PrivateKey.IsZero() {
ri.Keys.PrivateKey = alter.Keys.PrivateKey
}
if ri.Keys.PublicKey.IsZero() {
ri.Keys.PublicKey = alter.Keys.PublicKey
}
return ri.unsafeMerge(alter)
}
func (ri *RingInfo) unsafeMerge(alter *RingInfo) error {
// enable via Merge
if alter.Enabled {
ri.Enabled = true
}
if addressEqual(ri.Address, netip.Addr{}) {
// assign address
ri.Address = alter.Address
// fill the gaps on our keypair
if ri.Keys.PrivateKey.IsZero() {
ri.Keys.PrivateKey = alter.Keys.PrivateKey
}
if ri.Keys.PublicKey.IsZero() {
ri.Keys.PublicKey = alter.Keys.PublicKey
}
return nil
}
func canMergeAddress(ip1, ip2 netip.Addr) bool {
var zero netip.Addr
func canMergeKeyPairs(p1, p2 wireguard.KeyPair) bool {
switch {
case addressEqual(ip1, zero) || addressEqual(ip2, zero) || addressEqual(ip1, ip2):
return true
default:
return false
}
}
func addressEqual(ip1, ip2 netip.Addr) bool {
return ip1.Compare(ip2) == 0
}
func canMergeKeyPairs(p1, p2 *wireguard.KeyPair) bool {
switch {
case p1 == nil || p2 == nil:
return true
case !p1.PrivateKey.IsZero() && !p2.PrivateKey.IsZero() && !p1.PrivateKey.Equal(p2.PrivateKey):
return false
case !p1.PublicKey.IsZero() && !p2.PublicKey.IsZero() && !p1.PublicKey.Equal(p2.PublicKey):
@@ -96,6 +79,7 @@ func canMergeKeyPairs(p1, p2 *wireguard.KeyPair) bool {
// Wireguard ring
type RingAddressEncoder struct {
ID int
Port uint16
Encode func(zoneID, nodeID int) (netip.Addr, bool)
Decode func(addr netip.Addr) (zoneID, nodeID int, ok bool)
}
@@ -104,12 +88,14 @@ var (
// RingZero is a wg0 address encoder/decoder
RingZero = RingAddressEncoder{
ID: 0,
Port: RingZeroPort,
Decode: ParseRingZeroAddress,
Encode: RingZeroAddress,
}
// RingOne is a wg1 address encoder/decoder
RingOne = RingAddressEncoder{
ID: 1,
Port: RingOnePort,
Decode: ParseRingOneAddress,
Encode: RingOneAddress,
}
@@ -189,7 +175,7 @@ func RingOneAddress(zoneID, nodeID int) (netip.Addr, bool) {
case !ValidZoneID(zoneID) || !ValidNodeID(nodeID):
return netip.Addr{}, false
default:
a4 := [4]uint8{10, 0, uint8(zoneID << 4), uint8(nodeID)}
a4 := [4]uint8{10, uint8(zoneID << 4), 0, uint8(nodeID)}
return netip.AddrFrom4(a4), true
}
}
+9 -5
View File
@@ -93,8 +93,8 @@ func (m *Zones) scanSort() error {
m.ForEachZone(func(z *Zone) bool {
sort.SliceStable(z.Machines, func(i, j int) bool {
id1 := z.Machines[i].ID()
id2 := z.Machines[j].ID()
id1 := z.Machines[i].ID
id2 := z.Machines[j].ID
return id1 < id2
})
@@ -102,9 +102,9 @@ func (m *Zones) scanSort() error {
})
m.ForEachMachine(func(p *Machine) bool {
sort.SliceStable(p.RingAddresses, func(i, j int) bool {
ri1 := p.RingAddresses[i]
ri2 := p.RingAddresses[j]
sort.SliceStable(p.Rings, func(i, j int) bool {
ri1 := p.Rings[i]
ri2 := p.Rings[j]
return ri1.Ring < ri2.Ring
})
@@ -129,6 +129,10 @@ func (z *Zone) scan() error {
Name: e.Name(),
}
if err := m.init(); err != nil {
return err
}
z.Machines = append(z.Machines, m)
}
}
+33
View File
@@ -0,0 +1,33 @@
package zones
// SyncAll updates all config files
func (m *Zones) SyncAll() error {
for _, fn := range []func() error{
m.SyncAllWireguard,
} {
if err := fn(); err != nil {
return err
}
}
return nil
}
// SyncAllWireguard updates all wireguard config files
func (m *Zones) SyncAllWireguard() error {
var err error
for ring := 0; ring < RingsCount; ring++ {
err = m.PruneWireguardConfig(ring)
if err != nil {
return err
}
err = m.WriteWireguardKeys(ring)
if err != nil {
return err
}
}
return nil
}
+55
View File
@@ -0,0 +1,55 @@
package zones
import "os"
// PruneWireguardConfig removes wgN.conf files of machines with
// the corresponding ring disabled.
func (z *Zone) PruneWireguardConfig(ring int) error {
return pruneWireguardConfig(z, ring)
}
// WriteWireguardKeys rewrites all wgN.{key,pub} files on this zone
func (z *Zone) WriteWireguardKeys(ring int) error {
return writeWireguardKeys(z, ring)
}
// PruneWireguardConfig removes wgN.conf files of machines with
// the corresponding ring disabled on all zones
func (m *Zones) PruneWireguardConfig(ring int) error {
return pruneWireguardConfig(m, ring)
}
// WriteWireguardKeys rewrites all wgN.{key,pub} files
func (m *Zones) WriteWireguardKeys(ring int) error {
return writeWireguardKeys(m, ring)
}
func pruneWireguardConfig(m MachineIterator, ring int) error {
var err error
m.ForEachMachine(func(p *Machine) bool {
_, ok := p.getRingInfo(ring)
if !ok {
err = p.RemoveWireguardConfig(ring)
}
return err != nil
})
return err
}
func writeWireguardKeys(m MachineIterator, ring int) error {
var err error
m.ForEachMachine(func(p *Machine) bool {
err = p.WriteWireguardKeys(ring)
if os.IsNotExist(err) {
// ignore
err = nil
}
return err != nil
})
return err
}
+26 -4
View File
@@ -3,17 +3,29 @@ package zones
import (
"io/fs"
"os"
"path/filepath"
"github.com/hack-pad/hackpadfs/os"
"darvaza.org/resolver"
)
var (
_ MachineIterator = (*Zone)(nil)
_ MachineIterator = (*Zones)(nil)
)
// A MachineIterator is a set of Machines we can iterate on
type MachineIterator interface {
ForEachMachine(func(*Machine) bool)
}
// Zone represents one zone in a cluster
type Zone struct {
zones *Zones
ID int
Name string
ID int `toml:"id"`
Name string `toml:"name"`
Machines []*Machine `toml:"machines"`
}
@@ -104,5 +116,15 @@ func NewFS(dir fs.FS, domain string) (*Zones, error) {
// New builds a [Zones] tree using the given directory
func New(dir, domain string) (*Zones, error) {
return NewFS(os.DirFS(dir), domain)
dir, err := filepath.Abs(dir)
if err != nil {
return nil, err
}
base, err := os.NewFS().Sub(dir[1:])
if err != nil {
return nil, err
}
return NewFS(base, domain)
}