summaryrefslogtreecommitdiff
path: root/playbooks.d/vpn-wireguard/playbook.bash
blob: ae2167df97a9cdf33971f20862cc5b4372409cfc (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/env bash

# shellcheck disable=SC2034

BASHTARD_PLAYBOOK_VARS[$BASHTARD_PLAYBOOK.ip]="required"

playbook_add() {
	local data

	data="$(playbook_path "data")"

	pkg install wireguard

	# If there's no data directory yet, make it with a proper gitignore to ensure
	# the private key is not included
	if [[ ! -d "$data" ]]
	then
		mkdir -pv -- "$data"
		cat <<-EOF >> "$data/.gitignore"
			privkey
			EOF
	fi

	# Generate the private key for this machine
	( umask 077 && wg genkey > "$data/privkey" )

	# Generate the peerfile for this machine
	file_template "peer" \
		endpoint="$(config "$BASHTARD_PLAYBOOK.endpoint")" \
		ip="$(config "$BASHTARD_PLAYBOOK.ip")" \
		port="$(config "$BASHTARD_PLAYBOOK.port" "52345")" \
		pubkey="$(wg pubkey < "$data/privkey")" \
		> "$data/${BASHTARD_PLATFORM[fqdn]}"

	# Run the sync stage to make sure all the configuration files are written as
	# desired
	playbook_sync

	# TODO: Enable the wireguard interface
	systemctl enable --now wg-quick@wg$(config "$BASTHARD_PLAYBOOK.interface_id" "0").service
}

playbook_sync() {
	local data
	local wgconf

	data="$(playbook_path "data")"
	wgconf="$(config "fs.etcdir")/wireguard/wg$(config "$BASHTARD_PLAYBOOK.interface_id" "0").conf"

	# Create the wireguard config directory
	mkdir -pv "$(config "fs.etcdir")/wireguard"

	# Write the Interface section
	file_template "interface" \
		ip="$(config "$BASHTARD_PLAYBOOK.ip")" \
		port="$(config "$BASHTARD_PLAYBOOK.port" "52345")" \
		privkey="$(cat "$data/privkey")" \
		> "$wgconf"

	info "$BASHTARD_PLAYBOOK" "Generating wireguard configuration at $wgconf"

	# Include peerfiles for all other machines
	for path in "$data"/*
	do
		local peer="$(basename "$path")"

		[[ "$peer" == "privkey" ]] && continue
		[[ "$peer" == "${BASHTARD_PLATFORM[fqdn]}" ]] && continue

		# Append all peers, but prepend them with newlines so the resulting file
		# looks a little nicer
		printf "\n" >> "$wgconf"
		cat "$path" >> "$wgconf"
	done

	# TODO: Refresh the wireguard interface
	systemctl reload wg-quick@wg$(config "$BASTHARD_PLAYBOOK.interface_id" "0").service
}

playbook_del() {
	systemctl disable --now wg-quick@wg$(config "$BASTHARD_PLAYBOOK.interface_id" "0").service
	rm -f -- "$(config "fs.etcdir")/wireguard/wg$(config "$BASHTARD_PLAYBOOK.interface_id" "0").conf"
	pkg uninstall wireguard
}