#!/bin/bash
#
# Check if the DS Record set for the ZONE in the parent
# corresponds to at at least one of the current KSKs
# It only checks for RSASHA256-hashed DS-keyIDs
#
# File:         check_dnssec-ds
# Author:       Sven Duscha ( sven dot duscha @ lrz dot de )
# Date:         2017-02-17
# Last change:  2017-02-17

# Default values for warning and critical
CRITICALVAL=0
# Return values for WARN and CRIT
OK=0
WARN=1
CRIT=2
UNKNOWN=3
# Default return value RETVAL is UNKNOWN
RETVAL=$UNKNOWN


usage()
{
  echo "usage: $0 -z <ZONE>"
  echo "-z <ZONE> to check."
  echo "-h this usage help"
  exit 0
}

# Parse command line arguments
while [[ $# -gt 1 ]]
do
key="$1"

case $key in
    -z|--zone)
    ZONE="$2"
    shift # past argument
    ;;
    -h|--help)
    usage
    ;;
    *)
            # unknown option
    ;;
esac
shift # past argument or value
done


# Don't accept empty Zone
if [ "$ZONE" == "" ]
then
  echo "No zone given as argument -z"
  exit 1
fi


# Do the work using dig
DS=`dig DS $ZONE +short | grep ' 8 2 ' | gawk '{print $1}' | sort -u -n`

if [ "$?" -eq 1 ]	# call to dig  failed
then
  echo "dig DS $ZONE failed.|$DS"
  RETVAL=$UNKNOWN
fi

if [ "$DS" == "" ]	# Zone is NOT DNSSEC-secured, no DS RRs in parent
then
  echo "No DS Records in parent."
  RETVAL=$CRIT
fi

# Get the KSKs from the ZONE
KSK=`dig $ZONE DNSKEY +multi | grep KSK | awk '{print $10}' | sort -u -n -z | tr '\n' ' '`

# Check if the DS RRsets match any of the current KSKs

# PRE: RETVAL=CRIT
# Loop over the entries of KSK, k, found in the parent DS RR
for k in `echo "$DS"`
do
	if [[ "$KSK" =~ "$k" ]]		# k is a substring of all KSKs
	then
		echo "KSK $k found in DS RRsets of parent."
    RETVAL=$OK							# k (DS) is in the current KSKs
	fi
done
# POST: if found RETVAL=OK, else still RETVAL=CRIT

exit $RETVAL
