cli: allow generating private key on startup

Signed-off-by: HeshamTB <hishaminv@gmail.com>
This commit is contained in:
HeshamTB 2024-03-18 01:17:02 +03:00
parent 78b61aede4
commit 44961e91dc
Signed by: Hesham
GPG Key ID: 74876157D199B09E

View File

@ -114,7 +114,6 @@ func createCliApp() *cli.App {
privateKeyFileFlag := cli.PathFlag{ privateKeyFileFlag := cli.PathFlag{
Name: "private-key", Name: "private-key",
Required: true,
Usage: "Path to file with private key", Usage: "Path to file with private key",
Destination: &PrivateKeyPath, Destination: &PrivateKeyPath,
} }
@ -204,29 +203,45 @@ func setup(ctx *cli.Context) error {
} }
slog.Info("Node UUID: " + uuid.String()) slog.Info("Node UUID: " + uuid.String())
privKeyFile, err := os.Open(PrivateKeyPath) var privateKey wgtypes.Key
if err != nil { createPrivKey := func() error {
return cli.Exit(err, 1) slog.Info("Creating a private key")
privateKey, err = wgtypes.GeneratePrivateKey()
if err != nil {
return cli.Exit(err, 1)
}
slog.Debug(fmt.Sprintf("Private key: %s", privateKey.String()))
return nil
} }
defer privKeyFile.Close()
slog.Debug("Keyfile opened for reading")
if PrivateKeyPath == "" {
err := createPrivKey()
if err != nil {
return err
}
} else {
privKeyFile, err := os.Open(PrivateKeyPath)
defer privKeyFile.Close()
if err != nil {
return cli.Exit(err, 1)
}
privateKeyStr := make([]byte, 45)
n, err := privKeyFile.Read(privateKeyStr)
if err != nil {
return cli.Exit(err, 1)
}
if n != 45 {
slog.Warn("Private key length did not math the expected 45!")
}
slog.Debug(fmt.Sprintf("Read %d bytes from keyfile", n))
privateKeyStr := make([]byte, 45) privateKey, err = wgtypes.ParseKey(string(privateKeyStr))
n, err := privKeyFile.Read(privateKeyStr) slog.Debug("Keyfile opened for reading")
if err != nil { if err != nil {
return cli.Exit(err, 1) return cli.Exit(err, 1)
}
slog.Debug("Private key parsed and is correct")
} }
if n != 45 {
slog.Warn("Private key length did not math the expected 45!")
}
slog.Debug(fmt.Sprintf("Read %d bytes from keyfile", n))
privateKey, err := wgtypes.ParseKey(string(privateKeyStr))
if err != nil {
return cli.Exit(err, 1)
}
slog.Debug("Private key parsed and is correct")
wg, err := hvpnnode3.InitWGLink( wg, err := hvpnnode3.InitWGLink(
InterfaceName, InterfaceName,
@ -366,6 +381,7 @@ func handleStdin(c chan struct{}) {
in = strings.ReplaceAll(in, "\n", "") in = strings.ReplaceAll(in, "\n", "")
if in == "q" || in == "exit" { if in == "q" || in == "exit" {
c <- struct{}{} c <- struct{}{}
break
} }
} }
} }