#!/bin/bash
# 
# Atomicorp Inc
# Copyright 2021
# AWP full diagnostics
# 

VERSION="1.0.3"

TYPE=$1

if [ ! $TYPE ]; then
	echo "Atomicorp Diagnostics (${VERSION})"
	echo
	echo "  Usage: $0 <agent|server>"
	echo
	exit 1
fi


# Functions

# Input validation function 
# check_input <msg> <valid responses regex> <default>
# if <default> is passed on as null, then there is no default
# Example: check_input  "Some question (yes/no) " "yes|no"  "yes"
function check_input {
  message=$1
  validate=$2
  default=$3

  while [ $? -ne 1 ]; do
    echo -n "$message "
    read INPUTTEXT < /dev/tty
    if [ "$INPUTTEXT" == "" -a "$default" != "" ]; then
      INPUTTEXT=$default
      return 1
    fi
    echo $INPUTTEXT | egrep -q "$validate" && return 1
    echo -e "  ${RED}ERROR: Invalid input ${DEFAULT}"
  done
}

function valid_ip() {
    local  ip=$1
    local  stat=1

    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        OIFS=$IFS
        IFS='.'
        ip=($ip)
        IFS=$OIFS
        [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
            && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
        stat=$?
    fi
    return $stat
}



# Test permissions
function check_perms() {
        TARGET_PATH=$1
        TARGET_PERMS=$2
        MSG=$TARGET_PATH

        echo -n "    $MSG: "

        if [ -f $TARGET_PATH ] || [ -d $TARGET_PATH ]; then
                PERMS=$(stat -c "%U.%G  %A" $TARGET_PATH)
                if  [[ "$PERMS" == "${TARGET_PERMS}" ]]; then
                        echo "PASS"
                else
                        echo "FAIL"
                        echo "      Should be ${TARGET_PERMS}"
                fi
        else
                        echo "FAIL"
                        echo "      file not found"
        fi
}

# Test an Atomic agent

function test_agent() {

	############
	# OSSEC
	############

	echo
	echo "################################"
	echo "Atomic OSSEC agent Diagnostics"
	echo "################################"
	echo

	# Network connections
	if  [ -f /var/ossec/etc/ossec.conf ]; then
		IP_ADDRESS=$(grep -oP '<address>\S+</address>' /var/ossec/etc/ossec.conf  | sed -e 's/<address>\(.*\)<\/address>/\1/')

	fi
	
	if [ ! $IP_ADDRESS ] ; then
		read -p "Enter Hub ip address: " IP_ADDRESS

		if ! valid_ip $IP_ADDRESS; then
			echo "  IP address ${IP_ADDRESS} is not valid" 
			echo
			exit 1

		fi

	fi

	TCP_PORTS="80 443 1514 1515"

	echo
	echo "  Checking network connectivity"
	for port in $TCP_PORTS; do
		echo -n "    testing TCP $port :"

		timeout 3 bash -c "</dev/tcp/${IP_ADDRESS}/${port}" >/dev/null 2>&1
		if [ $? -eq 0 ]; then
			echo PASS
		else
			echo FAIL
		fi
		
	done

	# TODO: udp checks with nc


	#Does hub have a valid SSL cert
	
	echo 
	echo -n "  Checking HUB ${IP_ADDRESS} SSL Certificate: "
	if curl https://${IP_ADDRESS} >/dev/null 2>&1 ; then
		echo PASS
	else
		echo FAIL
	fi

	# Is ossec installed
	echo
	echo  -n "  Checking for agent installation: "
	if [ ! -f /var/ossec/bin/ossec-agentd ]; then
		echo "FAIL"
		exit 1
	else
		echo "PASS"

	fi
	
	# Check users
        USERS="ossec"
	echo
        echo "  Verifing user accounts"

        for username in $USERS; do
                echo -n "    ${username}: "
                if id ${username} &>/dev/null ; then
                        echo PASS
                else
                        echo FAIL

                fi
        done

	# Check groups
	echo
	echo "  Verifying groups"
	for username in $USERS; do
		echo -n "    ${username} in ossec: "
		if id -nG ${username} | grep -qw "ossec" ; then
			echo PASS	
		else
			echo FAIL	
		fi
	done


	# Test permissions
        echo
        echo "  Verifying permissions"
        #check_perms /var/ossec "root.ossec  dr-xr-x---"
        check_perms /var/ossec/etc "root.ossec  drwxrwx---"
        check_perms /var/ossec/etc/client.keys "ossec.ossec  -rw-r-----"
        check_perms /var/ossec/etc/internal_options.conf "root.root  -rw-r--r--"
        check_perms /var/ossec/logs "ossec.ossec  drwxr-x---"
        check_perms /var/ossec/queue "root.ossec  drwxr-x---"
        check_perms /var/ossec/queue/db "root.ossec  drwxrwxr-x"
        check_perms /var/ossec/var/wodles/ "root.ossec  drwxrwx---"


	# Test services
	echo
        echo "  Verifying daemons with (-t)"
        DAEMONS="ossec-execd ossec-logcollector ossec-modulesd ossec-syscheckd ossec-agentd"
        for daemon in ${DAEMONS}; do

                echo -n "    $daemon: "
                /var/ossec/bin/$daemon -t >/dev/null 2>&1
                if [ $? -eq 0 ]; then
                        echo "PASS"
                else
                        echo "FAIL"
                        echo
                        echo "      DEBUG Output"
                        echo
                        /var/ossec/bin/$daemon -t
                        echo
                fi
        done






}



# Test an Atomic Server
function test_server() {


	############
	# OSSEC
	############

	echo
	echo "################################"
	echo "Atomic OSSEC Server Diagnostics"
	echo "################################"
	echo

	# Test 0: Do the users exist
	USERS="ossec ossecr ossecm ossece"
	echo "  Verifing user accounts"

	for username in $USERS; do
		echo -n "    ${username}: "
		if id ${username} &>/dev/null ; then
			echo PASS
		else
			echo FAIL
			
		fi
	done
	echo


	# Test 1: -t all daemons
	echo "  Verifying daemons with (-t)"
	DAEMONS="ossec-agentlessd ossec-authd ossec-clusterd ossec-csyslogd ossec-db ossec-execd ossec-logcollector ossec-modulesd ossec-monitord ossec-remoted ossec-syscheckd"
	for daemon in ${DAEMONS}; do
			
		echo -n "    $daemon: "
		/var/ossec/bin/$daemon -t >/dev/null 2>&1
		if [ $? -eq 0 ]; then
			echo "PASS"
		else
			echo "FAIL"
			echo
			echo "      DEBUG Output"
			echo
			/var/ossec/bin/$daemon -t
			echo
		fi
	done


	echo
	echo
	echo "  Verifying permissions"
	check_perms /var/ossec "root.ossec  dr-xr-x---" 
	check_perms /var/ossec/etc "root.ossec  drwxrwx---"
	check_perms /var/ossec/etc/client.keys "root.ossec  -rw-r--r--"
	check_perms /var/ossec/etc/internal_options.conf "root.root  -rw-r--r--"
	check_perms /var/ossec/etc/lists/threat/threat1.cdb "root.ossec  -rw-rw----"
	check_perms /var/ossec/etc/rules.d "ossec.ossec  drwxrwx---"
	check_perms /var/ossec/etc/decoders.d "ossec.ossec  drwxrwx---"
	check_perms /var/ossec/logs "ossec.ossec  drwxr-x---"
	check_perms /var/ossec/logs/alerts "ossec.ossec  drwxrwx---"
	check_perms /var/ossec/logs/alerts/2021 "ossec.ossec  drwxr-x---"
	check_perms /var/ossec/queue "root.ossec  dr-xr-x---"
	check_perms /var/ossec/queue/fim "ossec.ossec  drwxr-x---"
	check_perms /var/ossec/queue/fim/db "ossec.ossec  drwxr-x---"
	check_perms /var/ossec/queue/db "ossec.ossec  drwxr-x---"
	check_perms /var/ossec/queue/vulnerabilities "ossec.ossec  drwxr-x---"
	check_perms /var/ossec/queue/vulnerabilities/dictionaries "ossec.ossec  drwxr-x---"
	check_perms /var/ossec/var/wodles/ "root.ossec  drwxrwx---"


	# AGENTS
	echo
	echo
	echo "  Agent checks"
	AGENT_COUNT=$(/var/ossec/bin/agent_control -lc -s | egrep , |egrep -v server |wc -l)
	if [ $AGENT_COUNT -lt 1 ]; then
		echo "    Connected Agent count is ${AGENT_COUNT}: FAIL"
	else
		# We have agents
		echo "    Agent count is ${AGENT_COUNT}"

		# Enumerate Active agents, then look at their data fields
		# look at the connected agents and look to see if they're not null
	fi

	# Verify agentconf


	# look at groups
		# are there groups
		# check that agent groups thing in internal isnt set
		# are there agents in undefined
		# check for ossec-db restarting over and over

	# internal options

	# remoted
		# is it on
		# is it listening on the right port
		# are the firewall rules open

	# authd
		# is it on
		# is it on the right port
		# are the firewall rules open


	# Vulnerability scanner data

				# cve.db?

		
	# AWP

}

# Main
if [[ $TYPE == server ]]; then
	test_server
elif [[ $TYPE == agent ]]; then
	test_agent

else
	echo "$TYPE invalid"
	exit 1

fi


echo
echo

