Skip to content

Instantly share code, notes, and snippets.

@fuero
Created January 23, 2024 15:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fuero/56811ada9d849cfc462da3fd07e8f05a to your computer and use it in GitHub Desktop.
Save fuero/56811ada9d849cfc462da3fd07e8f05a to your computer and use it in GitHub Desktop.
Refresh config from wirehub
#!/bin/bash
set -euo pipefail
IF=<if>
URL="https://wirehub.org/<user>/n/<net>/device/<id>/download?invite_code=<code>"
TMPFILE="$(mktemp)"
SPLITDIR="$(mktemp -d)"
DEST=/etc/wireguard/"$IF".conf
cleanup() {
rm -f "${TMPFILE}"
rm -f "${TMPFILE}".sha256sum
rm -rf "${SPLITDIR}"
}
trap cleanup EXIT INT
# The generated config is missing the device's private key, as the decryption is done
# with client-side javascript only.
# Thus, the key has to be kept locally is replaced via the sed command below
curl -s \
"$URL" \
| sed -re '/Interface|(Public|Private)Key/s/^# //' -e '3,4s/^# //' -e '4d' -e "s,PrivateKey = .*,PrivateKey = $(cat ${DEST/.conf/.sk})," \
> "$TMPFILE"
# Check for file changes
cat > "${TMPFILE}.sha256sum" << EOF
$(cat ${DEST}.sha256sum) ${TMPFILE}
EOF
if ! sha256sum -c "${TMPFILE}.sha256sum" > /dev/null 2>&1
then
# A peer might be missing its public key, making the configuration illegal.
# For now, we crash if a peer is invalid.
(
cd "${SPLITDIR}"
csplit ${TMPFILE} '/^$/' '{*}' > /dev/null 2>&1
if [[ $(grep -c "\[Peer\]" xx* | grep -v ":0" | wc -l) != $(grep -c "PublicKey" ${TMPFILE}) ]]
then
printf "Some peer is missing a public key, removing...!\n"
invalid_peers=$( \
grep -c PublicKey $(grep -c "\[Peer\]" xx* | grep -v ":0" | cut -d ':' -f1) \
| grep ":0" | cut -d ':' -f1 \
)
cat $invalid_peers
cat $( \
ls -I $( \
echo -n "$invalid_peers" | sed -e ':a; N; $!ba; s/\n/","/g' -e 's/^/{"/' -e 's/$/"}/' \
) \
) > "${DEST}"
else
cp -f "${TMPFILE}" "${DEST}"
fi
)
restorecon "$DEST"
printf "Updating checksum\n"
sha256sum "$DEST" | cut -d ' ' -f1 > "$DEST.sha256sum"
printf "Restarting interface\n"
systemctl restart "wg-quick@$IF"
else
printf "Config doesn't need an update\n"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment