#!/bin/bash 
#
# check_selinux_alerts
#
# Author 		: Nohaj
# Contact 		: johan.fr
# Date 			: 20/02/18
# Version 		: 1.0
# Description 	: Check SELinux alerts
# Notes 		: Designed to be used by Nagios/Shinken from NRPE through sudo
# 				: Performances data only make senses if used with daily period

# Reminder of sudoers configuration (exemple for nrpe user)
# Defaults:nrpe !requiretty
# nrpe    ALL= NOPASSWD: /usr/sbin/ausearch

#
# Variables and checks
#

# Defaults values
warning=1
critical=5
period="today"

# We check the state of SELinux
state=`getenforce`
if [ $state == "disabled" ] ; then
	echo "UNKNOWN: SELinux is disabled"
	exit 3
fi

# We check that we can run ausearch through sudo
if ( ! /usr/bin/sudo -n /usr/sbin/ausearch -v &> /dev/null ) ; then
	echo "UNKNOWN: User $USER is not allowed to run ausearch"
	exit 3
fi

#
# Usage
#

usage(){
	echo ""
	echo "Usage : check_selinux_alerts [-p PERIOD] [-w WARNING] [-c CRITICAL]"
	echo ""
	echo "OPTIONS :"
	echo "   -h     Print help"
	echo "   -p     Period to check (default : $period). Check ausearch manual for supported periods."
	echo "   -w     Warning threshold (default : $warning)"
	echo "   -c     Critical threshold (default : $critical)"
	echo ""
}

#
# Getopts
#

while getopts ":h:p:w:c:*" opt; do
	case $opt in
		w)
			warning="$OPTARG"
			;;
		c)
			critical="$OPTARG"
			;;
		p)
			period="$OPTARG"
			;;
		h)
			usage
			exit 3
			;;
		\?)
			usage
			exit 3
			;;
		*)
			usage
			exit 3
			;;
	esac
done

#
# Let's get the party started
#

alert_number=`/usr/bin/sudo /usr/sbin/ausearch -m avc --start $period 2> /dev/null | grep time | wc -l`

if [ $alert_number -ge $warning ] ; then
	if [ $alert_number -ge $critical ] ; then
		echo "CRITICAL: $alert_number SELinux alerts for $period's period ($state mode)|alerts=$alert_number;$warning;$critical"
		exit 2
	else
		echo "WARNING: $alert_number SELinux alerts for $period's period ($state mode)|alerts=$alert_number;$warning;$critical"
		exit 1
	fi
else
	echo "OK: $alert_number SELinux alerts for $period's period ($state mode)|alerts=$alert_number;$warning;$critical"
	exit 0
fi

