blob: cc6c5775681db67de9656936ce4b26059d6f8bdb (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
// Package wireguard implements a few helpers for the WireGuard protocol
package wireguard
import (
"fmt"
"regexp"
"github.com/go-errors/errors"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
// GenerateKey generates a WireGuard private key using wgctrl
// It returns an error if key generation failed.
func GenerateKey() (wgtypes.Key, error) {
key, err := wgtypes.GeneratePrivateKey()
if err != nil {
return key, errors.WrapPrefix(err, "failed generating WireGuard key", 0)
}
return key, nil
}
// ConfigAddKey takes the WireGuard configuration and adds the PrivateKey to the right section
// FIXME: Instead of doing a regex replace, decide if we should use a parser.
func ConfigAddKey(config string, key wgtypes.Key) string {
interfaceSection := "[Interface]"
InterfaceSectionEscaped := regexp.QuoteMeta(interfaceSection)
// (?m) enables multi line mode
// ^ match from beginning of line
// $ match till end of line
// So it matches [Interface] section exactly
InterfaceRe := regexp.MustCompile(fmt.Sprintf("(?m)^%s$", InterfaceSectionEscaped))
toReplace := fmt.Sprintf("%s\nPrivateKey = %s", interfaceSection, key.String())
return InterfaceRe.ReplaceAllString(config, toReplace)
}
|