#! /bin/bash
#
# Kali AWS Terraform Payload
#
# Set up following items:
# - A number of user accounts at kali linux defined as terraform variable (also keys for ssh)
# - Same number of VPN links (wireguard) running at kali linux 
# - Infection Monkey app (run as monkey user)
# - Audit service for tracking users activities
#
# NOTE: variable char is escaped with '$$', as single '$' is replaced at terraform level. 
#

WIREGUARD_INET=10.0.10

INPUT_SRV_WG_PUB=${SERVER_WG_PUB}
INPUT_SRV_WG_PRIV=${SERVER_WG_PRIV}

INPUT_USERS=(${USERS})
INPUT_PASSWORD=(${PASSWORDS})
INPUT_SSH_PUB=(${SSH_PUB})
INPUT_WG_PUB=(${WG_PUB})
INPUT_WG_PRIV=(${WG_PRIV})
INPUT_DUCKDNS="${DUCKDNS_DOMAIN}.duckdns.org"



echo "Name of the script: $0" >> /home/kali/init_debug.txt
echo "Total number of arguments: $#" >> /home/kali/init_debug.txt
echo "Values of all the arguments: $@" >> /home/kali/init_debug.txt

echo "---"  >> /home/kali/init_debug.txt
echo "Number of users: ${NUM_USERS}" >> /home/kali/init_debug.txt
echo "User names: $${INPUT_USERS}"    >> /home/kali/init_debug.txt
echo "User passwords: $${INPUT_PASSWORD}" >> /home/kali/init_debug.txt
echo "User SSH Pub Key: $${INPUT_SSH_PUB}" >> /home/kali/init_debug.txt
echo "User WireGuard Pub Keys: $${INPUT_WG_PUB}" >> /home/kali/init_debug.txt
echo "User WireGuard Priv Keys: $${INPUT_WG_PRIV}" >> /home/kali/init_debug.txt
echo "DynDNS Domain: $${INPUT_DUCKDNS}" >> /home/kali/init_debug.txt
echo "Log file: /var/log/cloud-init-output.log"  >> /home/kali/init_debug.txt
echo "---"  >> /home/kali/init_debug.txt
echo ""  >> /home/kali/init_debug.txt



touch /home/kali/.hushlogin

# To avoid user prompt during apt-get install 
echo '* libraries/restart-without-asking boolean true' | sudo debconf-set-selections

# Update package lists 
echo "Updating package list ..."  >> /home/kali/init_debug.txt
apt-get update -y
#echo "Upgrading ..."  >> /home/kali/init_debug.txt
#apt-get dist-upgrade -y

# reconfigure locales
echo "Reconfigure locales ..."  >> /home/kali/init_debug.txt
export LANG=en_US.utf8
update-locale LANG=en_US.UTF-8
dpkg-reconfigure --frontend noninteractive locales

# install locales
echo "Installing locales ..."  >> /home/kali/init_debug.txt
apt-get install locales-all -y
# touch /var/lib/cloud/instance/locale-check.skip

# install pip
echo "Installing pip3 ..."  >> /home/kali/init_debug.txt
apt-get install python3-pip libc-bin -y

apt-get install nmap hydra -y

# install docker
#curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add -
#echo 'deb [arch=amd64] https://download.docker.com/linux/debian buster stable' | tee /etc/apt/sources.list.d/docker.list
#apt-get install -y docker.io
#systemctl enable docker --now
#sudo usermod -aG docker kali

# install scoutsuite
#pip install ScoutSuite

# install pacu
#git clone https://github.com/RhinoSecurityLabs/pacu && mv ./pacu/ /home/kali/
#pip install -r /home/kali/pacu/requirements.txt
#chown -R kali:kali /home/kali/pacu/*
#cd /home/kali/pacu && bash install.sh && cd -

# install cloudsplaining - cloudsplaining.readthedocs.io/
# Cloudsplaining is an AWS IAM Security Assessment tool 
# that identifies violations of least privilege and generates
# a risk-prioritized report. 
#disabled# pip3 install cloudsplaining


###
### SET DYNAMIC DNS
###
mkdir /home/kali/duckdns
cat << DUCKDNS__EOF > /home/kali/duckdns/duck.sh
#!/bin/bash
current=""
while true; do
	latest=\$(ec2-metadata --public-ipv4 | cut -f2 -d" ")
	echo "public-ipv4=\$latest"
	if [ "\$current" == "\$latest" ]
	then
		echo "ip not changed"
	else
		echo "ip has changed - updating"
		current=\$latest
		echo url="https://www.duckdns.org/update?domains=${DUCKDNS_DOMAIN}&token=${DUCKDNS_TOKEN}&ip=" | curl -k -o ~/duckdns/duck.log -K -
	fi
	sleep 5m
