#!/bin/bash

#######
## Description: Extension for the check_rbl plugin to check multiple IP addresses for entries in blacklists.
## Author: Sebastian Klee
## E-Mail: s.klee@timmehosting.de
## Version: 1.2
## Date: 16.05.2022
#######

export PATH=$PATH:/usr/lib/nagios/plugins:/usr/lib/nagios/plugins/contrib:/usr/local/lib/nagios/plugins

#######
# Variables containing a regular expressions for private IP addresses and Loopback addresses.
# They are used in the IF block below to prevent a check of these Addresses.
reg_priv='^172\.1[6-9]\.|^172\.2[0-9]\.|^172\.3[0-1]\.|^192\.168\.|^10\.|^fe[89ab]{1}|^f[cd]'
# Explanation for the  regular expression:
# ^172\.1[6-9.]\.|^172\.2[0-9]\.|^172\.3[0-1]\. -> for 172.16.0.0/12 
# ^192\..168\.'                                 -> for 192.168.0.0/16
# ^10\.                                         -> for 10.0.0.0/8
# ^fe[89ab]{1}|^f[cd]                           -> for IPv6 Adresses beginning with fe80 - febf(link local) or fc - fd(Unique Local Address)
#
reg_lo='^127.0.0\.|^::1'
# Explanation for the  regular expression:
# ^127.0.0\.|^::1           -> for Looback IPv4 and IPv6
#######

# Variables to determine the exit code for the script
error=0
unknown=0

# The command in the loop determines the IP addresses of the server. The loop is repeated for each IP found.
for i in $(ip addr | grep 'inet' | awk '{print $2}' | awk -F '/' '{print $1}'| sort | uniq); do
      # If the condition of the if is true, the instruction in the then-block will be executed.
      if [[ ! $i =~ $reg_priv ]] && [[ ! $i =~ $reg_lo ]]; then
         # $i = IP address to be checked, determined by the command in the loop.
         # $1, $2, $3, $4, $5, $6 = Variables for the arguments that the check_rbl_extension script receives.
         result=$(check_rbl -H "$i" "$@")

         # A filter to get only the status-code of the result.
         status=$?

         # If the status-code is bigger then 0, the value of the variable error will be increased by one.
         if [[ $status -gt 0 ]] && [[ $status -le 2 ]]; then
            error=$((error + 1))
            # stdout to stderr
            echo "${result}" >&2
         elif [[ $status -gt 2 ]]; then
            unknown=$((unknown + 1))
            echo "${result}"
         fi
      fi
done

# If the value of the variable error is bigger then 0(at least one IP is on a blacklist), the script returns the exit code for a critical. 
if [[ $error -gt 0 ]]; then
   # Criical
   exit 2
elif [[ $unknown -gt 0 ]]; then
   # Unknown
   exit 3
else
   # OK
   echo "Server ist auf keiner der geprüften Blacklists"
   exit 0
fi

