Skip to content

Instantly share code, notes, and snippets.

@jfisbein
Forked from wikrie/fritzbox-cert-update.sh
Last active February 1, 2020 18:15
Show Gist options
  • Save jfisbein/fd6b85bb356149a3a0a99fbcf97d9dcf to your computer and use it in GitHub Desktop.
Save jfisbein/fd6b85bb356149a3a0a99fbcf97d9dcf to your computer and use it in GitHub Desktop.
Fritzbox Fritz!Box AVM SSL Letsencrypt automatically update
#!/bin/bash
MIN_EXPECTED_ARGS=4
if [ $# -lt $MIN_EXPECTED_ARGS ]; then
echo "Script to update the FritzBox SSL certificate"
echo ""
echo "Expected at least ${MIN_EXPECTED_ARGS} args"
echo ""
echo "Usage: $(basename "${0}") {username} {password} {cert-key-file} {cert-fullchain-file} [cert-password] [fritzbox-host]"
echo " - [cert-password] only needed if the {cert-key-file} is protected by a password"
echo " - If not set [fritzbox-host] defaults to 'http://fritz.box'"
echo ""
echo "Example: $(basename "${0}") peter mysecret /etc/letsencrypt/live/domain.tld/privkey.pem /etc/letsencrypt/live/domain.tld/fullchain.pem domainsecret http://fritz.box"
exit 1
fi
# parameters
USERNAME="$1"
PASSWORD="$2"
CERTKEYFILE="$3"
CERTFULLCHAINFILE="$4"
CERTPASSWORD="$5"
HOST="${6:-http://fritz.box}"
# make and secure a temporary file
TMP="$(mktemp -t XXXXXX)"
chmod 600 "${TMP}"
# login to the box and get a valid SID
CHALLENGE=$(wget --quiet -O - "${HOST}/login_sid.lua" | sed -e 's/^.*<Challenge>//' -e 's/<\/Challenge>.*$//')
HASH="$(echo -n "${CHALLENGE}-${PASSWORD}" | uconv --from-code ASCII --to-code UTF16LE |md5sum|awk '{print $1}')"
SID=$(wget --quiet -O - "${HOST}/login_sid.lua?sid=0000000000000000&username=${USERNAME}&response=${CHALLENGE}-${HASH}"| sed -e 's/^.*<SID>//' -e 's/<\/SID>.*$//')
# generate our upload request
BOUNDARY="---------------------------$(date +%Y%m%d%H%M%S)"
printf -- "--%s\r\n" "${BOUNDARY}" >> "${TMP}"
printf "Content-Disposition: form-data; name=\"sid\"\r\n\r\n%s\r\n" "${SID}" >> "${TMP}"
printf -- "--%s\r\n" "${BOUNDARY}" >> "${TMP}"
printf "Content-Disposition: form-data; name=\"BoxCertPassword\"\r\n\r\n%s\r\n" "${CERTPASSWORD}" >> "${TMP}"
printf -- "--%s\r\n" "${BOUNDARY}" >> "${TMP}"
printf "Content-Disposition: form-data; name=\"BoxCertImportFile\"; filename=\"BoxCert.pem\"\r\n" >> "${TMP}"
printf "Content-Type: application/octet-stream\r\n\r\n" >> "${TMP}"
cat "${CERTKEYFILE}" >> "${TMP}"
cat "${CERTFULLCHAINFILE}" >> "${TMP}"
printf "\r\n" >> "${TMP}"
printf -- "--%s--" "${BOUNDARY}" >> "${TMP}"
# upload the certificate to the box
wget --quiet -O - "${HOST}/cgi-bin/firmwarecfg" --header="Content-type: multipart/form-data boundary=${BOUNDARY}" --post-file "${TMP}" | grep "SSL"
# clean up
rm -f "${TMP}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment