#!/bin/sh

#################################################################################
#
#   Lynis
# ------------------
#
# Copyright 2007-2008, Michael Boelen (michael@rootkit.nl), The Netherlands
# Web site: http://www.rootkit.nl
#
# Lynis comes with ABSOLUTELY NO WARRANTY. This is free software, and you are
# welcome to redistribute it under the terms of the GNU General Public License.
# See LICENSE file for usage of this software.
#
#################################################################################
#
# Lynis is an automated auditing tool for Unix based operating systems.
#
#################################################################################
#

# Program information
PROGRAM_name="Lynis"
PROGRAM_version="1.1.1"
PROGRAM_releasedate="13 April 2008"
PROGRAM_author="Michael Boelen"
PROGRAM_author_contact="michael@rootkit.nl"
PROGRAM_website="http://www.rootkit.nl/"
PROGRAM_copyright="Copyright 2007-2008 - ${PROGRAM_author}, ${PROGRAM_website}"
PROGRAM_license="${PROGRAM_name} comes with ABSOLUTELY NO WARRANTY. This is free software, and you are
 welcome to redistribute it under the terms of the GNU General Public License.
 See LICENSE file for details about using this software."
 
PROGRAM_extrainfo=""
# Release version (beta || final)
PROGRAM_releasetype="final"
# Version number of report files (when format changes in future)
REPORT_version_major="1"; REPORT_version_minor="0"
REPORT_version="${REPORT_version_major}.${REPORT_version_minor}"

#
#################################################################################
#
# Configure Include path and files
#
#################################################################################
#
    # Which directory we use to include all functions and tests
    INCLUDEDIR="include"
    
    # Drop out if our include directory can't be found
    if [ ! -d ${INCLUDEDIR} ]; then
      echo "Fatal error: can't find include directory (${INCLUDEDIR})"
      exit 1
    fi
#
#################################################################################
#
# Consts
# (bin paths, text strings, colors)
#
#################################################################################
#
    . ${INCLUDEDIR}/consts
#
#################################################################################
#
# Include functions, traps
#
#################################################################################
#
    . ${INCLUDEDIR}/functions
    trap Maid INT
    
    # Use safe umask for the files we create
    umask 027
#
#################################################################################
#
# Parameter checks
#
#################################################################################
#
    . ${INCLUDEDIR}/parameters
#
#################################################################################
#
# Initialize and default settings
#
#################################################################################
#
    if [ "${PROGRAM_releasetype}" = "beta" ]; then
        echo "${YELLOW}"
	echo "  #########################################################"
	echo "  #   BETA SOFTWARE                                       #"
        echo "  #########################################################"
        echo ""
        echo "  Thank you for testing a beta release. Make sure to read"
        echo "  all available documentation before proceeding and/or"
        echo "  requesting support. Due the nature of beta releases, it"
        echo "  is possible new features give warnings."
    	echo ""
        echo "  Press [ENTER] to continue or [CTRL] + C to break"
        echo ""
        echo "  #########################################################"
        echo "${NORMAL}"; echo ""
        if [ ${NEVERBREAK} -eq 0 ]; then read void; fi
    fi
    
    if [ ${QUIET} -eq 0 ]; then
        echo ""
        echo "${WHITE}[ ${PROGRAM_name} ${PROGRAM_version} ]${NORMAL}"
        echo ""
        echo "################################################################################"
        echo " ${PROGRAM_license}"
        echo ""
        echo " ${PROGRAM_copyright}"
        echo "################################################################################"
    fi
    
    InsertSection "Initializing program"

    # Initialize and check profile file, auditor name, log file and report file
    if [ "${PROFILE}" = "" ];		then PROFILE="default.prf"; fi
    if [ ! -r ${PROFILE} ];		then echo "Fatal error: Can't open profile file (${PROFILE})"; exit 1; fi
    if [ "${AUDITORNAME}" = "" ];	then AUDITORNAME="[Unknown]"; fi
    if [ "${LOGFILE}" = "" ];		then LOGFILE="/var/log/lynis.log"; fi
    if [ "${REPORTFILE}" = "" ];	then REPORTFILE="/var/log/lynis-report.dat"; fi

