Skip to content

Instantly share code, notes, and snippets.

@stefanpejcic
Created July 9, 2024 16:35
Show Gist options
  • Save stefanpejcic/e229cb6911b39776cfe7a11991ee073f to your computer and use it in GitHub Desktop.
Save stefanpejcic/e229cb6911b39776cfe7a11991ee073f to your computer and use it in GitHub Desktop.
Setup DNSSEC for BIND9 *(OPENPANEL)
#!/bin/sh
# Variables
PDIR=$(pwd)
ZONEDIR="/var/cache/bind"
ZONE=$1
ZONEFILE="/etc/bind/zones/${ZONE}.zone"
CONFIG_FILE="/etc/bind/named.conf.local"
DNSSERVICE="bind9"
# Functions
error_exit() {
echo "Error: $1"
cd $PDIR
exit 1
}
sign_and_reload() {
cd $ZONEDIR && dnssec-signzone -A -3 $(head -c 1000 /dev/random | sha1sum | cut -b 1-16) -N INCREMENT -P -o ${ZONE} -t ${ZONEFILE} >/dev/null 2>&1 || error_exit "Failed to sign the zone file"
service $DNSSERVICE reload >/dev/null 2>&1 || error_exit "Failed to reload the DNS service"
}
setup_zone() {
# Check if the zone file exists
if [ ! -f "$ZONEFILE" ]; then
error_exit "Zone file $ZONEFILE does not exist"
fi
# Change to the zone directory
cd $ZONEDIR >/dev/null 2>&1 || error_exit "Failed to change directory to $ZONEDIR"
# Generate key pairs
dnssec-keygen -a NSEC3RSASHA1 -b 2048 -n ZONE ${ZONE} >/dev/null 2>&1 || error_exit "Failed to generate 2048-bit key"
dnssec-keygen -a NSEC3RSASHA1 -b 4096 -n ZONE ${ZONE} >/dev/null 2>&1 || error_exit "Failed to generate 4096-bit key"
# Allow bind group to read the keys
chgrp bind K${ZONE}.* >/dev/null 2>&1 || error_exit "Failed to change group of key files"
chmod g=r,o= K${ZONE}.* >/dev/null 2>&1 || error_exit "Failed to set permissions on key files"
# Include keys to the zone file
for key in K${ZONE}.*.key; do
echo "\$INCLUDE $key" >> ${ZONEFILE}
done
# Sign the zone file and reload DNS service
cd $ZONEDIR >/dev/null 2>&1 || error_exit "Failed to change directory to $ZONEDIR"
dnssec-signzone -A -3 $(head -c 1000 /dev/random | sha1sum | cut -b 1-16) -N INCREMENT -P -o ${ZONE} -t ${ZONEFILE} >/dev/null 2>&1 || error_exit "Failed to sign the zone file"
# Use sed to append .signed to the filename on the specific line containing the zone
sed -i "/zone \"${ZONE}\"/,/file/s|\(file \"/etc/bind/zones/${ZONE}\.zone\)|\1.signed|" "$CONFIG_FILE" >/dev/null 2>&1 || error_exit "Failed to update the config file"
# relaod service
service $DNSSERVICE reload >/dev/null 2>&1 || error_exit "Failed to reload the DNS service"
# Display DS records
cat dsset-${ZONE}. || error_exit "Failed to display DS records"
}
# Check for required arguments
if [ -z "$ZONE" ]; then
error_exit "Usage: $0 <DOMAIN> [--update | --check]"
fi
# Parse optional flag
if [ "$2" = "--update" ]; then
sign_and_reload
echo "Zone ${ZONE} has been re-signed and DNS service reloaded."
elif [ "$2" = "--check" ]; then
cat dsset-${ZONE}. || error_exit "Domain {$ZONE} has no DNSSEC enabled."
else
setup_zone
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment