summaryrefslogtreecommitdiff
path: root/internal/wireguard.go
blob: 4ec12bde9cd74198d81441e9b191264150c40aa0 (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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package internal

import (
	"fmt"
	"regexp"

	"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)

func wireguardGenerateKey() (wgtypes.Key, error) {
	key, error := wgtypes.GeneratePrivateKey()
	return key, error
}

// FIXME: Instead of doing a regex replace, decide if we should use a parser
func wireguardConfigAddKey(config string, key wgtypes.Key) string {
	interface_section := "[Interface]"
	interface_section_escaped := regexp.QuoteMeta(interface_section)

	// (?m) enables multi line mode
	// ^ match from beginning of line
	// $ match till end of line
	// So it matches [Interface] section exactly
	interface_re := regexp.MustCompile(fmt.Sprintf("(?m)^%s$", interface_section_escaped))
	to_replace := fmt.Sprintf("%s\nPrivateKey = %s", interface_section, key.String())
	return interface_re.ReplaceAllString(config, to_replace)
}

func (server *Server) WireguardGetConfig() (string, error) {
	profile_id := server.Profiles.Current
	wireguardKey, wireguardErr := wireguardGenerateKey()

	if wireguardErr != nil {
		return "", wireguardErr
	}

	wireguardPublicKey := wireguardKey.PublicKey().String()
	configWireguard, _, configErr := server.APIConnectWireguard(profile_id, wireguardPublicKey)

	if configErr != nil {
		return "", configErr
	}

	// FIXME: Store expiry
	// This needs the go code a way to identify a connection
	// Use the uuid of the connection e.g. on Linux
	// This needs the client code to call the go code

	configWireguardKey := wireguardConfigAddKey(configWireguard, wireguardKey)

	return configWireguardKey, nil
}