Skip to content

Instantly share code, notes, and snippets.

@Gowee
Last active March 9, 2024 01:29
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Gowee/e756f925cfcbd5ab32d564ee3c795786 to your computer and use it in GitHub Desktop.
Save Gowee/e756f925cfcbd5ab32d564ee3c795786 to your computer and use it in GitHub Desktop.
DNS-01 challenge hook script of uacme for Cloudflare
#!/bin/sh
# Copyright (C) 2020 Michel Stam <michel@reverze.net>
# Copyright (C) 2021 Hung-I Wang <whygowe@gmail.com>
#
# The script is adatped from:
# https://github.com/ndilieto/uacme/blob/5edec0eea1bcf6f454ec1787297c2408c2f2e97a/nsupdate.sh
#
# Licensed under the the GNU General Public License <http://www.gnu.org/licenses/>.
# The script is meant to be used as a hook script of uacme to update TXT records for acme challenges.
# Instead of relying on IETF RFC2136, it talks to cfapi-ddns-worker.js which is a wrapper around Cloudflare API:
# https://gist.github.com/Gowee/8c3e65b80767b915e0199908e5d7a916
# API Config
API_ENDPOINT="https://foo.bar.workers.dev/"
API_TOKEN="TOKEN_FOR_THE_DOMAIN_SPECIFIED_IN_THE_WORKER_SCRIPT"
# Arguments
METHOD=$1
TYPE=$2
IDENT=$3
TOKEN=$4
AUTH=$5
ns_ispresent()
{
local fqhn="$1"
local expect="$2"
local resp
resp=$(curl -fsSH "accept: application/dns-json" "https://cloudflare-dns.com/dns-query?name=${fqhn}&type=TXT")
if echo "$resp" | grep -q "$expect"; then
return 0
else
return 1
fi
}
ns_doupdate()
{
local fqhn="$1"
local challenge="$2"
if [ -n "${challenge}" ]; then
curl -fsS "${API_ENDPOINT}upsert/${API_TOKEN}/${fqhn}/TXT/${challenge}"
# TODO: --fail-with-body
else
curl -fsS "${API_ENDPOINT}delete/${API_TOKEN}/${fqhn}/TXT/${challenge}"
# TODO: --fail-with-body
fi
return $?
}
ns_update()
{
local fqhn="$1"
local challenge="$2"
local count=0
local res
res=1
while [ $res -ne 0 ]; do
if [ $count -eq 0 ]; then
ns_doupdate "$fqhn" "$challenge"
res=$?
[ $res -eq 0 ] || break
else
sleep 1
fi
count=$(((count + 1) % 5))
ns_ispresent "$fqhn" "$challenge"
res=$?
done
return $res
}
ARGS=5
E_BADARGS=85
if [ $# -ne "$ARGS" ]; then
echo "Usage: $(basename "$0") method type ident token auth" 1>&2
exit $E_BADARGS
fi
case "$METHOD" in
"begin")
case "$TYPE" in
dns-01)
ns_update "_acme-challenge.$IDENT" "$AUTH"
exit $?
;;
*)
exit 1
;;
esac
;;
"done"|"failed")
case "$TYPE" in
dns-01)
ns_update "_acme-challenge.$IDENT"
exit $?
;;
*)
exit 1
;;
esac
;;
*)
echo "$0: invalid method" 1>&2
exit 1
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment