diff options
Diffstat (limited to 'playbooks.d/vpn-wireguard/playbook.bash')
-rw-r--r-- | playbooks.d/vpn-wireguard/playbook.bash | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/playbooks.d/vpn-wireguard/playbook.bash b/playbooks.d/vpn-wireguard/playbook.bash new file mode 100644 index 0000000..ae2167d --- /dev/null +++ b/playbooks.d/vpn-wireguard/playbook.bash @@ -0,0 +1,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 +} |