I'm trying to create a simple honeypot using shell scripting. The script uses a while loop to keep a nc from stopping when the client closes the connection.
I wrote a function to kill all processes, including the script itself, to make sure that netcat will stop listening after the script is closed.
When I start the script, 3 processes honeypot.sh and 1 process n are created, when I close the script using ctrl-c and check the ps -a, the 3 honeypot.sh are gone, but the single nc is still there, and I have to kill it manually using killall -nc.
One interesting thing about this last nc process, is that even when the script is closed, I am still able to connect to the server, it even shows the banner, but this time, when I close the connection, the nc disappear and the server goes down as it should. - I wanted the server to close fully when the script closes.
Can someone show me what I'm doing wrong?
#! /usr/bin/bash
port="$1"
honeypot_pid=()
touch honeypot.log
# Handle SIGNI and kill created processes
function ctrl_c()
{
#kill "$honeypot_pid"
# wait
# cleanup
# exit 1
echo -e "\nEncerrando o servidor..."
for pid in "${honeypot_pid[@]}"; do
kill "$pid"
done
killall honeypot.sh
exit 1
}
# Netcat server
server ()
{
while true; do
( echo -e "--------" $(date) "--------\n" ; nc -vnlp $port < banner.txt) >> honeypot.log 2>&1
honeypot_pid+=($!)
done &
}
# Handles ctrl-c
trap ctrl_c INT
echo "Initializing server..."
ifconfig
server
# Show real time log
tail -f ./honeypot.log
I think by this:
you probably meant to do this:
or similar (check the syntax) so you have a loop running in a separate background process, with
ncrunning in the foreground of that process, and honeypot_pid containing the PID of that process so you can kill it later.That would still leave
ncorphaned though - I expect you can resolve that by enabling job control for that background process:and changing the kill command from
kill "$pid"tokill -- -"$pid"so that kills the process group of that process so it'll kill the subshell and anything being run from it, rather than just the subshell.