#!/bin/bash
#####################################################################
# Connection testing script for SFTP, manager and LDAP						
# Usage: ./test-connection <sftp|ldap> <connection parameters>"		
# Example 1: ./test-connection sftp 10.255.100.53 sftpuser encryptedpassword /
# Example 2: ./test-connection manager 10.111.2.11 engr encryptedpassword
# Example 3: ./test-connection ldap 10.141.0.240 389 cn=admin,dc=example,dc=com encryptedpassword ou=test,dc=example,dc=com all cn telephoneNumber
#
# Changelog:
# Initial creation: rpm69
# rpm77 - moving from /var/tmp/dtb into /var/pgsql/dtb_config/
# rpm2.0-1 - removing password from logs
# rpm2.0-11 - OSFOURK-26115 - provided password must now be encrypted due to injection sanitization
#####################################################################

# Import definitions
CMD=$(basename $0)
if [ -f /opt/dtb/bin/_common_definitions ]; then
    . /opt/dtb/bin/_common_definitions
else
	logger -t $CMD -p ERROR -s "The /opt/dtb/bin/_common_definitions file does not exist, exiting the script..."
	exit 1
fi

# Evaluate parameters: if the number of parameters is less than 1 or is not b or r then print out the help.
if [ $# -lt 1 ] || [ !"$1" == "sftp" ] || [ !"$1" == "ldap" ]; then
    logger -t $CMD -p ERROR -s "Usage: $0 <sftp|ldap> <connection parameters>"
    exit
fi

if [ "$1" == "sftp" ]; then
	plog "Testing SFTP connection"
	IP="$2"
	usr="$4"
	pwd="$5"
	pth="$3"
	pth=$(echo "$pth" | sed 's/ /\\ /g') # add \ before spaces
	outputVar="SFTP server"
	
	# Log the input parameters
	plog "SFTP host = $IP"
	plog "SFTP username = $usr"
	plog "SFTP path = $pth"
	
elif [ "$1" == "manager" ]; then
	plog "Testing Manager connection"
	IP="$2"
	usr="$3"
	pwd="$4"
	pth='/';
	outputVar="Manager"
	
	# Log the input parameters
	plog "Manager host = $IP"
	plog "Manager username = $usr"
	plog "Manager path = $pth"
	
elif [ "$1" == "ldap" ]; then
	plog "Testing LDAP connection..."
	IP="$2"
	port="$3"
	usr="$4"
	pwd="$5"
	baseDN="$6"
	filter="$7"
	name="$8"
	extension="$9"
	
	# Log the input parameters
	plog "LDAP host = $IP"
	plog "LDAP port = $port" 
	plog "LDAP username = $usr"
	plog "LDAP baseDN = $baseDN"
	plog "LDAP filter = $filter"
	plog "LDAP name field = $name"
	plog "LDAP extension field = $extension"

fi
	
# Check if IP format is 0..255.0..255.0..255.0..255
if [ `echo $IP | grep -o '\.' | wc -l` -ne 3 ]; then
	plog "ERROR: Exiting with: Invalid IP: does not contain 3 dots!"
	exit 1;
elif [ `echo $IP | tr '.' ' ' | wc -w` -ne 4 ]; then
	plog "ERROR: Exiting with: Invalid IP: does not contain 4 octets!"
	exit 1;
else
	for OCTET in `echo $IP | tr '.' ' '`; do
			if ! [[ $OCTET =~ ^[0-9]+$ ]]; then
					plog "ERROR: Exiting with: Invalid IP: an octet is not numeric!"
					exit 1;
			elif [[ $OCTET -lt 0 || $OCTET -gt 255 ]]; then
					plog "ERROR: Exiting with: Invalid IP: an octet in not in range 0-255!"
					exit 1;
			fi
	done
fi

pwd=$(echo $pwd | openssl aes-256-cbc -a -d -salt -k '1825e09252d7c6f66f5e1be666154306')
export expprompt=""
export secretpasswd=$pwd
export theexptimeout=15

if [ "$1" == "sftp" ] || [ "$1" == "manager" ]; then

	output=$(/opt/dtb/bin/auto-ssh-passwd.sh sftp $usr@$IP:$pth)
	
	if [[ $output == *"Connected to"* ]]; then
		if  [[ $output == *"not found"* ]]; then
			echo "The path $pth cannot be found." > $DTB_TESTRESULT;
			plog "Exiting with: The path $pth cannot be found."
			exit 1
		else
			echo "Connection OK." > $DTB_TESTRESULT;
			plog "Exiting with: Connection OK."
			exit 0
		fi
	fi
	
	if  [[ $output == *"No route to host"* ]] || [[ $output == *"Network is unreachable"* ]]; then
		echo "No route to $IP." > $DTB_TESTRESULT;
		plog "Exiting with: No route to $IP."
		exit 1
	fi
	
	if  [[ $output == *"The authenticity of host"* ]] || [[ $output == *"Connection refused"* ]]; then
		echo "Connection with $IP refused." > $DTB_TESTRESULT;
		plog "Exiting with: Connection with $IP refused."
		exit 1
	fi
	
	if  [[ $output == *"Permission denied"* ]]; then
		echo "Username or password is incorrect." > $DTB_TESTRESULT;
		plog "Exiting with: Username or password is incorrect."
		exit 1
	fi
	
	if  [[ $output == *"Connection timed out"* ]] || [[ $output == *"ERROR: timeout while waiting for following text"* ]]; then
		echo "Connection to host $IP has timed out." > $DTB_TESTRESULT;
		plog "Exiting with: Connection to host $IP timed out."
		exit 1
	fi
	
	echo "Connection has timed out. Please test the $outputVar manually with the following command: sftp $usr@$IP:$pth" > $DTB_TESTRESULT;
	plog "Exiting with: SFTP test END with unknown error."
	
	. /etc/profile
	export HOME=/root
	
elif [ "$1" == "ldap" ]; then
	
	# The * cannot be used as parameter
	if [ "$filter" == "all" ]; then 
		filter='';
	else
		filter=$filter;
	fi
	
	# Port 636 means secure LDAP
	if [[ "$port" == "s"* ]]; then 
		protocol="ldaps";
		port=${port:1};
	else
		protocol="ldap";
	fi
	
	# Anonymous search
	if [ "$usr" == "Anonymous" ]; then
		plog "Executing ldapsearch anonymously";
		plog "calling export LDAPTLS_REQCERT=never; ldapsearch -x -b \"$baseDN\" -H $protocol://$IP:$port $filter $name $extension"
		export LDAPTLS_REQCERT=never;
		timeout 10 export LDAPTLS_REQCERT=never; ldapsearch -x -b "$baseDN" -H $protocol://$IP:$port $filter $name $extension
	else
		plog "Executing ldapsearch with the provided credentials";
		# Credential search
		# -x: simple authentication
		# -b: base DN to bind
		# -H: ldap host
		# -D: username
		# -w: password
		# ldapsearch -x -b "ou=Users,dc=example,dc=com" -H ldap://10.112.0.240:389 -D "cn=admin,dc=example,dc=com" -w "Pom.uscat1" "objectclass=*" cn telephoneNumber
		plog "calling export LDAPTLS_REQCERT=never; ldapsearch -x -b \"$baseDN\" -H $protocol://$IP:$port -D \"$usr\" -w \"********\" $filter $name $extension"
		export LDAPTLS_REQCERT=never;
		timeout 10 ldapsearch -x -b "$baseDN" -H $protocol://$IP:$port -D "$usr" -w "$pwd" $filter $name $extension
	fi
	
	EXITCODE=$?
	plog "ldapsearch result is ${EXITCODE}"
	
	if [ ${EXITCODE} -eq 0 ]; then
		echo "Connection OK" > $DTB_TESTRESULT;
		plog "The authentication is successful."
	else
		if [ ${EXITCODE} == 124 ]; then  
			echo "Can't contact LDAP server. The connection timed out. Wrong IP or port." > $DTB_TESTRESULT;
			plog "Can't contact LDAP server. The connection timed out. Wrong IP or port."                                                                                     
		elif [ ${EXITCODE} == 255 ]; then
			echo "Can't contact LDAP server. Wrong IP or port." > $DTB_TESTRESULT;
			plog "Can't contact LDAP server. Wrong IP or port."
		elif ([ ${EXITCODE} == 49 ] || [ ${EXITCODE} == 53 ]); then
			echo "Invalid credentials. Wrong username or password." > $DTB_TESTRESULT;
			plog "Invalid credentials. Wrong username or password."
		elif [ ${EXITCODE} == 32 ]; then
			echo "Invalid baseDN. No such object." > $DTB_TESTRESULT;
			plog "Invalid baseDN. No such object."
		elif [ ${EXITCODE} == 249 ]; then
			echo "Bad search filter." > $DTB_TESTRESULT;
			plog "Bad search filter."
		elif [ ${EXITCODE} == 254 ]; then
			echo "Can't contact LDAP server." > $DTB_TESTRESULT;
			plog "Can't contact LDAP server."
		else
			echo "Unknown error." > $DTB_TESTRESULT;
			plog "Unknown error."
		fi
	fi
	exit ${EXITCODE}
fi
	