#
#################################################################################
#
# PID :: Check PID file, to avoid multiple instances running at the same time.
#
#################################################################################
#
    # Check user. We need root to be able to audit and use all required system tools
    if [ ! `id -u` -eq 0 ]; then
        echo "${WARNING}Fatal error${NORMAL}: ${NOTICE}Incorrect UID.${NORMAL}"
        echo "You have to be root (or equivalent) to perform an audit. Please su(do) and try again."
        exit 1
    fi

    # Check PID file
    if [ -f lynis.pid -o -f /var/run/lynis.pid ]; then
        echo "      ${WARNING}Warning${NORMAL}: ${WHITE}PID file exists, probably another Lynis process is running.${NORMAL}"
        echo "      ------------------------------------------------------------------------------"
        echo "      If you are unsure another Lynis process is running currently, you are adviced "
        echo "      to stop current process and check the process list first. If you cancelled"
        echo "      (by using CTRL+C) a previous instance, you can ignore this message."
        echo "      ------------------------------------------------------------------------------"
        echo ""
        echo "      ${YELLOW}Note: ${WHITE}Cancelling the program can leave temporary files behind${NORMAL}"
        echo ""    
        wait_for_keypress
	Display --indent 2 --text "- Deleting old PID file..."
        if [ -f lynis.pid ]; then rm -f lynis.pid
	  elif [ -f /var/run/lynis.pid ]; then rm -f /var/run/lynis.pid; fi
    fi

    # Create new PID file (use work directory if /var/run is not available)
    if [ -d /var/run ]; then PIDFILE="/var/run/lynis.pid"; else PIDFILE="lynis.pid"; fi
    OURPID=`echo $$`
    echo ${OURPID} > ${PIDFILE}
    chmod 600 ${PIDFILE}
#
#################################################################################
#
# OS Detection
#
#################################################################################
#
    . ${INCLUDEDIR}/osdetection
    Display --indent 2 --text "- Detecting OS... " --result DONE --color GREEN

    # Hostname
    HOSTNAME=`hostname`
#
#################################################################################
#
# Clear log and report files 
#
#################################################################################
#
    # Clear log file and test if it's writable
    logtext "### Starting ${PROGRAM_name} ${PROGRAM_version} with PID ${OURPID}, build date ${PROGRAM_releasedate} ###" > ${LOGFILE}
    if [ $? -eq 0 ]; then
	Display --indent 2 --text "- Clearing log file (${LOGFILE})... " --result DONE --color GREEN
      else
	Display --indent 2 --text "- Clearing log file (${LOGFILE})... " --result WARNING --color RED
        echo "${WARNING}Fatal error${NORMAL}: problem while writing to log file. Check location and permissions."
	RemovePIDFile    
        exit 1
    fi
    logtext "### ${PROGRAM_copyright} ###"

    # Clear report file (to avoid appending to an existing file)
    echo "# ${PROGRAM_name} Report" > ${REPORTFILE}
    report "[General]"
    report "report_version_major=${REPORT_version_major}"
    report "report_version_minor=${REPORT_version_minor}"
    CDATE=`date "+%H:%M:%S"`
    report "report_datetime=${CDATE}"
    report "auditor=${AUDITOR}"
    report "lynis_version=${PROGRAM_version}"
    report "[Operating System]"
    report "os=${OS}"
    report "os_fullname=${OS_FULLNAME}"
    report "hostname=${HOSTNAME}"
#
#################################################################################
#
# Check program parameters
#
#################################################################################
#
    # Bail out if we didn't get any parameter, or incorrect ones
    if [ ${PARAMCOUNT} -eq 0 -o ${WRONGOPTION} -eq 1 -o ${VIEWHELP} -eq 1 ]; then
        echo "  =================================================="
        echo "  ${WHITE}Valid parameters:${NORMAL}"
        echo "    --auditor \"<name>\"        : Auditor name"
        echo "    --check-all (-c)          : Check system"
        echo "    --no-log                  : Don't create a log file"
        echo "    --profile <profile>       : Scan the system with the given profile file"
        echo "    --quick (-Q)              : Quick, don't wait for user input"
        echo "    --view-manpage (--man)    : View man page"
        echo "    --version (-V)            : Display version number and quit"
        echo ""

        if [ ${WRONGOPTION} -eq 1 ]; then
            echo "  ${RED}Error${NORMAL}: ${WHITE}Invalid option ${WRONGOPTION_value}!${NORMAL}"
          else
            echo "  ${RED}Error${NORMAL}: ${WHITE}No parameters specified!${NORMAL}"
        fi
        echo "  See man page and documentation for all available options."
        echo ""
        echo "Exiting.."
        # Cleanup PID file if we drop out earlier
        RemovePIDFile    
        # Exit with exit code 1
        exit 1
    fi
