summaryrefslogtreecommitdiff
path: root/internal/wireguard/wireguard.go
blob: cd9c01106e80f13f256e8842715d905085c23aac (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
// Package wireguard implements a few helpers for the WireGuard protocol
package wireguard

import (
	"errors"

	"herkulessi.de/git/eduvpn-common/internal/wireguard/ini"
	"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)

// Config places a WireGuard key `key` inside of the WireGuard config `cfg`
func Config(cfg string, key *wgtypes.Key) (string, error) {
	// the key is nil if the client does not accept WireGuard
	if key == nil {
		return "", errors.New("the server sent us a WireGuard profile but the client does not accept WireGuard")
	}

	// first parse the config
	secs := ini.Parse(cfg)
	if secs.Empty() {
		return "", errors.New("parsed ini is empty")
	}

	// find the interface section
	// and set the private key
	is, err := secs.Section("Interface")
	if err != nil {
		return "", err
	}
	is.AddOrReplaceKeyValue("PrivateKey", key.String())
	return secs.String(), nil
}