done
DUCKDNS__EOF
chmod 700 /home/kali/duckdns/duck.sh

cat << DUCKDNSD__EOF > /home/kali/duckdns/duck_daemon.sh
#!/bin/bash
nohup /home/kali/duckdns/duck.sh > /home/kali/duckdns//duck.log 2>&1&
DUCKDNSD__EOF

sudo chown root /home/kali/duckdns/duck_daemon.sh
sudo chmod 744 /home/kali/duckdns/duck_daemon.sh
sudo ln -s /home/kali/duckdns/duck_daemon.sh /etc/rc2.d/S10duckdns
sudo /etc/rc2.d/S10duckdns





###
### SET WIREGUARD VPN
###

# Wireguard VPN Install & Set-Up
echo "Wireguard install and configuration"  >> /home/kali/init_debug.txt
apt-get install iptables wireguard wireguard-tools -y    

# Turn on IP forwarding 
sysctl -w net.ipv4.ip_forward=1             
sysctl -w net.ipv6.conf.all.forwarding=1    

# Generate WireGuard server keys
#taken now as parameter ---- wg genkey | tee /etc/wireguard/server-privatekey | wg pubkey | tee /etc/wireguard/server-publickey
echo "$${INPUT_SRV_WG_PUB}" > /etc/wireguard/server-publickey
echo "$${INPUT_SRV_WG_PRIV}" > /etc/wireguard/server-privatekey

# # Generate WireGuard client keys
wg genkey | tee /etc/wireguard/client-privatekey | wg pubkey | tee /etc/wireguard/client-publickey
# for user in ${USERS}
# do
#   echo "Creating wireguard key for user : $${user}"  >> /home/kali/init_debug.txt
#   wg genkey | tee /etc/wireguard/client-privatekey-$${user} | wg pubkey | tee /etc/wireguard/client-publickey-$${user}
# done

    
# Create server config file
cat << WG0__EOF > /etc/wireguard/wg0.conf
[Interface]
Address = 10.0.10.1/24
ListenPort = 51820
PrivateKey = $(cat /etc/wireguard/server-privatekey)

PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE;iptables -A FORWARD -o %i -j ACCEPT
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE;iptables -D FORWARD -o %i -j ACCEPT

[Peer]
PublicKey = $(cat /etc/wireguard/client-publickey)
AllowedIPs = 10.0.10.2/32

WG0__EOF

# Create client config file, admin vpn
cat << EOF_CLIENT > /home/kali/client_vpn.wg
[Interface]
PrivateKey = $(cat /etc/wireguard/client-privatekey)
ListenPort = 21841
Address = 10.0.10.2/32

[Peer]
PublicKey = $(cat /etc/wireguard/server-publickey)
AllowedIPs = 10.0.10.1/32,10.0.0.0/24,10.0.1.0/24
Endpoint = $${INPUT_DUCKDNS}:51820

# This is for if you're behind a NAT and
# want the connection to be kept alive.
PersistentKeepalive = 25

EOF_CLIENT



###
### CREATE USERS
###
INDEX=0
wg_client_peer_ip=10        # Variable to set different IPs to WireGuard clients
for i in $${INPUT_USERS[@]}
do
    user=$${INPUT_USERS[$${INDEX}]}
    pass=$${INPUT_PASSWORD[$${INDEX}]}
    ssh_key_pub=$${INPUT_SSH_PUB[$${INDEX}]}
    wg_key_pub=$${INPUT_WG_PUB[$${INDEX}]}
    wg_key_priv=$${INPUT_WG_PRIV[$${INDEX}]}

    echo " --- $${INDEX}: Creating $${user} $${pass} $${ssh_key_pub} $${wg_key_pub} $${wg_key_priv} --- " >> /home/kali/init_debug.txt

    echo "Creating user: $${user}"  >> /home/kali/init_debug.txt
    useradd -m -d /home/$${user} -g users -s /bin/bash $${user}
    # Create rsa pair keys
    mkdir -p /home/$${user}/.ssh
    touch /home/$${user}/.hushlogin
    #ssh-keygen -f /home/$${user}/.ssh/id_rsa -t rsa -N '' -q
    echo "$${ssh_key_pub} $${user}" >> /home/$${user}/.ssh/authorized_keys
    # Additional key
    ssh-keygen -q -t rsa -N '' -f /home/$${user}/.ssh/id_rsa <<<y >/dev/null 2>&1
    cat /home/$${user}/.ssh/id_rsa.pub >> /home/$${user}/.ssh/authorized_keys
    cp /home/$${user}/.ssh/id_rsa /home/kali/user_$${user}.key
    # Set passwords and save in home folder (needed for xrdp connection)
    echo $${pass} > /home/$${user}/password.txt
    echo "$${user}:$${pass}" | chpasswd
    ln -s /home/recursos /home/$${user}/recursos

    # Create WireGuard Secrets
    mkdir -p /etc/wireguard/
    echo $${wg_key_pub} > /etc/wireguard/client-publickey-$${user}
    echo $${wg_key_priv} > /etc/wireguard/client-privatekey-$${user}
    
    # Add user to WireGuard Server
    echo "Addind public key to wireguard server for user : $${user}"  >> /home/kali/init_debug.txt
    echo "" >> /etc/wireguard/wg0.conf
    echo "[Peer]" >> /etc/wireguard/wg0.conf
    echo "PublicKey = $${wg_key_pub}" >> /etc/wireguard/wg0.conf
    echo "AllowedIPs = 10.0.10.$${wg_client_peer_ip}/32" >> /etc/wireguard/wg0.conf
    echo "" >> /etc/wireguard/wg0.conf

    # Create user WireGuard file
    echo "Creating VPN Client file for user : $${user} - 10.0.10.$${wg_client_peer_ip}"  >> /home/kali/init_debug.txt
    cat << EOF_iCLIENT > /home/kali/client_vpn_$${user}.wg