#
#################################################################################
#
# Show program information to display
#
#################################################################################
#
    if [ ${QUIET} -eq 0 ]; then
        echo ""
        echo "  ---------------------------------------------------"
        echo "  Program version:           ${PROGRAM_version}"
        echo "  Operating system:          ${OS_NAME}"
        echo "  Operating system version:  ${OS_VERSION}" 
        echo "  Kernel version:            ${OS_KERNELVERSION}"
        echo "  Hardware platform:         ${HARDWARE}"
        echo "  Hostname:                  ${HOSTNAME}"
        echo "  Auditor:                   ${AUDITORNAME}"
        echo "  Profile:                   ${PROFILE}"
        echo "  Log file:                  ${LOGFILE}"
        echo "  Report file:               ${REPORTFILE}"
        echo "  Report version:            ${REPORT_version}"
        echo "  ---------------------------------------------------"
    fi
    
    logtext "Program version:           ${PROGRAM_version}"
    logtext "Operating system:          ${OS_NAME}"
    logtext "Operating system version:  ${OS_VERSION}"
    logtext "Kernel version:            ${OS_KERNELVERSION}"
    logtext "Hardware platform:         ${HARDWARE}"
    logtext "Hostname:                  ${HOSTNAME}"
    logtext "Auditor:                   ${AUDITORNAME}"
    logtext "Profile:                   ${PROFILE}"
    logtext "Log file:                  ${LOGFILE}"
    logtext "Report file:               ${REPORTFILE}"
    logtext "Report version:            ${REPORT_version}"

    logtextbreak
    wait_for_keypress

#
#################################################################################
#
# Read profile/template
#
#################################################################################
#
    #YYY Enable check when profile files are complete
    # Check if default profile is used
    if [ "${PROFILE}" = "defaultXXX.prf" ]; then
        echo ""
        echo "      ==============================================================================="
        echo "        ${WARNING}Warning${NORMAL}: ${WHITE}Default profile is used.${NORMAL}"
        echo "          Default profile contains only a small amount of options and settings."
        echo "          Consult the documentation to create a custom profile!"
        echo ""
        echo "      [ ${WHITE}Press [ENTER] to continue with the default profile or [CTRL] + C to stop${NORMAL} ]"
        echo "      ==============================================================================="
        wait_for_keypress
    fi

    Display --indent 2 --text "- Checking profile file (${PROFILE})..."
    if [ ${QUIET} -eq 0 ] ; then
        echo -n "    Options: "
    fi
    logtext "Reading profile/configuration ${PROFILE}"

    FIND=`cat ${PROFILE} | grep '^config:' | sed 's/ /!space!/g'`
    for I in ${FIND}; do
	OPTION=`echo ${I} | cut -d ':' -f2`
	VALUE=`echo ${I} | cut -d ':' -f3`    

	#YYY do something useful with configuration options
	#    logtext "Found configuration option ${OPTION} (with value ${VALUE})"
	if [ ${QUIET} -eq 0 ] ; then
    	    echo -n "${OPTION} "
	fi

	case ${OPTION} in

	debian_skip_security_repository)
	OPTION_DEBIAN_SKIP_SECURITY_REPOSITORY="${VALUE}"
	;;

	freebsd_skip_portaudit)
	logtext "Option set: Skip FreeBSD portaudit"
	OPTION_FREEBSD_SKIP_PORTAUDIT="${VALUE}"
	;;
	
	profile_name)
	# YYY dummy 
	;;
	
	# Catch all bad options and bail out
	*)
	logtext "Unknown option ${OPTION} (with value: ${VALUE})"
	echo "Fatal error: found errors in profile"
	echo "Unknown option ${OPTION} found (with value: ${VALUE})"
	RemovePIDFile    
	exit 1
	;;

        esac
      done
      
    if [ ${QUIET} -eq 0 ]; then echo ""; fi
    logtextbreak
