#!/bin/bash
#
# check_selinux_state
#
# Author        : Nohaj
# Contact       : johan.fr
# Date          : 16/10/18
# Version       : 1.0
# Description   : Check the active state of SELinux
# Notes         : Designed to be used by Nagios/Shinken from NRPE 

#
# Variables and checks
#

# Defaults values 
wanted_state="Enforcing"

#
# Usage
#

usage(){
    echo ""
    echo "Usage : check_selinux_state [-m STATE]"
    echo ""
    echo "OPTIONS :"
    echo "   -h     Print help"
    echo "   -m     SELinux wanted state (default: $wanted_state)"
    echo "          Can be: 'Enforcing'|'Permissive'|'Disabled'"
    echo ""
}

#
# Getopts
#

while getopts ":h:m:*" opt; do
    case $opt in
        m)
            wanted_state="$OPTARG"
            ;;
        h)
            usage
            exit 3
            ;;
        \?)
            usage
            exit 3
            ;;
        *)
            usage
            exit 3
            ;;
    esac
done

# Check the wanted state
if [[ $wanted_state != "Enforcing" ]] && [[ $wanted_state != "Permissive" ]] && [[ $wanted_state != "Disabled" ]] ; then
    echo "UNKNOWN: $wanted_state is not a valid SELinux state"
    exit 3
fi

#
# Let's get the party started
#

# Retrive active state
active_state=$(getenforce)

if [[ -z $active_state ]] ; then
    echo "UNKNOWN: Can't retrieve the SELinux active state"
    exit 3
fi

if [[ $active_state == $wanted_state ]] ; then
    echo "OK: SELinux is in $wanted_state state"
    exit 0
else
    echo "CRITICAL: SELinux is in $active_state state (should be in $wanted_state state)"
    conf_state=$(grep ^SELINUX= /etc/selinux/config | cut -d "=" -f 2)
    if [[ ${conf_state^} == $wanted_state ]] ; then
        echo "Notes: The SELinux boot state is set to $conf_state"
    fi
    exit 2
fi

