#!/bin/bash

# Description   :   This script is used to check for possibility of exploiting the recent sudo vulnerability CVE-2019-14287.
#
# Note          :   This script must be run as root.
#
# Returns       :   -1  Error
#                   0   Secure
#                   1   Vulnerable
#
# Usage         :   sudo bash check_sudo_vulnerability.sh
#
# Maintainer    :   ManageEngine Endpoint Central <endpointcentral-support@manageengine.com>

if [ $(id -u) != 0 ]; then
  echo "ERROR : This script must be run as root."
  exit -1
fi

no_sudoers=1
exit_status=0

cat "/etc/sudoers" | grep -v '^\s*[#%]' | grep -v '^root' | grep "(ALL\s*,.*!root.*)" >/dev/null 2>&1
retVal1=$?

cat "/etc/sudoers" | grep -v '^\s*[#%]' | grep -v '^root' | grep "ALL)" >/dev/null 2>&1
retVal2=$?

cat "/etc/sudoers" | grep -v '^\s*[#%]' | grep -v '^root' | grep "ALL=" | grep -v "(ALL\s*,.*!root.*)" | grep -v "ALL)" >/dev/null 2>&1
retVal3=$?

if [ $retVal1 -eq 0 ]; then

  echo "System is vulnerable."

  echo ""

  echo "Users who can exploit the vulnerability:"

  cat "/etc/sudoers" | grep -v '^\s*[#%]' | grep -v '^root' | grep "(ALL\s*,.*!root.*)" | sed 's/\s.*//'

  echo ""

  no_sudoers=0

  exit_status=1

fi

if [ $exit_status -eq 0 ]; then
  echo "System is secure."
  echo ""
fi

if [ $retVal2 -eq 0 ]; then

  echo "Users who already have all permissions or have"
  echo "already exploited the vulnerability to grant"
  echo "themselves all permissions:"

  cat "/etc/sudoers" | grep -v '^\s*[#%]' | grep -v '^root' | grep "ALL)" | sed 's/\s.*//'

  echo ""

  no_sudoers=0

fi

if [ $retVal3 -eq 0 ]; then

  echo "Users who cannot exploit the vulnerability:"

  cat "/etc/sudoers" | grep -v '^\s*[#%]' | grep -v '^root' | grep "ALL=" | grep -v "(ALL\s*,.*!root.*)" | grep -v "ALL)" | sed 's/\s.*//'

  no_sudoers=0

fi

if [ $no_sudoers -eq 1 ]; then
  echo "There appears to be no sudoers"
fi

exit $exit_status