#
#################################################################################
#
# Check for program update (people tend to be lazy and don't perform updates =))
#
#################################################################################
#
    logtext "Test: Checking for program update..."

    PROGRAM_AC=`echo ${PROGRAM_version} | awk '{ print $1 }' | sed 's/[.]//g'`
    PROGRAM_LV=`dig +short -t txt lynis-lv.rootkit.nl 2> /dev/null | sed 's/[".]//g'`

    if [ "${PROGRAM_AC}" = "" -o "${PROGRAM_LV}" = "" ]; then
        Display --indent 2 --text "- Program update status... " --result UNKNOWN --color YELLOW
        logtext "Result: Update check failed. No connection?"
        # Set both to safe values
        PROGRAM_AC=0; PROGRAM_LV=0
      else
        logtext "Current installed version  : ${PROGRAM_AC}"
        logtext "Latest stable version      : ${PROGRAM_LV}"
 
        if [ $PROGRAM_LV -gt $PROGRAM_AC ]; then
            Display --indent 2 --text "- Program update status... " --result "UPDATE AVAILABLE" --color YELLOW
	    echo ""
    	    echo "      ==============================================================================="
    	    echo "        ${NOTICE}Notice: ${WHITE}${PROGRAM_name} update available${NORMAL}"
    	    echo "          Current version : ${WHITE}${PROGRAM_AC}${NORMAL}"
    	    echo "          Latest version  : ${WHITE}${PROGRAM_LV}${NORMAL}"
	    echo "          ${WHITE}Please update to the latest version for new options, bug fixes"
	    echo "          audit tests and baselines.${NORMAL}"
    	    echo "      ==============================================================================="
	    echo ""
    	    logtext "Result: newer ${PROGRAM_name} release available!"
	    logtext "Suggestion: update to the latest stable release."
    	    wait_for_keypress
	  else
    	    Display --indent 2 --text "- Program update status... " --result "NO UPDATE" --color GREEN
    	    logtext "No ${PROGRAM_name} update available."
        fi  
    fi

    logtextbreak
