Repository navigation
Stop the reaper running instance-writable tags as root - #832
Merged
Merged
Conversation
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
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #830. Advisory: GHSA-8q3p-qcv8-2pr4 (draft; publishes on merge).
Found while verifying the
su -cusername splice from the audit, which turns out to bethe smaller half of it.
The defect
tryGracefulPreStop(#187) reads thespawn:pre-stoptag and runs it through SSMAWS-RunShellScript, which executes as root. Thesporedinstance role holdsec2:CreateTagsonResource: "*"conditioned onec2: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:
create-tagson a victim instance:spawn:pre-stop= the attacker's command,spawn:local-usernamedeleted,spawn:ttl-deadlineset to the past.tryGracefulPreStop, and SSM runs the string as root.The policy comment at
pkg/aws/iam.go:909reasons 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:
if c.localUsername != ""made root thedefault for any instance missing that tag — or whose tag was deleted, which the same
role can do.
su - %s -c %swhile the hook body besideit was quoted.
sutakes its first non-option argument as the user, sox -c 'id > /tmp/p' #supplied its own-c.Fix
The reaper refuses to run the hook unless the tag names a valid, non-
rootPOSIX 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
buildPreStopCommandbecausetryGracefulPreStoptakes aconcrete
*ssm.Clientand cannot be faked, and because the guard belongs to the commandconstruction rather than the SSM plumbing (rule 2).
pkg/securityis 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
Denyonec2:CreateTags/ec2:DeleteTagsconditioned on
ForAnyValue:StringEqualsoveraws:TagKeys.Deny, not a narrowerAllow— an explicit deny cannot be overridden by a latergrant, and these two policies have already diverged in exactly that way once (the DCV
copy granted
CreateTagsunconditioned while the dynamic baseline was being scoped for[HIGH] spored role grants unconditioned ec2:CreateTags on * → tag-then-terminate escalation #174).
ForAnyValue, notForAllValues— the latter fires only when every requested keyis 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-heartbeatevery cycle and both writes and deletesspawn:ttl-deadlineonthe
spored ttl setpath, so denying those would break idle detection andspored ttlwhile 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.
sporedDCVRolePolicybecame avarso the list renders from the same slicebuildInlinePolicyuses and the two cannot drift. Unexported, soapi/public-surface.txtis unchanged.
11 simulations, both documents, allow and deny
simulate-custom-policyagainst each policy document:aws:TagKeysspawn:last-heartbeatspawn:ttl,spawn:ttl-deadlinespawn:fsx-dra-statusspawn:ttl-deadlinespawn:pre-stopspawn:local-usernamespawn:last-heartbeat+spawn:pre-stopThe mixed row is the one that matters: it is what distinguishes
ForAnyValuefromForAllValues, 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. Thegrant is there; the code path is not reached —
spawn-ttl-reaper-productionsets noREAPER_GRACEFUL, andtryGracefulPreStopis called only underif 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-rolein435415984226 carries
ec2:CreateTagsconditioned only onspawn:managed=trueand zeroDenystatements today. The role is rewritten on each launch, so a launch from a buildcontaining 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 hostilespawn:local-usernamevalues.This gate found a real gap the audit missed:
security.ValidateUsernameacceptsroot, sosu - root -c …was a no-op privilege drop. Written from the intent ("neveras root") rather than from the code, so it failed on first run instead of certifying the
behaviour — rule 5 working as advertised.
TestBuildPreStopCommandDropsPrivilegeAndQuotesTheHookTestOnlyBuildPreStopCommandConstructsAnSuInvocation— exactly onesu - %sinmain.go, so the validation cannot be bypassed by a second path.TestReaperREADMEDescribesTheGracefulTierItActuallyHaspkg/aws/reaper_control_tags_test.go:TestBothSporedPoliciesDenyTheReaperControlTagKeys— runs against both documents, andnames the
ForAllValuestrap in the failure message.TestNoDeniedTagKeyHasAnInInstanceWriter— the gate that caught my mistake. Itgreps
pkg/agentandcmd/sporedfor every literalspawn:tag key handed toCreateTags/DeleteTags and fails if a denied key has a writer; it fails on empty discovery
and sanity-checks itself against
spawn:last-heartbeatso a regex that stops matchingcannot pass.
TestTheExecutedTagKeysAreDenied— a floor, not an inventory.Reverts: dropping the deny from one policy; swapping to
ForAllValues:StringNotEquals;adding
spawn:last-heartbeatto the list; removingspawn:pre-stop; droppingCreateTagsfrom the deny actions; restoring the conditional privilege drop; splicing theusername unquoted; adding a second
supath; and both stale README sentences. Each failsthe intended gate with a message naming the defect.
Two existing gates this exposed as broken
TestSporedTagPermissionsScopedmatched statements byActionwithout readingEffect, so it read the newDenyas an unconditioned grant. AnActionmatch alonecannot tell a grant from a prohibition. Re-verified that it still fails on a genuinely
unconditioned
Allow.TestBuildInlinePolicyasserted literal statement counts (6 and 7), so every statementlegitimately added to the spored baseline over the past year ([HIGH] spored role grants unconditioned ec2:CreateTags on * → tag-then-terminate escalation #174, [HIGH] dns-updater accepts unsigned identity docs + default-allows cross-account → Route53 spoofing #173, spored did not mount the async-created ephemeral FSx after it reached AVAILABLE (no mount, no log lines) — #194 not firing #221, --fsx-import-path silently does nothing: spored's DRA create always fails on a missing iam:CreateServiceLinkedRole, leaving an empty 1200 GB filesystem #622)
failed it for no reason and taught whoever hit it to bump a number. It now measures the
baseline and asserts the two properties meant: a known template adds statements, an
unknown one adds none. Verified against a revert that makes templates contribute nothing.
Two stale README claims
lambda/ttl-reaper/README.mdsaid a reaper-kill "does not run the in-instance pre-stophook" — 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.
TestReaperDocsAgreeThatTheCeilingBeatsAFarFutureDeadlinenow covers the READMEalongside
main.goandtemplate.yaml— it was the one page left out and the one a readerreaches first. Four link references (
#76,#187,#247,#438) also had no definitionand 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-reaperisgo 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/spawnreplaced byexit 1.