Recon Labs #1, a Weekly Recon series.
Hands-on lab · about 50 to 60 minutes (about 20 of it waiting) · costs less than one cent · AWS console + CloudShell
I see this all the time. You lock down an S3 bucket, Block Public Access is on, and a direct link without a signature can't open the files. Then someone clicks Share with a presigned URL and pastes the link into an email or a ticket. That link works for anyone who has it, as many times as they like, until it expires. Whoever makes the link sets a requested lifetime: up to 12 hours from the console, up to 7 days from code, though it can end sooner if the signing credentials expire or a policy blocks it. Those links end up in chat, email, browser history, screenshots and proxy logs, and Block Public Access does not stop them.
In this lab you'll replay a leaked link, find it in CloudTrail, and add a bucket rule that blocks links older than 2 minutes:
🔴 Red: share a private file, then replay the same link minutes later
🔍 Spot it: find the replay in CloudTrail, and how old the link was
🔵 Blue: add one bucket rule so old links stop working
✅ Prove it: show the old link is dead and the rest still works
🧹 Clean up: delete everything and check that nothing's left
Terminal images are from the November 17, 2026 sandbox run. Console screenshots were captured separately, so some bucket names differ.
A few words you'll see
S3 bucket: where you store files ("objects") in AWS.
Presigned URL (share link): a signed link. Anyone with it can download the file, no login.
CloudShell: a command line in the AWS console. Nothing to install.
CloudTrail: AWS's audit log.
Bucket policy: rules on a bucket for who can do what.
HTTP 200 / 403: 200 means the file came back. 403 means forbidden.
Before you start
You need:
A personal or sandbox AWS account. Please don't use production.
Admin rights, or permissions to use CloudShell plus S3 and CloudTrail for this lab.
A web browser.
Region US East (N. Virginia) us-east-1, picked before you open CloudShell, and kept for the whole lab.
💵 Cost: under one cent, as long as you clean up. CloudShell is free.
⏳ About 20 minutes is waiting for the audit log. Read ahead.
Part 1: Set up (15 minutes)
Step 1: Create a private bucket
Open the S3 console's create page: https://us-east-1.console.aws.amazon.com/s3/bucket/create?region=us-east-1
Bucket name: something unique, like
lab-reports-yourname-4821. Use lowercase letters, digits and hyphens, add a few random digits, and keep it under 50 characters so-logsstill fits.Leave everything else as it is. Scroll down and check that Block all public access is ticked (it's on by default).
Click Create bucket at the bottom.

Pick a unique name and leave Block all public access ticked
Step 2: Confirm it's private
Click your new bucket, then open the Permissions tab and check that Block all public access is On under "Block public access".

Block all public access is On
Step 3: Upload a fake "customer report" from CloudShell
Click the CloudShell button, in the bottom-left corner or the
>_icon in the top bar. Give it about 30 seconds to start.Copy and paste the lines below. When you paste more than one line, CloudShell shows a Safe Paste box. Check the text and click Paste.
✏️ Change the first line to your bucket name first. Use a new empty folder in CloudShell, so these file names don't overwrite something you already have.
BUCKET=lab-reports-yourname-4821 # <-- change to your bucket name
printf 'FAKE customer report for a security lab. No real data.\n' > customer-report.txt
printf 'Account: ACME-0001 Balance: $1,234.56\n' >> customer-report.txt
aws s3 cp customer-report.txt "s3://$BUCKET/customer-report.txt"You should see a line starting with upload:.

The fake report is uploaded
Now try a normal link, with no signature:
curl -sS -o /dev/null -w "HTTP %{http_code}\n" \
"https://$BUCKET.s3.amazonaws.com/customer-report.txt"
A plain link is refused (HTTP 403)
Step 4: Turn on your trail
S3 does not record who downloaded which file by default. Next are three pastes. They create a second bucket for the logs and a CloudTrail trail that records file activity in your lab bucket only.
4a. Name things. The trail and log bucket are named after your bucket:
TRAIL="$BUCKET-trail"
TRAIL_BUCKET="$BUCKET-logs"
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
echo "Bucket: $BUCKET Trail: $TRAIL Logs: $TRAIL_BUCKET Account: $ACCOUNT"Check that it prints your bucket name and a 12-digit account number. If anything is blank, set BUCKET= again (Step 3) and repeat 4a.
4b. Create the log bucket. This block stops at the first error. If the trail or log bucket name is already in use, or a check fails, stop. A failed lookup can also mean an access or connection problem. You should see a ✅. If you don't, stop and read the error above it.
( set -e
if aws cloudtrail get-trail --name "$TRAIL" >/dev/null 2>&1; then
echo "❌ A trail named $TRAIL already exists. Pick a new bucket name."; exit 1; fi
if aws s3api head-bucket --bucket "$TRAIL_BUCKET" 2>/dev/null; then
echo "❌ Bucket $TRAIL_BUCKET already exists. Pick a new bucket name."; exit 1; fi
aws s3api create-bucket --bucket "$TRAIL_BUCKET" >/dev/null
cat > trail-bucket-policy.json <<EOF
{ "Version": "2012-10-17",
"Statement": [
{ "Effect": "Allow",
"Principal": { "Service": "cloudtrail.amazonaws.com" },
"Action": "s3:GetBucketAcl",
"Resource": "arn:aws:s3:::$TRAIL_BUCKET",
"Condition": { "StringEquals": {
"aws:SourceArn": "arn:aws:cloudtrail:us-east-1:$ACCOUNT:trail/$TRAIL" } } },
{ "Effect": "Allow",
"Principal": { "Service": "cloudtrail.amazonaws.com" },
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::$TRAIL_BUCKET/AWSLogs/$ACCOUNT/*",
"Condition": { "StringEquals": {
"s3:x-amz-acl": "bucket-owner-full-control",
"aws:SourceArn": "arn:aws:cloudtrail:us-east-1:$ACCOUNT:trail/$TRAIL" } } } ] }
EOF
aws s3api put-bucket-policy --bucket "$TRAIL_BUCKET" --policy file://trail-bucket-policy.json
echo "✅ Log bucket $TRAIL_BUCKET is ready." )4c. Create the trail and switch it on. A block of JSON will scroll by. Check that IsLogging prints true before you continue. The ✅ can appear even if the status is false:
( set -e
aws cloudtrail create-trail --name "$TRAIL" --s3-bucket-name "$TRAIL_BUCKET"
cat > selectors.json <<EOF
[{ "Name": "Lab bucket file activity",
"FieldSelectors": [
{ "Field": "eventCategory", "Equals": ["Data"] },
{ "Field": "resources.type", "Equals": ["AWS::S3::Object"] },
{ "Field": "resources.ARN", "StartsWith": ["arn:aws:s3:::$BUCKET/"] } ] }]
EOF
aws cloudtrail put-event-selectors --trail-name "$TRAIL" \
--advanced-event-selectors file://selectors.json >/dev/null
aws cloudtrail start-logging --name "$TRAIL"
aws cloudtrail get-trail-status --name "$TRAIL" --query IsLogging
echo "✅ Trail $TRAIL is on." )
The trail exists, IsLogging is true, and you get the check mark
You can also check it in the CloudTrail trails page: https://us-east-1.console.aws.amazon.com/cloudtrail/home?region=us-east-1#/trails. Click your trail. It should say Logging, and its data event selector should show your bucket.

The trail in the console is Logging, and its data events only cover your bucket
Step 5: Test the audit log
A new trail takes a few minutes to show records, and in our tests, downloads in the first minute were not recorded. Wait a minute after the ✅, then do one normal download and wait for it in the log.
Paste this once. It defines spot, which pulls the audit files and prints one line per download. jq is already in CloudShell and picks fields out of JSON. This paste prints nothing.
SPOT='.Records[] | select(.eventName == "GetObject")
| [ .eventTime,
.additionalEventData.AuthenticationMethod,
(if .requestParameters["X-Amz-Date"]
then ((.eventTime | fromdate)
- (.requestParameters["X-Amz-Date"]
| strptime("%Y%m%dT%H%M%SZ") | mktime)
| tostring) + "s old"
else "-" end),
(.errorCode // "OK"),
.sourceIPAddress ]
| @tsv'
spot() {
rm -rf ct; aws s3 cp "s3://$TRAIL_BUCKET/AWSLogs/" ct/ --recursive --quiet
rows=$(find ct -name '*.json.gz' -exec zcat {} + 2>/dev/null | jq -r "$SPOT" | sort)
if [ -n "$rows" ]; then echo "$rows"
else echo "No downloads in the log yet. Wait 2 or 3 minutes and run spot again."; fi
}Download the file the usual way, then check the log:
aws s3 cp "s3://$BUCKET/customer-report.txt" - ; spotAt first you'll see No downloads in the log yet. Wait 2 or 3 minutes and run spot again, until a line with AuthHeader appears, usually 5 to 10 minutes. If 10 minutes go by with nothing, paste the download line again. Our first download, made seconds after the trail switched on, never showed up. The second one did.

The audit log works once your test download shows up
🧭 Lost your place? If CloudShell sits idle it restarts and forgets what you set. Your bucket, trail and files in AWS are fine. Paste this with your bucket name:
BUCKET=lab-reports-yourname-4821 # <-- your bucket name again
TRAIL="$BUCKET-trail"; TRAIL_BUCKET="$BUCKET-logs"
aws cloudtrail get-trail-status --name "$TRAIL" --query IsLoggingIt should print true. Then:
Paste the Step 5
SPOT=block again to getspotback.If you still have the share link, paste it into
URL='...'again. You can't rebuild a working link from the log, because the trail redacts the signature.If you lost the link, or you were about to do Step 12, make a new one in Step 6. For Step 12, set
URLto the new link, wait 2 and a half minutes, then run Step 12.
In the S3 console, open your bucket and tick the box next to
customer-report.txt.Click Actions → Share with a presigned URL.
Choose Hours, enter 1, and click Create presigned URL. The link is copied to your clipboard.

A 1-hour share link, which works for anyone who has it
The dialog says: "Anyone can access the object with this presigned URL until it expires, even if the bucket, and object are private."
Step 7: Use the link with no login at all
Open a private or incognito window that isn't signed in to AWS, and paste the link. The fake report appears, or the browser downloads the .txt file.
Do the same in CloudShell, the way a script would. Paste your link between the single quotes:
URL='paste-your-link-here'
curl -sS -w "HTTP %{http_code}\n" "$URL"
The link hands over the file to anyone, no login needed
You get HTTP 200 and you never logged in.
Step 8: Look inside the link
Print the three fields:
echo "$URL" | tr '&?' '\n\n' | grep -E 'X-Amz-(Date|Expires|Credential)'
The link says who signed it, when, and for how long (key ID masked)
X-Amz-Credentialstarts with the access key ID of whoever made the link.ASIA…means temporary credentials, like your console session, which is what you'll see here.AKIA…means a long-term key.X-Amz-Dateis when the link was signed.X-Amz-Expires=3600is the requested lifetime: one hour, for anyone, any number of times. If it was signed with temporary credentials, it also dies when those credentials expire. In our test, a link that asked for 2 hours but was signed with 15-minute credentials died at minute 15 withExpiredToken.
Step 9: Replay it later, like an attacker who found it
Wait 3 minutes, then run the same request again:
date -u; curl -sS -w "HTTP %{http_code}\n" "$URL"
Three minutes later, the same link still works
You get HTTP 200 again, three minutes later.
🔍 Part 3: Spot the replay in the audit log (5 minutes, plus waiting)
Step 10: Find the downloads in the audit log
CloudTrail usually writes records 5 to 10 minutes after something happens. Run spot (if CloudShell restarted, see 🧭 Lost your place?):
spot
The test download, the share link, and its replay 3+ minutes later
The columns are time, how the request was signed, link age, result, and source IP.
What to expect, in time order:
Step 5's test download:
AuthHeader, no link age (-). That's theaws s3 cpdownload, signed in a header.Step 7, the incognito browser:
QueryString(a share link), usually from your browser's public IP.Step 7, CloudShell: another
QueryStringrow, a few seconds to a minute old.Step 9, the replay:
QueryString, about180s oldor more.
CloudTrail can deliver batches late or out of order. spot sorts the rows by timestamp each time you run it. If a row is missing, wait a few minutes and run spot again.
Normally a link is used a few seconds after it was signed. If it's used minutes or hours later from an IP you don't recognize, check it. Compare each source IP with your browser and CloudShell. In our run, CloudShell showed a private 10.x address. Yours may differ.
A customer opening an email the next morning looks the same in the log as a replay. If a link is old or the IP is odd, ask the person who shared it.
🗂️ File downloads are data events, written as .json.gz files under AWSLogs/ in the log bucket. They do not show up in CloudTrail Event history, which only lists management events like creating buckets. spot downloads those files and reads them.
🔵 Part 4: BLUE, make old links stop working (5 minutes)
Step 11: Add the bucket rule
A share link carries its signature in the address. S3 can check how old that signature is (s3:signatureAge, in milliseconds). This rule refuses a download if the signature is more than 2 minutes old.
S3 console → your bucket → Permissions tab → scroll to Bucket policy → click Edit.
Paste the policy below, and change
YOUR-BUCKET-NAMEto your bucket name:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DenyOldPresignedLinks",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/*",
"Condition": {
"NumericGreaterThan": { "s3:signatureAge": "120000" }
}
}
]
}Click Save changes.

The key line, which refuses any link older than 120,000 ms (2 minutes)

Saved, so the defense is live
💡 In plain English: "Deny anyone (Principal: *) downloading a file (s3:GetObject) from this bucket through a share link that was signed more than 2 minutes ago."
This rule covers share links made with Signature Version 4, the modern kind. The signature sits in the address and gets older every minute. aws s3 cp and apps that sign each request in a header keep working. Apps that fetch files through presigned URLs get the same 2 minute limit, so they need a longer window or a different path if users click later. The console Open and Download buttons still work; see Step 13.
Links signed the old way (Signature Version 2) report an age of 0, so this rule misses them. AWS has mostly retired SigV2. To be strict, add a second deny when s3:signatureversion equals AWS. If your app emails download links that people click hours later, 2 minutes will break that. Try it on a test bucket before you use it on a real one.
✅ Part 5: Prove the defense works (5 minutes)
Step 12: The old link is now dead
curl -sS -w "\nHTTP %{http_code}\n" "$URL"
The old link is refused (AccessDenied, HTTP 403)
Expect AccessDenied and HTTP 403. In our run the deny showed up immediately for a link signed more than 2 minutes earlier.
If the error includes the signing IAM identity's ARN and account ID, mask those before you share a screenshot, like we did.
Step 13: Fresh links and normal downloads still work
Make a new link in the console (Actions → Share with a presigned URL, like Step 6) and use it within 2 minutes:
NEW_URL='paste-the-new-link-here'
curl -sS -w "HTTP %{http_code}\n" "$NEW_URL"
aws s3 cp "s3://$BUCKET/customer-report.txt" -
A fresh link works, and a normal download works
The console Open button still works. It makes a new share link on each click and requests a 5-minute lifetime, so the signature is only seconds old when the tab opens. The tab address starts with your bucket name, and the X-Amz- parameters come after the ?. After 2 minutes, S3 denies a new request to that URL. The browser may still show a copy it already loaded. Click Open again for a fresh link.

Open makes a fresh share link (signature hidden here), so it still works with the policy on
Step 14: A fresh link stops working after 2 minutes too
Wait 2½ minutes, then try the new link again:
curl -sS -o /dev/null -w "HTTP %{http_code}\n" "$NEW_URL"
Once it's over 2 minutes old, the fresh link is refused too
Step 15: See the blocked attempts in the audit log
Wait 5 to 10 minutes, then run spot again, and once more a few minutes later if a row is missing, because rows trickle in.
spot
The replays now show AccessDenied, right next to the link's age
Blocked attempts show up as new AccessDenied rows, with the signature age beside them. Earlier successful downloads still show OK, including your aws s3 cp (AuthHeader) and the fresh link you used within 2 minutes (a young QueryString).
🧹 Part 6: Clean up (5 minutes, please don't skip)
Step 16: Delete everything
Paste this in CloudShell first, and check the three names match what you created. If CloudShell restarted, paste the first two lines of 🧭 Lost your place? first, so BUCKET, TRAIL and TRAIL_BUCKET are set.
printf 'Lab bucket: %s\nLog bucket: %s\nTrail: %s\n' "$BUCKET" "$TRAIL_BUCKET" "$TRAIL"Check you're in the same sandbox account. If the names are right, paste the deletion block. Deleting the buckets also removes their policies.
aws cloudtrail stop-logging --name "$TRAIL"
aws cloudtrail delete-trail --name "$TRAIL"
aws s3 rm "s3://$BUCKET" --recursive
aws s3api delete-bucket --bucket "$BUCKET"
aws s3 rm "s3://$TRAIL_BUCKET" --recursive --quiet
aws s3api delete-bucket --bucket "$TRAIL_BUCKET"
rm -rf ct customer-report.txt trail-bucket-policy.json selectors.jsonStep 17: Check that nothing's left
This checks the exact names you set. You want three ✅ lines. A ✅ can also appear if credentials expired or you lack permission, so confirm in the console too.
for B in "$BUCKET" "$TRAIL_BUCKET"; do
aws s3api head-bucket --bucket "$B" 2>/dev/null \
&& echo "❌ still there: bucket $B" || echo "✅ gone: bucket $B"
done
aws cloudtrail get-trail --name "$TRAIL" >/dev/null 2>&1 \
&& echo "❌ still there: trail $TRAIL" || echo "✅ gone: trail $TRAIL"
Three check marks, so nothing is left behind
If you see a ❌, run Step 16 again and look for the error. Also refresh the S3 bucket list and the CloudTrail trails list in us-east-1, and confirm the exact names are gone. If a list fails to load, retry the check.

The S3 bucket list no longer shows the lab buckets
What to take away
A share link works for anyone who has it, as many times as they like, until it expires, even when the bucket is private.
For the lab's SigV4 download links, the bucket policy denies new
GetObjectrequests once the signature is more than 2 minutes old, even if the link requested an hour.Turn on CloudTrail data events to see share-link downloads (
QueryStringwithX-Amz-Expires), when the link was signed, and the source IP. If a link is old and the IP is unfamiliar, ask the person who shared it.Inside those 2 minutes, a leaked link still works. CloudFront signed URLs can also be reused until they expire, if the request meets the signed policy, for example an IP restriction. For a one-time download, your app has to issue a token and mark it used on the server the first time someone presents it.
If people need to open emailed download links or scheduled reports more than 2 minutes after signing, use a longer limit or a separate bucket. Try the policy on a test bucket first.
Try this next: Set the limit to 15 minutes and send a link to a coworker. Then search your audit log for every QueryString download that was more than 10 minutes old.
Recon Labs #1, from Weekly Recon by Raajhesh Kannaa Chidambaram · join.defensive.works · tested in a real AWS sandbox on November 17, 2026.
Optional: set up and clean up from your own terminal
The walkthrough above uses the console and CloudShell. The two optional scripts below do the same setup and teardown from your own terminal, and they match the scripts in the free lab download, with the PDF and a README. Set AWS_PROFILE to your sandbox profile, and for an account check set EXPECTED_ACCOUNT to your 12-digit sandbox account ID. Please don't use production.
setup.sh
#!/usr/bin/env bash
# Optional helper: recreates this lab from your own terminal.
# ./setup.sh bucket + fake report + CloudTrail data-event trail (state before the attack)
# ./setup.sh --defense same, plus the signature-age bucket policy (state after the fix)
# State (bucket names) is saved to .lab-state next to this script; cleanup.sh reads it.
set -euo pipefail
PROFILE="${AWS_PROFILE:-default}" # set this to your sandbox profile
EXPECTED_ACCOUNT="${EXPECTED_ACCOUNT:-}" # optional: your 12-digit account ID, as a safety check
REGION=us-east-1
HERE="$(cd "$(dirname "$0")" && pwd)"
STATE="$HERE/.lab-state"
export AWS_PROFILE=$PROFILE AWS_DEFAULT_REGION=$REGION AWS_PAGER=""
ACCOUNT="$(aws sts get-caller-identity --query Account --output text)"
if [ -n "$EXPECTED_ACCOUNT" ] && [ "$ACCOUNT" != "$EXPECTED_ACCOUNT" ]; then
echo "STOP: profile $PROFILE is account $ACCOUNT, expected $EXPECTED_ACCOUNT"; exit 1
fi
echo "Account check OK: $ACCOUNT"
if [ -f "$STATE" ]; then echo "STOP: $STATE exists. Run ./cleanup.sh first."; exit 1; fi
SUFFIX="$(python3 -c 'import uuid; print(uuid.uuid4().hex[:10])')"
BUCKET="lab-reports-$SUFFIX"
TRAIL="$BUCKET-trail"
TRAIL_BUCKET="$BUCKET-logs"
if aws cloudtrail get-trail --name "$TRAIL" >/dev/null 2>&1; then echo "STOP: trail $TRAIL already exists"; exit 1; fi
if aws s3api head-bucket --bucket "$TRAIL_BUCKET" 2>/dev/null; then echo "STOP: bucket $TRAIL_BUCKET already exists"; exit 1; fi
TAGS='TagSet=[{Key=purpose,Value=security-drills},{Key=drill,Value=s3-presigned-link}]'
printf 'BUCKET=%s\nTRAIL_BUCKET=%s\nTRAIL=%s\n' "$BUCKET" "$TRAIL_BUCKET" "$TRAIL" > "$STATE"
aws s3api create-bucket --bucket "$BUCKET" >/dev/null
aws s3api put-public-access-block --bucket "$BUCKET" --public-access-block-configuration \
BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
aws s3api put-bucket-tagging --bucket "$BUCKET" --tagging "$TAGS"
printf 'FAKE customer report for a security lab. No real data.\nAccount: ACME-0001 Balance: $1,234.56\n' > /tmp/customer-report.txt
aws s3 cp /tmp/customer-report.txt "s3://$BUCKET/customer-report.txt" --quiet
rm -f /tmp/customer-report.txt
echo "Created bucket $BUCKET with customer-report.txt"
aws s3api create-bucket --bucket "$TRAIL_BUCKET" >/dev/null
aws s3api put-public-access-block --bucket "$TRAIL_BUCKET" --public-access-block-configuration \
BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
aws s3api put-bucket-tagging --bucket "$TRAIL_BUCKET" --tagging "$TAGS"
TRAIL_ARN="arn:aws:cloudtrail:$REGION:$ACCOUNT:trail/$TRAIL"
aws s3api put-bucket-policy --bucket "$TRAIL_BUCKET" --policy "{
\"Version\":\"2012-10-17\",\"Statement\":[
{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"cloudtrail.amazonaws.com\"},\"Action\":\"s3:GetBucketAcl\",
\"Resource\":\"arn:aws:s3:::$TRAIL_BUCKET\",\"Condition\":{\"StringEquals\":{\"aws:SourceArn\":\"$TRAIL_ARN\"}}},
{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"cloudtrail.amazonaws.com\"},\"Action\":\"s3:PutObject\",
\"Resource\":\"arn:aws:s3:::$TRAIL_BUCKET/AWSLogs/$ACCOUNT/*\",
\"Condition\":{\"StringEquals\":{\"s3:x-amz-acl\":\"bucket-owner-full-control\",\"aws:SourceArn\":\"$TRAIL_ARN\"}}}]}"
aws cloudtrail create-trail --name "$TRAIL" --s3-bucket-name "$TRAIL_BUCKET" \
--tags-list Key=purpose,Value=security-drills Key=drill,Value=s3-presigned-link >/dev/null
aws cloudtrail put-event-selectors --trail-name "$TRAIL" --advanced-event-selectors "[{
\"Name\":\"Reads and writes of lab bucket objects\",
\"FieldSelectors\":[
{\"Field\":\"eventCategory\",\"Equals\":[\"Data\"]},
{\"Field\":\"resources.type\",\"Equals\":[\"AWS::S3::Object\"]},
{\"Field\":\"resources.ARN\",\"StartsWith\":[\"arn:aws:s3:::$BUCKET/\"]}]}]" >/dev/null
aws cloudtrail start-logging --name "$TRAIL"
[ "$(aws cloudtrail get-trail-status --name "$TRAIL" --query IsLogging --output text)" = "True" ] \
|| { echo "STOP: trail $TRAIL is not logging"; exit 1; }
echo "Created trail $TRAIL -> s3://$TRAIL_BUCKET (data events for $BUCKET only)"
if [ "${1:-}" = "--defense" ]; then
aws s3api put-bucket-policy --bucket "$BUCKET" --policy "{
\"Version\":\"2012-10-17\",\"Statement\":[{
\"Sid\":\"DenyOldPresignedLinks\",\"Effect\":\"Deny\",\"Principal\":\"*\",
\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::$BUCKET/*\",
\"Condition\":{\"NumericGreaterThan\":{\"s3:signatureAge\":\"120000\"}}}]}"
echo "Applied DenyOldPresignedLinks (links older than 2 minutes are refused)"
fi
echo
echo "Done. Lab bucket: $BUCKET"
echo "Console: https://us-east-1.console.aws.amazon.com/s3/buckets/$BUCKET?region=us-east-1"cleanup.sh
#!/usr/bin/env bash
# Optional helper: removes exactly what setup.sh recorded in .lab-state, then checks those exact names are gone.
set -uo pipefail
PROFILE="${AWS_PROFILE:-default}" # set this to your sandbox profile
EXPECTED_ACCOUNT="${EXPECTED_ACCOUNT:-}" # optional: your 12-digit account ID, as a safety check
export AWS_PROFILE=$PROFILE AWS_DEFAULT_REGION=us-east-1 AWS_PAGER=""
HERE="$(cd "$(dirname "$0")" && pwd)"
STATE="$HERE/.lab-state"
ACCOUNT="$(aws sts get-caller-identity --query Account --output text)"
if [ -n "$EXPECTED_ACCOUNT" ] && [ "$ACCOUNT" != "$EXPECTED_ACCOUNT" ]; then
echo "STOP: profile $PROFILE is account $ACCOUNT, expected $EXPECTED_ACCOUNT"; exit 1
fi
echo "Account check OK: $ACCOUNT"
[ -f "$STATE" ] || { echo "No $STATE found; nothing recorded to clean."; exit 0; }
source "$STATE"
echo "Deleting: $BUCKET $TRAIL_BUCKET $TRAIL"
if aws cloudtrail get-trail --name "$TRAIL" >/dev/null 2>&1; then
aws cloudtrail stop-logging --name "$TRAIL"
aws cloudtrail delete-trail --name "$TRAIL" && echo "Deleted trail $TRAIL"
fi
for B in "$BUCKET" "$TRAIL_BUCKET"; do
if aws s3api head-bucket --bucket "$B" >/dev/null 2>&1; then
aws s3 rm "s3://$B" --recursive --quiet
aws s3api delete-bucket --bucket "$B" && echo "Deleted bucket $B"
fi
done
echo "--- Verify by exact name ---"
LEFT=0
for B in "$BUCKET" "$TRAIL_BUCKET"; do
if aws s3api head-bucket --bucket "$B" 2>/dev/null; then echo "still there: bucket $B"; LEFT=1; else echo "gone: bucket $B"; fi
done
if aws cloudtrail get-trail --name "$TRAIL" >/dev/null 2>&1; then echo "still there: trail $TRAIL"; LEFT=1; else echo "gone: trail $TRAIL"; fi
[ "$LEFT" = 0 ] && rm -f "$STATE" && echo "Clean." || echo "Something is left; .lab-state kept so you can re-run."If you skipped the walkthrough, download the free lab bundle. It has the step-by-step PDF with screenshots, both optional scripts, and a README.