#
#################################################################################
#
# Check which tools are installed
#
#################################################################################
#
    Display --indent 2 --text "- Scanning available tools..."
    logtext "Start scanning for available audit binaries and tools..."

    for I in ${BINPATHS}; do
      J=${I}"/chkconfig"; 	if [ -f ${J} ]; then logtext "Found ${J}"; CHKCONFIGFOUND=1;  	 CHKCONFIGBINARY=${J};   fi
      J=${I}"/chkrootkit"; 	if [ -f ${J} ]; then logtext "Found ${J}"; CHKROOTKITFOUND=1;  	 CHKROOTKITBINARY=${J};      	fi
      J=${I}"/exim";      	if [ -f ${J} ]; then EXIMFOUND=1;	EXIMBINARY=${J};	EXIMVERSION=`${J} -bV | grep 'Exim version' | awk '{ print $3 }' | xargs`; logtext "Found ${J} (version ${EXIMVERSION})";	fi
      J=${I}"/find";      	if [ -f ${J} ]; then logtext "Found ${J}"; FINDFOUND=1;    	 FINDBINARY=${J};      	fi
      J=${I}"/grpck";      	if [ -f ${J} ]; then logtext "Found ${J}"; GRPCKFOUND=1;    	 GRPCKBINARY=${J};     	fi
      J=${I}"/httpd";      	if [ -f ${J} ]; then logtext "Found ${J}"; HTTPDFOUND=1;    	 HTTPDBINARY=${J};      fi
      J=${I}"/ip";      	if [ -f ${J} ]; then logtext "Found ${J}"; IPFOUND=1;    	 IPBINARY=${J};      	fi
      J=${I}"/ifconfig";	if [ -f ${J} ]; then logtext "Found ${J}"; IFCONFIGFOUND=1;      IFCONFIGBINARY=${J};   fi
      J=${I}"/kldstat";		if [ -f ${J} ]; then logtext "Found ${J}"; KLDSTATFOUND=1;       KLDSTATBINARY=${J};    fi
      J=${I}"/locate";    	if [ -f ${J} ]; then logtext "Found ${J}"; LOCATEFOUND=1;	 LOCATEBINARY=${J};     fi
      J=${I}"/ls";      	if [ -f ${J} ]; then logtext "Found ${J}"; LSFOUND=1;   	 LSBINARY=${J};         fi
      J=${I}"/lsattr";     	if [ -f ${J} ]; then logtext "Found ${J}"; LSATTRFOUND=1;  	 LSATTRBINARY=${J};     fi
      J=${I}"/lsmod";      	if [ -f ${J} ]; then logtext "Found ${J}"; LSMODFOUND=1;    	 LSMODBINARY=${J};      fi
      J=${I}"/lsof";    	if [ -f ${J} ]; then logtext "Found ${J}"; LSOFFOUND=1;    	 LSOFBINARY=${J};       fi
      J=${I}"/lynx";    	if [ -f ${J} ]; then logtext "Found ${J}"; LYNXFOUND=1;	 	 LYNXBINARY=${J};       fi
      J=${I}"/md5";     	if [ -f ${J} ]; then logtext "Found ${J}"; MD5FOUND=1;     	 MD5BINARY=${J};        fi
      J=${I}"/md5sum";  	if [ -f ${J} ]; then logtext "Found ${J}"; MD5FOUND=1;     	 MD5BINARY=${J};        fi
      J=${I}"/netstat";  	if [ -f ${J} ]; then logtext "Found ${J}"; NETSTATFOUND=1;     	 NETSTATBINARY=${J};    fi
      J=${I}"/nmap";    	if [ -f ${J} ]; then logtext "Found ${J}"; NMAPFOUND=1;    	 NMAPBINARY=${J};       fi
      J=${I}"/openssl";    	if [ -f ${J} ]; then OPENSSLFOUND=1;  	 OPENSSLBINARY=${J};	OPENSSLVERSION=`${J} version | head -n 1 | awk '{ print $2 }' | xargs`; logtext "Found ${J} (version ${OPENSSLVERSION})";    fi
      J=${I}"/perl";        	if [ -f ${J} ]; then PERLFOUND=1;	PERLBINARY=${J};	PERLVERSION=`${J} -V:version | ${J} -pi -e "s/^version='(.*)';$/\1/" | xargs`;    logtext "Found ${J} (version ${PERLVERSION})"; fi
      J=${I}"/postconf";   	if [ -f ${J} ]; then logtext "Found ${J}"; POSTCONFFOUND=1; 	 POSTCONFBINARY=${J};   fi
      J=${I}"/postfix";   	if [ -f ${J} ]; then logtext "Found ${J}"; POSTFIXFOUND=1; 	 POSTFIXBINARY=${J};    fi
      J=${I}"/prelink";   	if [ -f ${J} ]; then logtext "Found ${J}"; PRELINKFOUND=1; 	 PRELINKBINARY=${J};    fi
      J=${I}"/ps";      	if [ -f ${J} ]; then logtext "Found ${J}"; PSFOUND=1;      	 PSBINARY=${J};         fi
      J=${I}"/rkhunter";   	if [ -f ${J} ]; then logtext "Found ${J}"; RKHUNTERFOUND=1;	 RKHUNTERBINARY=${J};        fi    
      J=${I}"/rpm";    		if [ -f ${J} ]; then logtext "Found ${J}"; RPMFOUND=1;	 	 RPMBINARY=${J};        fi  
      J=${I}"/slocate";    	if [ -f ${J} ]; then logtext "Found ${J}"; LOCATEFOUND=1;	 LOCATEBINARY=${J};     fi
      J=${I}"/sockstat";   	if [ -f ${J} ]; then logtext "Found ${J}"; SOCKSTATFOUND=1;	 SOCKSTATBINARY=${J};   fi
      J=${I}"/stat"; 		if [ -f ${J} ]; then logtext "Found ${J}"; STATFOUND=1;	   	 STATBINARY=${J};       fi
      J=${I}"/sshd"; 		if [ -f ${J} ]; then SSHDFOUND=1;	SSHDBINARY=${J};	SSHDVERSION=`${J} -t -d 2>&1 | head -n 1 | awk '{ print $4 }' | cut -d '_' -f2 | xargs`; logtext "Found ${J} (version ${SSHDVERSION})";      fi
      J=${I}"/strings"; 	if [ -f ${J} ]; then logtext "Found ${J}"; STRINGSFOUND=1; 	 STRINGSBINARY=${J};    fi
      J=${I}"/wget";    	if [ -f ${J} ]; then logtext "Found ${J}"; WGETFOUND=1;    	 WGETBINARY=${J};       fi
    done

    Display --indent 4 --text "Application scan finished" --result DONE --color GREEN
    logtextbreak
#
#################################################################################
#
    INCLUDE_TESTS="boot_services kernel memory_processes authentication homedirs shells"
    for INCLUDE_TEST in ${INCLUDE_TESTS}; do
      . ${INCLUDEDIR}/tests_${INCLUDE_TEST}
    done
