#!/bin/bash

NAGIOS_OK=0
NAGIOS_ERROR=2

PAKITI_RESULT="pakiti_results"

SINGULARITY_CONFIG=/etc/singularity/singularity.conf

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

if [ -d /usr/libexec/singularity ]; then
    SUID_SET="no"
    for bin in /usr/libexec/singularity/bin/*-suid; do
        if [ -u "$bin" ]; then
            SUID_SET="yes"
            break
        fi
    done
    if [ "$SUID_SET" = "no" ]; then
        echo "no singularity suid command has the set-uid bit set"
        exit $NAGIOS_OK
    fi
fi

egrep -q '^\S*allow setuid = no' $SINGULARITY_CONFIG 2>/dev/null
if [ $? -eq 0 ]; then
    echo "Using of set-uid isn't enabled by singularity"
    exit $NAGIOS_OK
fi

exe=$(which singularity)
if [ -z "$exe" ]; then
    echo "singularity not found in PATH, probably not installed"
    exit $NAGIOS_OK
fi

ver=$(singularity --version)
if [ $? -ne 0 ]; then
    echo "Can't obtain the singularity version, considering it vulnerable"
    exit $NAGIOS_ERROR
fi

if [[ ! $ver == 2.5.* ]]; then
    echo "There's no working mitigation for singularity of versions older then 2.5.0"
    exit $NAGIOS_ERROR
fi

egrep -q '^\S*enable overlay = no' $SINGULARITY_CONFIG 2>/dev/null
if [ $? -eq 0 ]; then
    echo "OverlayFS is disabled by singularity"
    exit $NAGIOS_OK
fi

echo "No known mitigation of EGI-SVG-2018-14213 detected"
exit $NAGIOS_ERROR
