#!/bin/bash

NAGIOS_OK=0
NAGIOS_WARNING=1
NAGIOS_ERROR=2
NAGIOS_UNKNOWN=3

PAKITI_RESULT="pakiti_results"

if [ -f "$PAKITI_RESULT" ]; then
    cve=$(echo $0 | sed 's/.*check_//')
    grep -q "$cve" "$PAKITI_RESULT" 2>/dev/null
    if [ $? -eq 1 ]; then
        echo "No $cve vulnerability found, skipping the mitigation check"
        exit $NAGIOS_OK
    fi
fi

sudo=$(which sudo)

if [ -z "$sudo" ]; then
    echo "sudo not found in PATH, probably not installed"
    exit $NAGIOS_OK
fi

if [ ! -x "$sudo" ]; then
    echo "sudo not executable"
    exit $NAGIOS_OK
fi

bit=$(stat -L -c "%A" "$sudo" | cut -c4)
if [ "$bit" != "s" ]; then
    echo "sudo doesn't have the suid bit set"
    exit $NAGIOS_OK
fi

# vulnerable sudo aborts on SIGABRT (which maps to 134),
# we're checking for any signal here just to be sure
sudoedit -s '\' `perl -e 'print "A" x 65536'` 2>/dev/null
if [ $? -lt 128 ]; then
    echo "sudo doesn't seem to abort on overflowing payload"
    exit $NAGIOS_OK
fi

echo "No mitigation found for CVE-2021-3156, sudo seems vulnerable"
exit $NAGIOS_ERROR