#
#################################################################################
#
    INCLUDE_TESTS="filesystems ports_packages networking printers_spools mail_messaging"
    for INCLUDE_TEST in ${INCLUDE_TESTS}; do
      . ${INCLUDEDIR}/tests_${INCLUDE_TEST}
    done
#
#################################################################################
#
    INCLUDE_TESTS="file_integrity firewalls"
    for INCLUDE_TEST in ${INCLUDE_TESTS}; do
      . ${INCLUDEDIR}/tests_${INCLUDE_TEST}
    done
#
#################################################################################
#

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

InsertSection "Software: nameserver"

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

#YYY
# FIND=`named-checkconf ; echo $?`
# - Add to binary check list
#echo "      - Checking Bind configuration... [Test not implemented yet]"

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

InsertSection "Software: security"

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

    counttests
    
    logtext "Test: checking presence chkrootkit"
    if [ "${CHKROOTKITBINARY}" = "" ]; then
	Display --indent 2 --text "- Checking chkrootkit..." --result "NOT FOUND" --color WHITE
	logtext "Result: chkrootkit not found"
      else
	Display --indent 2 --text "- Checking chkrootkit..." --result "FOUND" --color GREEN
	logtext "Result: Found ${CHKROOTKITBINARY}"
    fi
    logtextbreak

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

    counttests
    logtext "Test: checking presence Rootkit Hunter"
    if [ "${RKHUNTERBINARY}" = "" ]; then
	Display --indent 2 --text "- Checking Rootkit Hunter..." --result "NOT FOUND" --color WHITE
	logtext "Result: Rootkit Hunter not found"
      else
	Display --indent 2 --text "- Checking Rootkit Hunter..." --result "FOUND" --color GREEN
	logtext "Result: Found ${RKHUNTERBINARY}"
    fi
    logtextbreak

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

    #YYY check if at least one security scanner is installed

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

InsertSection "Software: webserver"

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

    Display --indent 2 --text "- Checking Apache... "	    	

    APACHE_CONFIGFILE=""

    if [ ! "${HTTPDBINARY}" = "" ]; then
	logtext "Test: Scanning for Apache binary..."
        IS_APACHE=`${HTTPDBINARY} -v | egrep '[aA]pache'`
        if [ "${IS_APACHE}" = "" ]; then
            logtext "${HTTPDBINARYI} is not Apache"
	    Display --indent 4 --text "- Identifying ${HTTPDBINARY}..." --result "NO MATCH" --color WHITE
          else
	    Display --indent 4 --text "- Identifying ${HTTPDBINARY}..." --result "FOUND" --color GREEN
            logtext "${HTTPDBINARY} seems to be Apache HTTP daemon"
             
	    APACHE_TEST=`${HTTPDBINARY} -V | grep "\-D SERVER_CONFIG_FILE=" | sed 's/[ ]-D SERVER_CONFIG_FILE=//' | tr -d '"' | tr -d ' '`

	    if [ "${APACHE_TEST}" = "" ]; then
	        Display --indent 8 --text "Result: Can't find the configuration file, so skipping some Apache related tests"
	      else	      
	        # We found a possible match. Checking if it's valid filename. If not, we need to add a prefix
	        if [ -f ${APACHE_TEST} ]; then
        	    APACHE_CONFIGFILE="${APACHE_TEST}"
		    Display --indent 8 --text "Result: Configuration file found: ${APACHE_CONFIGFILE}"
	          else
	            # Probably the prefix is missing, so we are going to search that
		    APACHE_HTTPDROOT=`${HTTPDBINARY} -V | grep "\-D HTTPD_ROOT=" | sed 's/[ ]-D HTTPD_ROOT=//' | tr -d '"' | tr -d ' '`
	            #echo "Apache root prefix: ${APACHE_HTTPDROOT}"
    		    #echo "Complete path to configuration file: ${APACHE_HTTPDROOT}/${APACHE_TEST}"
		    APACHE_TESTFILE="${APACHE_HTTPDROOT}/${APACHE_TEST}"
		    if [ -f ${APACHE_TESTFILE} ]; then
			APACHE_CONFIGFILE="${APACHE_TESTFILE}"					      
			Display --indent 8 --text "[Info] Configuration file found: ${APACHE_CONFIGFILE}"		        
	              else
			Display --indent 8 --text "[Notice] possible directory/file parts found, but still unsure what the real configuration file is. Skipping some Apache related tests"
	            fi
	        fi
	    fi

	    # Configuration specific tests
	    SERVERTOKENSFOUND=0
	    APACHE_CONFIGFILES="${APACHE_CONFIGFILE} /usr/local/etc/apache22/extra/httpd-default.conf"
	    for APACHE_CONFIGFILE in ${APACHE_CONFIGFILES}; do
	        if [ -f ${APACHE_CONFIGFILE} ]; then	            
	    	    # Check if option ServerTokens is configured
	    	    SERVERTOKENSTEST=`cat ${APACHE_CONFIGFILE} | grep ServerTokens | grep -v '^#'`
	    	    if [ ! "${SERVERTOKENSTEST}" = "" ]; then
			Display --indent 4 --text "- Checking option ServerTokens..." --result FOUND --color WHITE
	    		SERVERTOKENSTEST=`echo ${SERVERTOKENSTEST} | sed 's/ServerTokens//' | tr -d ' '`
			logtext "Option ServerTokens found: ${SERVERTOKENSTEST}"
			SERVERTOKENSEXPECTED=`cat ${PROFILE} | grep 'apache' | grep 'ServerTokens' | cut -d ':' -f3`
			if [ "${SERVERTOKENSEXPECTED}" = "${SERVERTOKENSTEST}" ]; then
			    logtext "Result: Value from configuration file yielded the same output as in template"
			    SERVERTOKENSFOUND=1
		          else
			    logtext "Warning: Value of ServerTokens within active configuration is different than from used template."
			    logtext "Found: ${SERVERTOKENSTEST}"
			    logtext "Expected: ${SERVERTOKENSEXPECTED}"
			fi
		      else
			Display --indent 4 --text "- Checking option ServerTokens..." --result "NOT FOUND" --color WHITE
		    fi
		
		    #YYY read all Apache modules
		
		
	        else
		  # File does not exist, skipping
		  logtext "File ${APACHE_CONFIGFILE} does not exist, so skipping tests on this file"
	      fi
	    done
	    
	    # Display results from checks
	    if [ ${SERVERTOKENSFOUND} -eq 1 ]; then
	        Display --indent 6 --text "- Value of ServerTokens..." --result OK --color GREEN
	      else	    
	        Display --indent 6 --text "- Value of ServerTokens..." --result WARNING --color RED
		report "warning[]=Value of 'ServerTokens' in Apache config is different than template"
	    fi
       fi 
       
       logtextbreak
    fi
    
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

