#!/bin/sh
# Usage: dnssec-check-zone <zone-file>
set -e
if [ $# -ne 1 ]
then
	echo 'Usage: dnssec-sign-zone <zone-file>' >&2
	exit 1
fi
prog="$0"
zone="$1"

tmpfile="/tmp/dns-check-zone-tmp-$$"
tmpfile2="/tmp/dns-check-zone-tmp2-$$"
tmpfile3="/tmp/dns-check-zone-tmp3-$$"
tmpfile_ds="/tmp/dns-check-zone-tmp-ds-$$"
tmpfile_ds_ttl="/tmp/dns-check-zone-tmp-ds-ttl-$$"

trap cleanup 0

cleanup()
{
	rm -f "$tmpfile" "$tmpfile2" "$tmpfile3" "$tmpfile_ds" "$tmpfile_ds_ttl"
}

check_update()
{
	resign_cmd="${1:-resign}"
	if [ $(stat -mtime "$zone".in) -gt $(stat -mtime "work/$zone.signed") ]
	then
		echo "Signed zone '$zone' is out of date, please run:" >&2
		echo "# dnssec-sign-zone $zone $resign_cmd" >&2
		exit 1
	fi
}

check_soa()
{
	# Get the current SOA from the signed zone file.
	set -- $(grep "$zone\..*IN	SOA" work/"$zone".signed)
	current_serial="$7"
	all_current=1
	some_current=0
	tmpfile="/tmp/dns-check-zone-tmp-$$"
	host -t ns "$zone" > $tmpfile
	while read tmp_zone tmp_NS nameserver rest
	do
		set -- $(drill soa "$zone" @"$nameserver" | grep "^$zone.*IN	SOA")
		serial="$7"
		if [ X"$serial" != X"$current_serial" ]
		then
			echo "Name server '$nameserver' has wrong serial '$serial', expected '$current_serial'" >&2
			all_current=0
			continue
		fi
		some_current=1
	done < "$tmpfile"
	if [ $some_current -eq 0 ]
	then
		echo "No up-to-date nameservers found for zone '$zone'" >&2
		return 1
	fi
	if [ $all_current -eq 0 ]
	then
		echo "$zone: wait for the update to propagate" >&2
		return 1
	fi
	# We now know that all nameserver are current and that there is at least
	# one nameserver
}

check_dnskey()
{
	# Create a file with the data we expect
	cat active/K"$zone"*.key passive/K"$zone"*.key 2>/dev/null |
	while read tmp_zone tmp_ttl tmp_in tmp_dnskey flags protocol algorithm key rest
	do
		echo "$flags" "$protocol" "$algorithm" "$key"
	done | sort > "$tmpfile2"

	all_current=1
	some_current=0
	host -t ns "$zone" > $tmpfile
	while read tmp_zone tmp_NS nameserver rest
	do
		drill -b 4096 dnskey "$zone" @"$nameserver" | grep "^$zone.*IN	DNSKEY" |
		while read tmp_zone tmp_ttl tmp_in tmp_dnskey flags protocol algorithm key rest
		do
			echo "$flags" "$protocol" "$algorithm" "$key"
		done | sort > "$tmpfile3"

		if expr -s "$tmpfile3" -eq 0 >/dev/null
		then
			all_current=0
			continue
		fi

		if diff "$tmpfile2" "$tmpfile3"
		then
			# Okay
			some_current=1
			continue
		fi

		echo "DNSKEY inconsistent for nameserver '$nameserver'" >&2
		all_current=0
	done < "$tmpfile"
	if [ $some_current -eq 0 ]
	then
		echo "No up-to-date nameservers found for zone '$zone'" >&2
		return 1
	fi
	if [ $all_current -eq 0 ]
	then
		echo "$zone: wait for the update to propagate" >&2
		return 1
	fi
	# We now know that all nameservers are current and that there is at
	# least one nameserver
}

check_soa_sig()
{
	# Assume that checking the key id is enough. 

	# Create a file with the data we expect
	grep "^$zone.*RRSIG	SOA" "work/$zone.signed" |
	while read tmp_zone tmp_ttl tmp_in tmp_rrsig tmp_soa algorithm hashid ttl valid_until valid_from keyid hash rest
	do
		echo "$algorithm" "$hashid" "$ttl" "$keyid"
	done | sort > "$tmpfile2"

	all_current=1
	some_current=0
	host -t ns "$zone" > $tmpfile
	while read tmp_zone tmp_NS nameserver rest
	do
		drill -D -b 4096 soa "$zone" @"$nameserver" |
			grep "^$zone.*RRSIG	SOA" |
		while read tmp_zone tmp_ttl tmp_in tmp_rrsig tmp_soa algorithm hashid ttl valid_until valid_from keyid hash rest
		do
			echo "$algorithm" "$hashid" "$ttl" "$keyid"
		done | sort > "$tmpfile3"

		if expr -s "$tmpfile3" -eq 0 >/dev/null
		then
			all_current=0
			continue
		fi

		if diff "$tmpfile2" "$tmpfile3"
		then
			# Okay
			some_current=1
			continue
		fi

		echo "RRSIG SOA inconsistent for nameserver '$nameserver'" >&2
	done < "$tmpfile"
	if [ $some_current -eq 0 ]
	then
		echo "No up-to-date nameservers found for zone '$zone'" >&2
		return 1
	fi
	if [ $all_current -eq 0 ]
	then
		echo "$zone: wait for the update to propagate" >&2
		return 1
	fi
	# We now know that all nameservers are current and that there is at
	# least one nameserver
}

check_ds()
{
	# Check if the DS record is in the parent zone. 

	# Create a file with the data we expect
	:> "$tmpfile_ds"
	for i in active/K"$zone"*.key
	do
		if grep 'DNSKEY	256' "$i" >/dev/null
		then
			# Ignore ZSKs
			continue
		fi
		key=$(basename "$i" .key)
		ds_file="active/$key.ds"
		if [ ! -f "$ds_file" ]
		then	
			echo "DS file not found for key '$key'" >&1
			exit 1
		fi
		cat "$ds_file" >> "$tmpfile_ds"
		set $(cat "$ds_file")
		key_id="$5"
		alg_id="$6"
		hash_id="$7"
		hash="$8"
		echo $key_id $alg_id $hash_id $hash 
	done | sort > "$tmpfile"

	# Assume that the parent is one level up.
	parent_zone=$(expr "$zone." : "[^.]*\.\(.*\)")
	# Loop over name servers
	all_current=1
	some_current=0
	drill ns "$parent_zone" | grep "^$parent_zone.*IN	NS" > $tmpfile2
	:> "$tmpfile_ds_ttl"
	while read tmp_zone tmp_ttl tmp_IN tmp_NS nameserver rest
	do
		drill ds "$zone" @"$nameserver" | grep "^$zone.*IN	DS" |
		while read tmp_zone tmp_ttl tmp_in tmp_ds key_id alg_id hash_id hash rest
		do
			if [ "$hash_id" = "1" ]
			then
				# Ignore sha1 hashes. Scary but necessary
				continue
			fi
			echo "$tmp_ttl" >> "$tmpfile_ds_ttl"
			echo $key_id $alg_id $hash_id $hash 
		done | sort > "$tmpfile3"

		if diff "$tmpfile" "$tmpfile3"
		then
			# Okay
			some_current=1
			continue
		fi

		all_current=0
		echo "DS inconsistent for nameserver '$nameserver'" >&2
	done < "$tmpfile2"

	if [ $some_current -eq 0 ]
	then
		echo "No up-to-date DS records found for zone '$zone'" >&2
		return 1
	fi
	if [ $all_current -eq 0 ]
	then
		echo "$zone: wait for the update to propagate" >&2
		return 1
	fi
	# We now know that all nameservers are current and that there is at
	# least one nameserver
	return 0
}

check_ds_empty()
{
	# Check if the DS record is in the parent zone. 

	# Create a file with the data we expect
	:> "$tmpfile_ds"
	for i in active/K"$zone"*.key
	do
		if grep 'DNSKEY	256' "$i" >/dev/null
		then
			# Ignore ZSKs
			continue
		fi
		key=$(basename "$i" .key)
		ds_file="active/$key.ds"
		if [ ! -f "$ds_file" ]
		then	
			echo "DS file not found for key '$key'" >&1
			exit 1
		fi
		cat "$ds_file" >> "$tmpfile_ds"
		set $(cat "$ds_file")
		key_id="$5"
		alg_id="$6"
		hash_id="$7"
		hash="$8"
		echo $key_id $alg_id $hash_id $hash 
	done | sort > "$tmpfile"

	# Assume that the parent is one level up.
	parent_zone=$(expr "$zone." : "[^.]*\.\(.*\)")
	# Loop over name servers
	all_empty=1
	some_empty=0
	drill ns "$parent_zone" | grep "^$parent_zone.*IN	NS" > $tmpfile2
	while read tmp_zone tmp_ttl tmp_IN tmp_NS nameserver rest
	do
		drill ds "$zone" @"$nameserver" | grep "^$zone.*IN	DS" |
		while read tmp_zone tmp_ttl tmp_in tmp_ds key_id alg_id hash_id hash rest
		do
			echo $key_id $alg_id $hash_id $hash 
		done | sort > "$tmpfile3"

		if expr -s "$tmpfile3" -eq 0 >/dev/null
		then
			some_empty=1
			continue
		fi

		all_empty=0
	done < "$tmpfile2"

	if [ "$all_empty" -eq 0 ]
	then
		# Changes are propagating
		return 1
	fi
	if [ "$some_empty" -eq 1 ]
	then
		# There is at least one nameserver
		return 0
	fi

	# No nameservers. Just report error
	echo 'No nameservers'
	return 1
}

# Find out the current state of the zone.
# First find out if we are in the progress of upgrading a ZSK or KSK
if cat passive/K"$zone".*key 2>/dev/null |
	grep 'DNSKEY[ 	]*256' >/dev/null 2>&1
then
	# Currently upgrading ZSK, phase1
	echo "$zone: Currently upgrading ZSK, phase1"

	# Check if the new keys are in the DNSKEY set
	if check_dnskey
	then
		if grep update-zsk-phase1 "work/S$zone" >/dev/null 2>&1
		then
			# Wait for the TTL plus one day.
			set -- $(grep DNSKEY work/"$zone".signed | head -1)
			ttl="$2"
			waituntil="$(expr $(stat -mtime "work/S$zone") + \
				"$ttl" + 86400)"
			if test $waituntil -le \ $(date +%s)
			then
				echo 'Phase1 has completed, please run:' >&2
				echo "# dnssec-sign-zone $zone update-zsk-phase2" >&2
				exit 1
			else
				echo "$zone: wait a bit more, until $(date -t $waituntil)"
				check_update update-zsk-phase1
				check_soa
				exit 1
			fi

		else
			echo update-zsk-phase1 > "work/S$zone"
			echo "$zone: please wait a bit"
			check_update
			check_soa
			exit 1
		fi
	else
		echo "$zone: more propagation needed"
		exit 1
	fi
fi
if cat previous/K"$zone".*key 2>/dev/null |
	grep 'DNSKEY[ 	]*256' >/dev/null 2>&1
then
	# Currently upgrading ZSK, phase2
	echo 'Currently upgrading ZSK, phase2'

	# Check if the new keys is used to sign the zone's SOA record.
	if check_soa_sig
	then
		if grep update-zsk-phase2 "work/S$zone" >/dev/null 2>&1
		then
			# Wait for the TTL plus one day.
			set -- $(grep 'RRSIG	SOA' work/"$zone".signed | head -1)
			ttl="$2"
			waituntil="$(expr $(stat -mtime "work/S$zone") + \
				"$ttl" + 86400)"
			if test $waituntil -le \ $(date +%s)
			then
				echo 'Phase2 has completed, please run:' >&2
				echo "# dnssec-sign-zone $zone update-zsk-phase3" >&2
				exit 1
			else
				echo "$zone: wait a bit more, until $(date -t $waituntil)"
				check_update update-zsk-phase2-resign
				check_soa
				exit 1
			fi

		else
			echo update-zsk-phase2 > "work/S$zone"
			echo "$zone: please wait a bit"
			check_update
			check_soa
			exit 1
		fi
	else
		echo "$zone: more propagation needed"
		exit 1
	fi
fi

if cat passive/K"$zone".*key 2>/dev/null |
	grep 'DNSKEY[ 	]*257' >/dev/null 2>&1
then
	# Currently upgrading KSK, phase1
	echo 'Currently upgrading KSK, phase1'

	# Check if the new keys are in the DNSKEY set
	if check_dnskey
	then
		if grep update-ksk-phase1 "work/S$zone" >/dev/null 2>&1
		then
			# Wait for the TTL plus one day.
			set -- $(grep DNSKEY work/"$zone".signed | head -1)
			ttl="$2"
			waituntil="$(expr $(stat -mtime "work/S$zone") + \
				"$ttl" + 86400)"
			if test $waituntil -le \ $(date +%s)
			then
				echo 'Phase1 has completed, please run:' >&2
				echo "# dnssec-sign-zone $zone update-ksk-phase2" >&2
				exit 1
			else
				echo "$zone: wait a bit more, until $(date -t $waituntil)"
				check_update update-ksk-phase1
				check_soa
				exit 1
			fi

		else
			echo update-ksk-phase1 > "work/S$zone"
			echo "$zone: plase wait a bit"
			check_update update-ksk-phase1
			check_soa
			exit 1
		fi
	else
		echo "$zone: more propagation needed"
		exit 1
	fi
fi

if cat previous/K"$zone".*key 2>/dev/null |
	grep 'DNSKEY[ 	]*257' >/dev/null 2>&1
then
	# Currently upgrading KSK, phase2
	echo 'Currently upgrading KSK, phase2'

	# Check if the DS record has propagated
	if check_ds
	then
		if grep update-ksk-phase2 "work/S$zone" >/dev/null 2>&1
		then
			ttl=$(sort -r -n "$tmpfile_ds_ttl" | head -1)
			waituntil="$(expr $(stat -mtime "work/S$zone") + \
				"$ttl" + 86400)"
			if test $waituntil -le \ $(date +%s)
			then
				echo 'Phase2 has completed, please run:' >&2
				echo "# dnssec-sign-zone $zone update-ksk-phase3" >&2
				exit 1
			else
				echo "$zone: wait a bit more, until $(date -t $waituntil)"
				check_update update-ksk-phase2-resign
				check_soa
				exit 1
			fi

		else
			echo update-ksk-phase2 > "work/S$zone"
			echo "$zone: please wait a bit"
			check_update
			check_soa
			exit 1
		fi
	else
		echo 'More propagation needed'
		exit 1
	fi
fi

# If the signed zone is old enough it may need re-signing.
signed_zone=work/"$zone".signed
if [ ! -f "$signed_zone" ]
then
	echo "No signed zone file, please sign with 'dnssec-sign-zone $zone initial'" >&2

	exit 1
fi
if expr $(stat -mtime "$signed_zone") + 14 '*' 86400 -lt $(date +%s) >/dev/null
then
	echo "$zone: zone need re-signing"
	echo "# dnssec-sign-zone $zone resign" >&2
	exit 1
fi

set +e
if check_ds_empty
then
	if check_dnskey
	then
		if grep initial "work/S$zone" >/dev/null 2>&1
		then
			# Wait for the TTL plus one day.
			set -- $(grep DNSKEY work/"$zone".signed | head -1)
			ttl="$2"
			waituntil="$(expr $(stat -mtime "work/S$zone") + \
				"$ttl" + 86400)"
			if test $waituntil -le \ $(date +%s)
			then
				echo Add DS record to parent zone
				cat "$tmpfile_ds"
				exit 1
			else
				echo "$zone: wait a bit more, until $(date -t $waituntil)"
				exit 0
			fi

		else
			echo "$zone: please wait"
			echo initial > "work/S$zone"
		fi
	else
		rm -f "work/S$zone"
		echo "Wait for zone to propagate to nameservers" >&2
		exit 1
	fi
	exit 1
fi
set -e

check_ds
check_soa
check_dnskey

# SOA checks out, also check if we need to update the zone.
if [ ! -f "$zone".in ]
then
	echo "Strange, no source file '$zone.in'" >&2
	exit 1
fi
check_update

for i in active/K"$zone".*key
do
	if grep 'DNSKEY	257' "$i" >/dev/null
	then
		# ZSK
		if expr $(stat -mtime "$i") + 3 \* 365 '*' 86400 -lt $(date +%s) >/dev/null
		then
			echo 'KSK needs updating, please run' >&2
			echo "# dnssec-sign-zone $zone update-ksk-phase1" >&2

			exit 1
		fi
	fi
done

for i in active/K"$zone".*key
do
	if grep 'DNSKEY	256' "$i" >/dev/null
	then
		# ZSK
		if expr $(stat -mtime "$i") + 180 '*' 86400 -lt $(date +%s) >/dev/null
		then
			echo "$zone: ZSK needs updating, please run" >&2
			echo "# dnssec-sign-zone $zone update-zsk-phase1" >&2

			exit 1
		fi
	fi
done

exit 0
