#!/usr/bin/env bash # # SendPier webhooks — check an X-SendPier-Signature by hand. # # Requirements: bash, openssl. # # Usage: # export SENDPIER_WEBHOOK_SECRET='whsec_...' # from the webhook page # ./verify-webhook-signature.sh 't=1755172800,v1=1f3a...' ./payload.json # # This is a debugging aid, not a receiver: it is what you run when a delivery # in the log was refused and you want to know whether the signature or your own # code was at fault. Real receivers belong in your application -- see # webhook-receiver.php, webhook-receiver.mjs or webhook_receiver.py, which also # compare in constant time. # # After you renew a secret, the header carries two signatures for 24 hours: # 't=1755172800,v1=,v1=' # The script collects every v1 and reports the request as valid if any one of # them matches the secret you set. # # The signature is HMAC-SHA256 over the literal text ".", keyed # with the secret of that endpoint. The body must be the bytes we sent: a # re-serialised object shifts a space or a key order and the signature no longer # matches. set -euo pipefail TOLERANCE_SECONDS=300 : "${SENDPIER_WEBHOOK_SECRET:?set SENDPIER_WEBHOOK_SECRET to the secret of this endpoint}" header="${1:-}" file="${2:-}" if [ -z "$header" ] || [ -z "$file" ]; then echo "usage: $0 't=,v1=' " >&2 exit 64 fi if [ ! -r "$file" ]; then echo "cannot read ${file}" >&2 exit 66 fi timestamp='' signatures=() # The header is a comma separated list of key=value pairs. Reading it this way # keeps working when a renewed secret adds a second v1 value. IFS=',' read -ra parts <<<"$header" for part in "${parts[@]}"; do case "$part" in t=*) timestamp="${part#t=}" ;; v1=*) signatures+=("${part#v1=}") ;; esac done if [ -z "$timestamp" ] || [ "${#signatures[@]}" -eq 0 ]; then echo 'header does not carry both t and v1' >&2 exit 1 fi age=$(( $(date +%s) - timestamp )) [ "$age" -lt 0 ] && age=$(( -age )) if [ "$age" -gt "$TOLERANCE_SECONDS" ]; then # Without this check an intercepted request stays replayable for as long as # the secret lives: the signature itself never expires. echo "signature is ${age}s old, over the ${TOLERANCE_SECONDS}s tolerance" >&2 exit 1 fi expected=$( { printf '%s.' "$timestamp"; cat "$file"; } \ | openssl dgst -sha256 -hmac "$SENDPIER_WEBHOOK_SECRET" -r \ | cut -d' ' -f1 ) # Check every v1 value; one match is enough. This is a debugging aid, so a # plain comparison is fine here -- the receivers compare in constant time. matched=0 for signature in "${signatures[@]}"; do if [ "$expected" = "$signature" ]; then matched=1 fi done if [ "$matched" -ne 1 ]; then echo 'signature does not match' >&2 echo "expected ${expected}" >&2 exit 1 fi echo 'signature is valid'