#YYY insert PHP version here

logtext "Checking for presence php.ini"

PHPINILOCS="/etc/php.ini /usr/local/etc/php.ini"

PHPINIFILE=""
for I in ${PHPINILOCS}; do
  if [ -f ${I} ]; then
    PHPINIFILE=${I}
  fi
done

if [ ! "${PHPINIFILE}" = "" ]; then
    counttests
    Display --indent 2 --text "- Checking PHP..." --result FOUND --color WHITE
    
    logtext "Found ${PHPINIFILE}"

    logtext "Test: Checking expose_php option.."
    FIND=`cat ${PHPINIFILE} | grep 'expose_php = Off' | grep -v '^;'`
    if [ "${FIND}" = "" ]; then
        Display --indent 4 --text "- Checking expose_php option..." --result WARNING --color RED
	logtext "Warning: PHP option expose_php is possibly turned on, which can reveal useful information for attackers."
	logtext "Change the expose_php line to: expose_php = Off"
	logtext "Impact: MEDIUM"
      else
        Display --indent 4 --text "- Checking expose_php option..." --result OK --color GREEN
	logtext "Result: Found 'expose_php = Off'"
	logtext "Status: OK"
    fi	
  else
    Display --indent 2 --text "Checking PHP..." --result "NOT FOUND" --color WHITE
    logtext "Result: no php.ini file found"
fi
logtextbreak

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

