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,14 +203,28 @@ 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
createPrivKey := func() error {
slog.Info("Creating a private key")
privateKey, err = wgtypes.GeneratePrivateKey()
if err != nil { if err != nil {
return cli.Exit(err, 1) return cli.Exit(err, 1)
} }
slog.Debug(fmt.Sprintf("Private key: %s", privateKey.String()))
return nil
}
if PrivateKeyPath == "" {
err := createPrivKey()
if err != nil {
return err
}
} else {
privKeyFile, err := os.Open(PrivateKeyPath)
defer privKeyFile.Close() defer privKeyFile.Close()
slog.Debug("Keyfile opened for reading") if err != nil {
return cli.Exit(err, 1)
}
privateKeyStr := make([]byte, 45) privateKeyStr := make([]byte, 45)
n, err := privKeyFile.Read(privateKeyStr) n, err := privKeyFile.Read(privateKeyStr)
if err != nil { if err != nil {
@ -222,11 +235,13 @@ func setup(ctx *cli.Context) error {
} }
slog.Debug(fmt.Sprintf("Read %d bytes from keyfile", n)) slog.Debug(fmt.Sprintf("Read %d bytes from keyfile", n))
privateKey, err := wgtypes.ParseKey(string(privateKeyStr)) privateKey, err = wgtypes.ParseKey(string(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") 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
} }
} }
} }