[Interface]
PrivateKey = $${wg_key_priv}
ListenPort = 21841
Address = 10.0.10.$${wg_client_peer_ip}/32

[Peer]
PublicKey = $(cat /etc/wireguard/server-publickey)
AllowedIPs = 10.0.10.1/32,10.0.0.0/24,10.0.1.0/24
Endpoint = $${INPUT_DUCKDNS}:51820

# This is for if you're behind a NAT and
# want the connection to be kept alive.
PersistentKeepalive = 25

EOF_iCLIENT

    # Increment variables by '1'
    let wg_client_peer_ip=$${wg_client_peer_ip}+1
    # increase index
    let INDEX=$${INDEX}+1
done




# set restrictive permissions to private keys
chmod 600 /etc/wireguard/{server-privatekey*,client-privatekey*,wg0.conf}


# keep established connections
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT 
iptables -A OUTPUT -m state --state RELATED,ESTABLISHED -j ACCEPT 
# block connectivity to VPN clients (security zero trust) - for now I will disable this to allow reverse shells and similar staff
#iptables -A OUTPUT -p icmp  -s 10.0.10.0/24 -j DROP
#iptables -A OUTPUT -p tcp  -s 10.0.10.0/24 --dport 4000:4999 -m state --state NEW,ESTABLISHED -j ACCEPT
#iptables -A OUTPUT -p tcp  -s 10.0.10.0/24 -j DROP
#iptables -A OUTPUT -p udp  -s 10.0.10.0/24 -j DROP

# START WIREGUARD SERVICE
wg-quick up wg0     


# Set passwords and save in home folder (needed for xrdp connection)
kali_password="`openssl rand -base64 8`"
echo $${kali_password} > /home/kali/password.txt
echo "kali:$${kali_password}" | chpasswd
ln -s /home/recursos /home/kali/recursos

# Accept ssh keys for Vulnerable ssh login: ssh -o PubkeyAcceptedKeyTypes=ssh-rsa -i ~/.ssh/id_rsa ubuntu@10.0.1.5 
mkdir -p /home/kali/.ssh/
cat << SSH_CONFIG > /home/kali/.ssh/config
Host *
    PubkeyAcceptedKeyTypes +ssh-rsa
SSH_CONFIG

# ## Create users
# for user in ${USERS}
# do
#   echo "Creating user: $${user}"  >> /home/kali/init_debug.txt
#   useradd -m -d /home/$${user} -g users -s /bin/bash $${user}
#   # Create rsa pair keys
#   mkdir -p /home/$${user}/.ssh
#   touch /home/$${user}/.hushlogin
#   #ssh-keygen -f /home/$${user}/.ssh/id_rsa -t rsa -N '' -q
#   ssh-keygen -q -t rsa -N '' -f /home/$${user}/.ssh/id_rsa <<<y >/dev/null 2>&1
#   cat /home/$${user}/.ssh/id_rsa.pub >> /home/$${user}/.ssh/authorized_keys
#   cp /home/$${user}/.ssh/id_rsa /home/kali/user_$${user}.key
#   # Set passwords and save in home folder (needed for xrdp connection)
#   user_password="`openssl rand -base64 8`"
#   echo $${user_password} > /home/$${user}/password.txt
#   echo "$${user}:$${user_password}" | chpasswd
#   ln -s /home/recursos /home/$${user}/recursos

# done 

# Add PASSWORD LESS sudo for nmap
echo "PASSWORDLESS sudo for nmap"  >> /home/kali/init_debug.txt
echo "%users ALL=(ALL:ALL) NOPASSWD: /usr/bin/nmap" >> /etc/sudoers


