Skip to content

Stop the reaper running instance-writable tags as root - #832

Merged
scttfrdmn merged 1 commit into
mainfrom
fix/830-reaper-prestop-root
Oct 11, 2026
Merged

scttfrdmn merged 1 commit into
mainfrom
fix/830-reaper-prestop-root

Conversation

@scttfrdmn

Copy link
Copy Markdown
Contributor

Closes #830. Advisory: GHSA-8q3p-qcv8-2pr4 (draft; publishes on merge).

Found while verifying the su -c username splice from the audit, which turns out to be
the smaller half of it.

The defect

tryGracefulPreStop (#187) reads the spawn:pre-stop tag and runs it through SSM
AWS-RunShellScript, which executes as root. The spored instance role holds
ec2:CreateTags on Resource: "*" conditioned on ec2:ResourceTag/spawn:managed=true —
so a spore can retag any other managed instance in the account, not only itself.

The chain needs no local privilege:

  1. Read the instance-role credentials from IMDS.
  2. create-tags on a victim instance: spawn:pre-stop = the attacker's command,
    spawn:local-username deleted, spawn:ttl-deadline set to the past.
  3. The reaper collects it, calls tryGracefulPreStop, and SSM runs the string as root.

The policy comment at pkg/aws/iam.go:909 reasons that the tag condition means a spore
"cannot pull a foreign instance into scope." That is accurate and was not sufficient:
re-tagging an instance already in scope is the attack, because a tag value is later
executed.

Two distinct paths reached root:

  • The privilege drop was conditional. if c.localUsername != "" made root the
    default for any instance missing that tag — or whose tag was deleted, which the same
    role can do.
  • The username was spliced unquoted into su - %s -c %s while the hook body beside
    it was quoted. su takes its first non-option argument as the user, so
    x -c 'id > /tmp/p' # supplied its own -c.

Fix

The reaper refuses to run the hook unless the tag names a valid, non-root POSIX user.
Refusing cannot weaken the hard-deadline guarantee (#72) — the caller terminates either
way, and losing the flush is already what happens when an instance isn't SSM-managed.
Running as root was never the intent: #63 is "run the hook as this user".

Construction moved into buildPreStopCommand because tryGracefulPreStop takes a
concrete *ssm.Client and cannot be faked, and because the guard belongs to the command
construction rather than the SSM plumbing (rule 2).

pkg/security is now imported rather than copied. Measured first, per the #106 lesson:
4 new packages, and the arm64 binary goes 69,936,112 → 69,948,287 bytes.

IAM half

Both spored policies gained an explicit Deny on ec2:CreateTags/ec2:DeleteTags
conditioned on ForAnyValue:StringEquals over aws:TagKeys.

  • Deny, not a narrower Allow — an explicit deny cannot be overridden by a later
    grant, and these two policies have already diverged in exactly that way once (the DCV
    copy granted CreateTags unconditioned while the dynamic baseline was being scoped for
    [HIGH] spored role grants unconditioned ec2:CreateTags on * → tag-then-terminate escalation #174).
  • ForAnyValue, not ForAllValues — the latter fires only when every requested key
    is a control key, so appending one innocuous tag to the request would defeat it.

Three keys, deliberately. The obvious longer list is wrong: spored writes
spawn:last-heartbeat every cycle and both writes and deletes spawn:ttl-deadline on
the spored ttl set path, so denying those would break idle detection and spored ttl
while reading as a hardening. Deadline tampering stays contained by the unconditional
max-age ceiling (#76) instead — the right tool precisely because that key has a
legitimate in-instance writer.

sporedDCVRolePolicy became a var so the list renders from the same slice
buildInlinePolicy uses and the two cannot drift. Unexported, so api/public-surface.txt
is unchanged.

11 simulations, both documents, allow and deny

simulate-custom-policy against each policy document:

action aws:TagKeys decision
CreateTags spawn:last-heartbeat allowed
CreateTags spawn:ttl, spawn:ttl-deadline allowed
CreateTags spawn:fsx-dra-status allowed
DeleteTags spawn:ttl-deadline allowed
CreateTags spawn:pre-stop explicitDeny
DeleteTags spawn:local-username explicitDeny
CreateTags spawn:last-heartbeat + spawn:pre-stop explicitDeny

The mixed row is the one that matters: it is what distinguishes ForAnyValue from
ForAllValues, and a policy with the wrong operator passes every other row.

Corrections to what I wrote on #830

Not exploitable in the current deployment, and I said otherwise. I claimed the path
was live in 435415984226 because the cross-account role holds a working SendCommand. The
grant is there; the code path is not reached — spawn-ttl-reaper-production sets no
REAPER_GRACEFUL, and tryGracefulPreStop is called only under if r.graceful
(main.go:614). The whole graceful tier is dead code in production. It arms the moment
#187 is enabled as documented, so this is latent, not closed. Checking the grant without
checking the invocation is the inverse of the #818 mistake, same day.

The IAM half does need remediation, unlike #818. spored-instance-role in
435415984226 carries ec2:CreateTags conditioned only on spawn:managed=true and zero
Deny statements today. The role is rewritten on each launch, so a launch from a build
containing this change updates it; a long-lived role keeps the old grant until then. The
reaper code fix is the independent and higher-priority half — it closes the escalation
without waiting for any policy to reach any instance. Deploying the reaper is a live
change and I have not made it.

Gates

Ten, every one watched failing against a revert that compiles.

lambda/ttl-reaper/prestop_test.go:

  • TestBuildPreStopCommandNeverRunsAsRoot — 11 hostile spawn:local-username values.
    This gate found a real gap the audit missed: security.ValidateUsername accepts
    root, so su - root -c … was a no-op privilege drop. Written from the intent ("never
    as root") rather than from the code, so it failed on first run instead of certifying the
    behaviour — rule 5 working as advertised.
  • TestBuildPreStopCommandDropsPrivilegeAndQuotesTheHook
  • TestOnlyBuildPreStopCommandConstructsAnSuInvocation — exactly one su - %s in
    main.go, so the validation cannot be bypassed by a second path.
  • TestReaperREADMEDescribesTheGracefulTierItActuallyHas

pkg/aws/reaper_control_tags_test.go:

  • TestBothSporedPoliciesDenyTheReaperControlTagKeys — runs against both documents, and
    names the ForAllValues trap in the failure message.
  • TestNoDeniedTagKeyHasAnInInstanceWriter — the gate that caught my mistake. It
    greps pkg/agent and cmd/spored for every literal spawn: tag key handed to
    CreateTags/DeleteTags and fails if a denied key has a writer; it fails on empty discovery
    and sanity-checks itself against spawn:last-heartbeat so a regex that stops matching
    cannot pass.
  • TestTheExecutedTagKeysAreDenied — a floor, not an inventory.

Reverts: dropping the deny from one policy; swapping to ForAllValues:StringNotEquals;
adding spawn:last-heartbeat to the list; removing spawn:pre-stop; dropping
CreateTags from the deny actions; restoring the conditional privilege drop; splicing the
username unquoted; adding a second su path; and both stale README sentences. Each fails
the intended gate with a message naming the defect.

Two existing gates this exposed as broken

Two stale README claims

lambda/ttl-reaper/README.md said a reaper-kill "does not run the in-instance pre-stop
hook" — written before #187 added exactly that. Someone auditing the reaper's blast radius
would have concluded there was no SSM execution path at all.

It also said "Within-deadline instances are always spared", which my own #76 change
invalidated
and I did not update. The ceiling is the control against a spore writing
itself a far-future deadline, so a page promising the opposite is the most misleading line
available. TestReaperDocsAgreeThatTheCeilingBeatsAFarFutureDeadline now covers the README
alongside main.go and template.yaml — it was the one page left out and the one a reader
reaches first. Four link references (#76, #187, #247, #438) also had no definition
and rendered as literal text.

Verification

make check (all 9 nested modules), make check-docs, changelog gate,
scripts/lambda-deploy-census.sh, semgrep scan --config=auto --error ., make api-snapshot (no drift), Tier 0 e2e with -count=1 — all clean. lambda/ttl-reaper is
go mod tidy-clean and builds under -mod=readonly.

Separately filed from this work: #831 — none of the four e2e make targets pass -count=1,
and a cached pass certifies a bin/spawn replaced by exit 1.

The graceful pre-stop tier (#187) read the spawn:pre-stop tag and ran it
through SSM AWS-RunShellScript, which executes as root, and the spored
instance role holds ec2:CreateTags on Resource "*" for every instance
carrying spawn:managed=true. So any principal with one spore's
instance-role credentials — including any unprivileged local user on that
spore, via IMDS — could rewrite ANOTHER instance's spawn:pre-stop and
spawn:ttl-deadline and get root command execution there when the reaper
next collected it. In a team-shared account that is cross-tenant root RCE.

Two paths reached root and both are closed. The privilege drop was
conditional (`if localUsername != ""`), so a missing — or deleted, which
the same role could do — tag ran the hook as root outright. And the
username was spliced into `su - %s -c ...` unquoted while the hook body
beside it was quoted, so `x -c '...' #` supplied its own -c.

The reaper now refuses to run the hook unless the tag names a valid,
non-root POSIX user. Refusing cannot weaken the hard deadline (#72): the
caller terminates either way, and losing the flush is already what
happens when an instance isn't SSM-managed. Running as root was never
the intent — #63 is "run the hook as this user". Command construction
moved to buildPreStopCommand so the guard is testable where it lives;
tryGracefulPreStop takes a concrete *ssm.Client and could not be driven.
security.ValidateUsername accepts "root", so that is refused explicitly
— found by a gate written from the intent rather than the code.

Both spored policies gained an explicit Deny on ec2:CreateTags and
ec2:DeleteTags over aws:TagKeys for spawn:pre-stop,
spawn:pre-stop-timeout and spawn:local-username. Deny because an
explicit deny cannot be overridden by a later grant and these two
policies have diverged that way before; ForAnyValue because ForAllValues
fires only when every requested key is a control key, so one innocuous
tag would defeat it. The list is three keys deliberately: spored writes
spawn:last-heartbeat and both writes and deletes spawn:ttl-deadline, so
denying those breaks idle detection and `spored ttl` while reading as
hardening. Deadline tampering stays contained by the max-age ceiling
(#76) instead. sporedDCVRolePolicy became a var so the list renders from
the same slice and cannot drift.

Also fixes two gates this exposed as broken —
TestSporedTagPermissionsScoped matched Action without reading Effect,
and TestBuildInlinePolicy asserted literal statement counts — and two
stale README claims, including "Within-deadline instances are always
spared", which the #76 ceiling invalidated.

Refs GHSA-8q3p-qcv8-2pr4
Closes #830
@scttfrdmn scttfrdmn added this to the Security audit 2026-10 milestone Oct 11, 2026
@codecov

codecov Bot commented Oct 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@scttfrdmn
scttfrdmn merged commit 05a6d9f into main Oct 11, 2026
7 checks passed
@scttfrdmn
scttfrdmn deleted the fix/830-reaper-prestop-root branch October 11, 2026 18:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Reaper: stop executing tag-sourced strings as root, and deny the control tag keys to the instance role

1 participant