From b16c648f2c2c1e27138d8ada013a2bbdde52dd45 Mon Sep 17 00:00:00 2001 From: Alejandro Mery Date: Wed, 23 Aug 2023 21:03:03 +0000 Subject: [PATCH] zones: introduce Machine.GetWireguardKeys() Signed-off-by: Alejandro Mery --- pkg/zones/machine_rings.go | 51 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/pkg/zones/machine_rings.go b/pkg/zones/machine_rings.go index 2c59fb0..8a80748 100644 --- a/pkg/zones/machine_rings.go +++ b/pkg/zones/machine_rings.go @@ -10,6 +10,57 @@ 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 + key wireguard.PrivateKey + pub wireguard.PublicKey + ) + + data, err = m.ReadFile("wg%v.key", ring) + if err != nil { + // failed to read + return nil, err + } + + key, err = wireguard.PrivateKeyFromBase64(string(data)) + if err != nil { + // bad key + err = core.Wrapf(err, "wg%v.key", ring) + return nil, 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 nil, err + default: + // good read + pub, err = wireguard.PublicKeyFromBase64(string(data)) + if err != nil { + // bad key + err = core.Wrapf(err, "wg%v.pub", ring) + return nil, err + } + } + + kp := &wireguard.KeyPair{ + PrivateKey: key, + PublicKey: pub, + } + + if err = kp.Validate(); err != nil { + return nil, err + } + + return kp, nil +} + // GetWireguardConfig reads a wgN.conf file func (m *Machine) GetWireguardConfig(ring int) (*wireguard.Config, error) { data, err := m.ReadFile("wg%v.conf", ring)