Compare commits

...

14 Commits

Author SHA1 Message Date
amery 07fd7b450a zones: env: use SetGateway()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-23 20:28:33 +00:00
amery 61d1ea85ee zones: SetGateway [WIP]
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-23 20:28:33 +00:00
amery 87258c7a9e zones: writeRingInfo [WIP]
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-23 20:28:33 +00:00
amery c5c99db732 zones: introduce Machine.createRingInfo()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-23 20:14:35 +00:00
amery 7258b4a20e zones: Machine.IsGateway()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-23 20:14:35 +00:00
amery 15f28fa7c8 zones: Machine.CreateFile() and Machine.CreateTruncFile()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-23 20:13:20 +00:00
amery 6838d00a0a zones: introduce Machine.OpenFile()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-23 20:12:39 +00:00
amery e723066f7b zones: introduce Machine.RemoveFile()
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-23 19:36:26 +00:00
amery 3c6dee543a zones: switch to using hackpadfs/os.FS as the standard os.FS is incomplete
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-23 19:14:56 +00:00
amery 75d7b4389a zones: move Machine.ReadFile to a dedicated machine_file.go
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-08-23 18:12:06 +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
9 changed files with 394 additions and 60 deletions
+2
View File
@@ -8,8 +8,10 @@ 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
)
+4
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=
+4 -4
View File
@@ -31,13 +31,13 @@ func (f *Config) Peers() int {
// 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 +135,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 +162,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
+151 -15
View File
@@ -2,35 +2,171 @@ package wireguard
import (
"bytes"
"crypto/rand"
"encoding/base64"
"errors"
"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 []byte
// PublicKey is a binary Wireguard Public Key
PublicKey []byte
)
func (key PrivateKey) String() string {
return encodeKey(key)
}
func (pub PublicKey) String() string {
return encodeKey(pub)
}
// IsZero tells if the key hasn't been set
func (k BinaryKey) IsZero() bool {
return len(k) == 0
func (key PrivateKey) IsZero() bool {
return len(key) == 0
}
// 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 {
return len(pub) == 0
}
// 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)
return b, err
}
// PublicKeyFromBase64 decodes a base64-based string into
// a [PublicKey]
func PublicKeyFromBase64(data string) (PublicKey, error) {
b, err := decodeKey(data, PublicKeySize)
return b, err
}
func encodeKey(b []byte) string {
switch {
case len(b) == 0:
return ""
default:
return base64.StdEncoding.EncodeToString(b)
}
}
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 {
return []byte{}, 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 {
if len(key) != PrivateKeySize {
return []byte{}
}
out := [PublicKeySize]byte{}
in := (*[PrivateKeySize]byte)(key)
curve25519.ScalarBaseMult(&out, in)
return out[:]
}
// 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) {
key, err := NewPrivateKey()
if err != nil {
return nil, err
}
out := &KeyPair{
PrivateKey: key,
PublicKey: key.Public(),
}
return out, nil
}
+30 -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,32 @@ func genEnvZoneNodes(z *Zone) string {
}
return strings.Join(s, " ")
}
func getRingZeroGatewayID(z *Zone) (int, error) {
var gatewayID int
var first *Machine
z.ForEachMachine(func(p *Machine) bool {
nodeID := p.ID()
if first == nil {
first = p
}
if p.IsGateway() {
gatewayID = nodeID
}
return gatewayID != 0
})
if gatewayID == 0 {
gatewayID = first.ID()
if err := first.SetGateway(true); err != nil {
return gatewayID, err
}
}
return gatewayID, nil
}
+23 -20
View File
@@ -1,10 +1,7 @@
package zones
import (
"fmt"
"io/fs"
"net/netip"
"path/filepath"
"strconv"
"strings"
"sync"
@@ -61,28 +58,34 @@ 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...)
// IsGateway tells if the Machine is a ring0 gateway
func (m *Machine) IsGateway() bool {
m.mu.Lock()
defer m.mu.Unlock()
return fs.ReadFile(base, fullName)
}
func (m *Machine) getFilename(name string, args ...any) string {
if len(args) > 0 {
name = fmt.Sprintf(name, args...)
if ri, found := m.getRingInfo(0); found {
return ri.Enabled
}
s := []string{
m.zone.Name,
m.Name,
name,
}
return filepath.Join(s...)
return false
}
// SetGateway enables/disables a Machine ring0 integration
func (m *Machine) SetGateway(enabled bool) error {
m.mu.Lock()
defer m.mu.Unlock()
ri, found := m.getRingInfo(0)
switch {
case !found && !enabled:
return nil
case !found:
return m.createRingInfo(0, true)
default:
ri.Enabled = enabled
return m.writeRingInfo(ri)
}
}
func (m *Machine) getPeerByName(name string) (*Machine, bool) {
return m.zone.zones.GetMachineByName(name)
}
+63
View File
@@ -0,0 +1,63 @@
package zones
import (
"fmt"
"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) (fs.File, error) {
return m.OpenFile(name, os.O_RDWR|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) (fs.File, error) {
return m.OpenFile(name, os.O_RDWR|os.O_CREATE, args...)
}
// 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)
}
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...)
}
+84
View File
@@ -3,6 +3,7 @@ package zones
import (
"bytes"
"fmt"
"io/fs"
"os"
"darvaza.org/core"
@@ -134,3 +135,86 @@ func (m *Machine) applyZoneNodeID(zoneID, nodeID int) error {
return nil
}
func (m *Machine) createRingInfo(ring int, enabled bool) error {
keys, err := wireguard.NewKeyPair()
if err != nil {
return err
}
ri := &RingInfo{
Ring: ring,
Enabled: enabled,
Keys: keys,
}
err = m.applyRingInfo(ring, ri)
if err != nil {
return err
}
return m.writeRingInfo(ri)
}
func (m *Machine) writeRingInfo(ri *RingInfo) error {
var err error
if m == nil || ri == nil {
return fs.ErrInvalid
}
err = m.writeRingInfoPrivate(ri.Ring, ri.Keys.PrivateKey)
if err != nil {
return err
}
err = m.writeRingInfoPublic(ri.Ring, ri.Keys.PublicKey)
if err != nil {
return err
}
if !ri.Enabled {
return m.deleteRingInfoConf(ri.Ring)
}
return m.writeRingInfoConf(ri.Ring, ri.Keys.PrivateKey)
}
func (m *Machine) writeRingInfoPrivate(ring int, _ wireguard.PrivateKey) error {
f, err := m.CreateTruncFile("wg%v.key", ring)
if err != nil {
return err
}
defer f.Close()
return nil
}
func (m *Machine) writeRingInfoPublic(ring int, _ wireguard.PublicKey) error {
f, err := m.CreateTruncFile("wg%v.pub", ring)
if err != nil {
return err
}
defer f.Close()
return nil
}
func (m *Machine) writeRingInfoConf(ring int, _ wireguard.PrivateKey) error {
f, err := m.CreateTruncFile("wg%v.conf", ring)
if err != nil {
return err
}
defer f.Close()
return nil
}
func (m *Machine) deleteRingInfoConf(ring int) error {
err := m.RemoveFile("wg%v.conf", ring)
switch err {
case os.ErrNotExist:
return nil
default:
return err
}
}
+33 -2
View File
@@ -3,7 +3,8 @@ package zones
import (
"io/fs"
"os"
"github.com/hack-pad/hackpadfs/os"
"darvaza.org/resolver"
)
@@ -32,6 +33,31 @@ func (z *Zone) ForEachMachine(fn func(*Machine) bool) {
}
}
// SetGateway configures a machine to be the zone's ring0 gateway
func (z *Zone) SetGateway(gatewayID int, enabled bool) error {
var err error
var found bool
z.ForEachMachine(func(p *Machine) bool {
if p.ID() == gatewayID {
found = true
err = p.SetGateway(enabled)
return true
}
return false
})
switch {
case err != nil:
return err
case !found:
return fs.ErrNotExist
default:
return nil
}
}
// Zones represents all zones in a cluster
type Zones struct {
dir fs.FS
@@ -104,5 +130,10 @@ 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)
base, err := os.NewFS().Sub(dir)
if err != nil {
return nil, err
}
return NewFS(base, domain)
}