## Change home folder to do not allow access for non-owners
chmod 750 /home/*

## Owner and permisions for VPN and User keys
chown kali:kali /home/kali/user*.key    # chg owner
chown kali:kali /home/kali/client_vpn*.wg    # chg owner


# Download and install Infection Monkey App
echo "Creating infection monkey user: monkey"  >> /home/kali/init_debug.txt
useradd -m -d /home/monkey -s /bin/bash monkey
su - monkey -c 'wget -O /home/monkey/Infection_Monkey-1.11.0-x86_64.AppImage https://github.com/guardicore/monkey/releases/download/v1.11.0/Infection_Monkey-1.11.0-x86_64.AppImage'
su - monkey -c 'chmod u+x /home/monkey/Infection_Monkey-1.11.0-x86_64.AppImage'
#chown monkey:monkey /home/monkey/Infection_Monkey-1.11.0-x86_64.AppImage
su - monkey -c 'nohup /home/monkey/Infection_Monkey-1.11.0-x86_64.AppImage > /home/monkey/Infection_Monkey-server.log 2>&1' &
# review list of vulnerabilities https://github.com/guardicore/monkey/blob/be5d354c069b9c996bcc77c3c740d6f7d8ef5541/envs/monkey_zoo/docs/fullDocs.md#machines

# Install Security Tools 
echo "Installing burpsuit and zaproxy"  >> /home/kali/init_debug.txt
apt-get install burpsuite -y
apt-get install zaproxy -y

# Create recursos folder
echo "Creating custom shared resources"  >> /home/kali/init_debug.txt
mkdir /home/recursos
chown kali:users /home/recursos
chmod 775 /home/recursos

# Generate password list for brute-force-attack lab
echo "Installing pydictor"  >> /home/kali/init_debug.txt
git clone https://github.com/LandGrey/pydictor.git /home/recursos/pydictor
python3 /home/recursos/pydictor/pydictor.py --head rwaaaaaw --len 2 2 -base dL --output /tmp
_file=`ls -rt1 /tmp | tail -1`
cat /tmp/$${_file} | egrep -v "[bcdefghijk1234569]" > /home/recursos/password_list.txt
chown -R kali:kali /home/recursos/* /home/kali/

# Install Remote Desktop Protocol (RDP)  
# echo "[+] Installing Xfce, this will take a while"  >> /home/kali/init_debug.txt
# apt-get install -y kali-desktop-xfce xorg xrdp
# apt-get install -y dbus-x11
# systemctl start xrdp
# systemctl enable xrdp
# /etc/init.d/xrdp start 

# Auditing for linux with Auditd
echo "Installing audit daemon"  >> /home/kali/init_debug.txt
apt-get install auditd audispd-plugins -y

# Create audit rules: guide https://www.tekfik.com/kb/linux/audit/audit-or-track-all-commands-linux
cat << EOF_AUDITD >> /etc/audit/rules.d/audit.rules

# Track all sudo commands" >> /etc/audit/rules.d/audit.rules
-a always,exit -F arch=b64 -S execve -F euid=0 -F auid>=1000 -F auid!=-1 -F key=sudo_log
-a always,exit -F arch=b32 -S execve -F euid=0 -F auid>=1000 -F auid!=-1 -F key=sudo_log

# Track all commands for USERS
-a exit,always -F arch=b32 -S execve -k allcmds -F auid>=1000 -F key=users_log
-a exit,always -F arch=b64 -S execve -k allcmds -F auid>=1000 -F key=users_log

EOF_AUDITD

service auditd start



# ToDO: send audit log to CloudWatch
#https://www.rapidspike.com/blog/how-to-send-log-files-to-aws-cloudwatch-ubuntu/

# Possible Update: IDS/IPS 
# apt-get install suricata -y
# setup https://redmine.openinfosecfoundation.org/projects/suricata/wiki/Basic_Setup
# https://suricata.readthedocs.io/en/latest/quickstart.html#running-suricata
# ubnt setup https://kifarunix.com/install-and-setup-suricata-on-ubuntu-18-04/

# Command line audit logging
# https://askubuntu.com/questions/1044669/bash-history-log-all-commands-to-syslog
#echo "" >> /etc/profile
#echo "# Command line audit logging" >> /etc/profile.d/cmdline_audit.sh
#echo "trap 'logger -p local1.notice -t bash -i -- \"\$${USER}:\$${COMMAND}\"' DEBUG" >> /etc/profile.d/cmdline_audit.sh


# /etc/rsyslog.conf
#echo "# command line audit logging" >> /etc/rsyslog.d/22-userlog.conf
#echo "local1.* -/var/log/cmdline"   >> /etc/rsyslog.d/22-userlog.conf

#/etc/init.d/rsyslog restart

echo "END"  >> /home/kali/init_debug.txt