#!/bin/sh
#
# setup.sh
# Move files about, run test, and start things
# By J. Stuart McMurray
# Created 20250504
# Last Modified 20250511

set -euo pipefail

echo "---- $(date) -- Setup starting ----"

# Make sure the code looks normal locally
make build test

# Copy all the files we need to the droplets.
(
        RSYNC="rsync \
                --delete \
                --delete-excluded \
                --exclude '/.git/' \
                --exclude *.swp \
                --itemize-changes \
                --omit-dir-times \
                --perms \
                --recursive \
                --relative \
                --times"
        set -x
        # Copy files about.
        $RSYNC . --exclude '/crs/files/libcrsconn.so'    ops:lutlol/
        $RSYNC bin/vulnerableserver t_victim victim:
        $RSYNC authorized_keys \
                victim:.ssh/authorized_keys
        $RSYNC procrastinationedr.specs rc.local root@victim:/etc/
        $RSYNC procrastinationedr startprocrastinationedr.sh \
                        root@victim:/usr/local/sbin/
)

# Make sure our code is solid and put the demo code in ~.
ssh -qtt ops '
. ./.profile
set -xeuo pipefail
go install -trimpath -ldflags "-w -s" \
        github.com/magisterquis/curlrevshell@bettertemplates
cd lutlol
make test install
rsync \
        --delete \
        --itemize-changes \
        --omit-dir-times \
        --recursive \
        --times \
        ./exploit.sh ./crs ../
'

# Make sure we're up to date, EDR's going and we have a veth pair.
ssh -T root@victim <<'_eof'
set -xeuo pipefail
export DEBIAN_FRONTEND=noninteractive
apt-get -y -qq update
apt-get -y -qq upgrade
apt-get -y -qq dist-upgrade
apt-get -y -qq autoremove
if ! pgrep -Ax procrastination >/dev/null; then
        /usr/local/sbin/startprocrastinationedr.sh
fi
pkill -CONT procrastination
ps awwwfux | egrep "procrastinationed[r]"
if ! grep eth10 /proc/net/dev; then
        ip link add eth10 type veth peer name eth11
fi
_eof

# (Re)start the server process.
ssh -T victim <<'_eof'
set -xeuo pipefail
chmod 0755 bin/vulnerableserver
unset SSH_CLIENT SSH_CONNECTION SSH_TTY
>log
( pkill -Ax vulnerableserve; pidwait -Ax vulnerableserve) ||:
PATH=$HOME/bin:$PATH \
        VULNERABLE_SERVER_PASSWORD=b6974f35b717c68ee1455840c884c4ac \
        vulnerableserver \
        -domain victim.not-h4x.lol \
        >log 2>&1 </dev/null &
ps awwwfux | egrep "vulnerableserve[r]"
_eof

# Make sure everything looks ok.
(
        set -x
        ssh -qtt linuxbuild 'cd lutlol && bmake test'
        ssh -qtt ops        '. ./.profile && cd lutlol && prove -It t_ops'
        ssh -qtt victim     'prove --directives t_victim'
)

# Kill SSH connections to the victim
(
        set -x
        ssh      victim -qO exit
        ssh root@victim -qO exit
)

echo "---- $(date) -- Setup complete ----"