InsertSection "System Tools"

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

    counttests
    SCANNEDPATHS=""
    Display --indent 2 --text "- Checking system binaries..."
    logtext "Starting binary scan..."
    for SCANDIR in ${BINPATHS}; do
        logtext "Test: Checking binaries in directory ${SCANDIR}"
        if [ -d ${SCANDIR} ]; then
	    Display --indent 4 --text "- Checking ${SCANDIR}... " --result FOUND --color GREEN
            SCANNEDPATHS="${SCANNEDPATHS}, ${SCANDIR}"
            logtext "Directory ${SCANDIR} exists. Starting directory scanning..."
    	    FIND=`ls ${SCANDIR}`
	    for I in ${FIND}; do
	      logtext "Binary: ${SCANDIR}/${I}"
    	    done
          else
	    Display --indent 4 --text "- Checking ${SCANDIR}... " --result "NOT FOUND" --color WHITE
            logtext "Directory ${SCANDIR} does NOT exist."
        fi
        logtextbreak
    done

    logtext "Scanned directories: ${SCANNEDPATHS}"
    logtextbreak

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

    counttests

    Display --indent 2 --text "- Starting file permissions check..."
    logtext "Test: Checking file permissions"
    logtext "Using profile ${PROFILE} for baseline."
    FIND=`cat ${PROFILE} | egrep '^permfile:|^permdir:' | cut -d: -f2`
    for I in ${FIND}; do

      logtext "Checking ${I}"
      CheckFilePermissions ${I}
      logtext "  Expected permissions: ${PROFILEVALUE}"
      logtext "  Actual permissions: ${FILEVALUE}"
      logtext "  Result: $PERMS"
      if [ "${PERMS}" = "FILE_NOT_FOUND" ]; then
	  Display --indent 4 --text "${I}" --result "NOT FOUND" --color WHITE
	elif [ "${PERMS}" = "OK" ]; then
	  Display --indent 4 --text "${I}" --result OK --color GREEN
	elif [ "${PERMS}" = "BAD" ]; then
	  Display --indent 4 --text "${I}" --result WARNING --color RED
	else
	  echo "UNKNOWN"
      fi
    done
    

#YYY enter file checks here
#

logtextbreak

wait_for_keypress

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

    . ${INCLUDEDIR}/tests_logging
    . ${INCLUDEDIR}/tests_banners
    . ${INCLUDEDIR}/tests_accounting

    # Custom tests
    if [ -f ${INCLUDEDIR}/tests_custom ]; then . ${INCLUDEDIR}/tests_custom; fi

#
#################################################################################
#
# Show test results overview
#
#################################################################################
#

report "lynis_tests_done=${CTESTS_PERFORMED}"

if [ ${QUIET} -eq 0 ]; then
    echo ""
    echo "================================================================================="
    echo ""
    echo "  -[ ${WHITE}${PROGRAM_name} ${PROGRAM_version} Results${NORMAL} ]-"
    echo ""
    echo "  ${SECTION}Tests performed${NORMAL}: ${CTESTS_PERFORMED}"

    # Show warnings from logfile
    SWARNINGS=`cat ${LOGFILE} | grep -i 'warning:' | sed 's/ /!space!/g'`

    if [ "${SWARNINGS}" = "" ]; then
        echo "${OK}No warnings${NORMAL}"
      else
        echo "  ${WARNING}Warnings${NORMAL}:"
        echo "  ----------------------------"
        for WARNING in ${SWARNINGS}; do
          SHOWWARNING=`echo ${WARNING} | sed 's/!space!/ /g'`
          echo "   - ${SHOWWARNING}"
        done
    fi

    echo "================================================================================"
    echo "  ${SECTION}Files${NORMAL}:"
    echo "  - Test and debug information      : ${WHITE}${LOGFILE}${NORMAL}."
    echo "  - Report data                     : ${WHITE}${REPORTFILE}${NORMAL}."
    echo "================================================================================"
    if [ $PROGRAM_LV -gt $PROGRAM_AC ]; then
      echo "  ${NOTICE}Notice: ${WHITE}${PROGRAM_name} update available${NORMAL}"
      echo "  Current version : ${WHITE}${PROGRAM_AC}${NORMAL}    Latest version : ${WHITE}${PROGRAM_LV}${NORMAL}"
      echo "================================================================================"
    fi
    echo "  ${PROGRAM_website}"
    echo "  ${PROGRAM_copyright}"
    echo "================================================================================"

    echo ""; echo ""
fi

logtext "${PROGRAM_name} ${PROGRAM_version} ended successfully"

# Bye bye PID file
RemovePIDFile

# A happy ending
exit 0

###########################################################################
##%HASH-SHA1%----------------------------%
##%TESTS-COUNT%50%
###########################################################################

#
#================================================================================
# Lynis - Copyright 2007-2008, Michael Boelen - www.rootkit.nl - The Netherlands
