Automatically Remediate Security Threats in Your AWS Account, in Seconds

Automatically Remediate Security Threats in Your AWS Account, in Seconds

An AWS access key leaked and I never found out how. This is the system I built afterwards: it deactivates leaked keys, isolates compromised EC2 instances, makes public S3 buckets private, and restarts stopped CloudTrail logs automatically, with Terraform and a public repo.

2× AWS Certified | Helping Businesses Scale and Secure AWS Infrastructure | DevOps Automation

Why I built this

A while ago, an AWS access key in an account I was responsible for leaked. To this day I don't know exactly where it leaked from. What I do know is how it felt: every minute between the leak and someone noticing was a minute an attacker could use that key.
My first fix was to remove the problem at the source. I moved our CI/CD pipelines to GitHub OIDC, so they get short-lived credentials and no longer store access keys at all. But OIDC only closed one door. Long-lived keys still exist in most accounts: on developer laptops, in older applications, in third-party tools. The next leak is a question of when, not if.
So I asked myself a second question: when something bad happens, does a human really need to be awake before anything is done? For some incidents, no. A leaked key can be switched off safely. A bucket that was made public can be made private again. Those fixes are small, reversible, and urgent, which makes them perfect for automation.
This guide builds that automation. Amazon GuardDuty detects the problem, and a small Lambda function fixes it within seconds, then tells your team what it did.

What gets fixed automatically

Incident
Automatic response
Why it is safe to automate
A leaked IAM user access key is used from a malicious IP or in an unusual way
The key is deactivated
One click to reactivate; the owner can create a new key
An EC2 instance mines crypto, talks to a command-and-control server, or uses Tor
The instance is isolated with an empty security group and tagged
The instance keeps running for investigation; nothing is deleted
An S3 bucket is made public
Block Public Access is turned back on
Public access is rarely intended; exempt real public buckets with a tag
Account-level S3 Block Public Access is turned off
It is turned back on
Same as above, for the whole account
CloudTrail logging is stopped, a classic attacker cover-up
Logging is restarted
Restarting logs never breaks anything
Some incidents are deliberately not fixed automatically, and get an email alert instead: an instance that is the victim of an attack rather than the attacker, temporary role credentials, and anything you tag  AutoRemediation=skip . The design section explains why.
The tools are interchangeable; the pattern is the point. GuardDuty is the detector and Terraform deploys everything, but the same detect, decide, fix, notify loop works with Security Hub or AWS Config as the source.
All the code, including 14 unit tests and a CI pipeline, is in a public repository:  github.com/muzammilcloud/guardduty-auto-remediation .

Architecture


Architecture diagram: GuardDuty detects a problem and sends the finding to EventBridge, which forwar


GuardDuty detects the problem. EventBridge forwards every High or Critical finding, plus the lower-severity findings that have a safe fix, such as a public bucket. Lambda decides whether to act or only alert, and every outcome, including a skipped one, is emailed through SNS.

Design decisions: when to act and when to only alert

The rule I settled on: act automatically only when the fix is reversible, low-risk, and the resource is clearly compromised or misconfigured. Everything else goes to a human.
Situation
Response
Reasoning
EC2 instance targeted by inbound brute force
Alert only
The instance is the victim; isolating it would cause your own outage
Temporary (assumed-role) credentials
Alert only
They cannot be deactivated; revoking role sessions needs human judgment
The person who stopped CloudTrail
Alert only
Logging is restarted, but stopping a trail can be legitimate admin work, so their key is left alone
A bucket that is meant to be public, such as a static website
Skipped with a tag
 AutoRemediation=skip  keeps intentional public buckets public
GuardDuty sample findings
Dry run
Testing never changes real resources
The same principle shaped each fix: deactivate keys instead of deleting them, isolate instances instead of stopping or terminating them, and re-enable protections instead of changing policies. A false positive should cost minutes to undo, not data.

Prerequisites, cost, and the repository

You need Terraform 1.5 or later, the AWS CLI v2, an email address for alerts, and about 30 minutes.
Cost: GuardDuty offers a 30-day free trial per account and Region, then charges based on the volume of logs it analyzes. If GuardDuty is already enabled, this project adds almost nothing: Lambda, EventBridge, and SNS usage for a handful of findings stays in the Free Tier. Check the  GuardDuty pricing page  before enabling it in a busy account.
Clone the repository:
git clone https://github.com/muzammilcloud/guardduty-auto-remediation.git
cd guardduty-auto-remediation
├── versions.tf # providers
├── variables.tf # inputs with validation
├── guardduty.tf # detector (new or existing)
├── events.tf # EventBridge rule + Lambda permission
├── lambda.tf # function + log group
├── iam.tf # least-privilege role
├── sns.tf # email alerts
├── test.tf # permissionless test user
├── outputs.tf
├── lambda/remediate.py
├── tests/test_remediate.py
└── .github/workflows/ci.yml
The article walks through the important parts; the repository has every file.

Step 1: Detection with GuardDuty and EventBridge

GuardDuty publishes every new finding to EventBridge; the rule below forwards only the findings this project can act on or should alert about.
 guardduty.tf  handles a common real-world snag: GuardDuty allows only one detector per Region, so creating a second one fails. The  create_detector  variable lets you reuse an existing detector instead.
resource "aws_guardduty_detector" "this" {
count = var.create_detector ? 1 : 0
enable = true
}

data "aws_guardduty_detector" "existing" {
count = var.create_detector ? 0 : 1
}

locals {
detector_id = var.create_detector ? aws_guardduty_detector.this[0].id : data.aws_guardduty_detector.existing[0].id
}
 events.tf :
locals {
# Low-severity findings that still have a safe, automatic fix.
remediable_types = [
"Policy:S3/BucketBlockPublicAccessDisabled",
"Policy:S3/BucketAnonymousAccessGranted",
"Policy:S3/BucketPublicAccessGranted",
"Policy:S3/AccountBlockPublicAccessDisabled",
"Stealth:IAMUser/CloudTrailLoggingDisabled",
]
}

resource "aws_cloudwatch_event_rule" "findings" {
name = "${var.name_prefix}-findings"
description = "High-severity GuardDuty findings, plus findings with a safe automatic fix"

event_pattern = jsonencode({
source = ["aws.guardduty"]
"detail-type" = ["GuardDuty Finding"]
"$or" = [
{ detail = { severity = [{ numeric = [">=", var.min_severity] }] } },
{ detail = { type = local.remediable_types } },
]
})
}

resource "aws_cloudwatch_event_target" "remediation" {
rule = aws_cloudwatch_event_rule.findings.name
arn = aws_lambda_function.remediation.arn
}

resource "aws_lambda_permission" "allow_eventbridge" {
statement_id = "AllowEventBridgeInvoke"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.remediation.function_name
principal = "events.amazonaws.com"
source_arn = aws_cloudwatch_event_rule.findings.arn
}
This rule taught me something while building it. My first version filtered only on severity 7 and above, which silently ignored public buckets and stopped CloudTrail logs, because GuardDuty rates most of those findings Low. Severity measures how alarming a finding is, not how easy it is to fix. The  $or  pattern now sends two kinds of findings to Lambda: anything High or Critical, and specific lower-severity types that have a safe fix. Everything else is filtered out by EventBridge before it ever invokes Lambda.

Step 2: The remediation Lambda

The handler routes each finding to a fix, decides whether to act or only alert, and always sends a notification describing the outcome.
The entry point in  lambda/remediate.py :
def lambda_handler(event, context):
finding = event["detail"]
is_sample = bool(finding.get("service", {}).get("additionalInfo", {}).get("sample"))
dry_run = MODE != "enforce" or is_sample

resource = finding.get("resource", {})
resource_type = resource.get("resourceType")
finding_type = finding.get("type", "")

# Route by finding type first: these findings describe what was changed,
# not who changed it, so the fix targets the changed resource.
if finding_type == CLOUDTRAIL_STOPPED_TYPE:
action = handle_cloudtrail_stopped(dry_run)
elif finding_type == ACCOUNT_PUBLIC_TYPE:
action = handle_account_public(finding.get("accountId"), dry_run)
elif finding_type in PUBLIC_BUCKET_TYPES:
action = handle_public_bucket(resource, dry_run)
elif resource_type == "AccessKey":
action = handle_access_key(resource.get("accessKeyDetails", {}), dry_run)
elif resource_type == "Instance":
action = handle_instance(finding, dry_run)
else:
action = f"Alert only: no automatic action for resource type {resource_type}"

notify(finding, action, is_sample)
return {"action": action}
The order matters. A "CloudTrail stopped" finding points at the access key of whoever stopped it, so routing by resource type alone would deactivate that person's key. Checking the finding type first sends it to the right fix: restart the logs and alert a human about who did it.
Deactivating a leaked key:
def handle_access_key(details, dry_run):
user = details.get("userName")
key_id = details.get("accessKeyId")
user_type = details.get("userType")

if user_type != "IAMUser":
return f"Alert only: {user_type} credentials cannot be deactivated; revoke the role sessions manually"
if dry_run:
return f"DRY RUN: would deactivate access key {key_id} for user {user}"

tags = iam.list_user_tags(UserName=user)["Tags"]
if any((t["Key"], t["Value"]) == SKIP_TAG for t in tags):
return f"Skipped: user {user} is tagged AutoRemediation=skip"

iam.update_access_key(UserName=user, AccessKeyId=key_id, Status="Inactive")
return f"Deactivated access key {key_id} for user {user}"
Isolating an instance only when it is the attacker:
ISOLATE_PREFIXES = (
"Backdoor:EC2/",
"CryptoCurrency:EC2/",
"Trojan:EC2/",
"Impact:EC2/",
"UnauthorizedAccess:EC2/TorClient",
)

def handle_instance(finding, dry_run):
instance_id = finding["resource"]["instanceDetails"]["instanceId"]
finding_type = finding.get("type", "")
direction = (
finding.get("service", {}).get("action", {})
.get("networkConnectionAction", {}).get("connectionDirection")
)

if direction == "INBOUND":
return f"Alert only: {instance_id} is the target of inbound activity, not the attacker"
if not finding_type.startswith(ISOLATE_PREFIXES):
return f"Alert only: {finding_type} is not in the isolation list"
if dry_run:
return f"DRY RUN: would isolate instance {instance_id}"

instance = ec2.describe_instances(InstanceIds=[instance_id])["Reservations"][0]["Instances"][0]
tags = {t["Key"]: t["Value"] for t in instance.get("Tags", [])}
if tags.get("AutoRemediation") == "skip":
return f"Skipped: instance {instance_id} is tagged AutoRemediation=skip"

sg_id = get_or_create_quarantine_sg(instance["VpcId"])
ec2.modify_instance_attribute(InstanceId=instance_id, Groups=[sg_id])
ec2.create_tags(Resources=[instance_id], Tags=[
{"Key": "SecurityStatus", "Value": "Quarantined"},
{"Key": "QuarantineFinding", "Value": finding.get("id", "unknown")[:255]},
])
return f"Isolated instance {instance_id} with security group {sg_id}"
 get_or_create_quarantine_sg  finds or creates a security group named  guardduty-quarantine  in the instance's VPC. A new security group allows all outbound traffic by default, so the function revokes those egress rules right after creating it. That detail is easy to miss: without it, the "isolated" instance could still send data out.
Making a public bucket private again, unless it is tagged as intentionally public:
def handle_public_bucket(resource, dry_run):
buckets = resource.get("s3BucketDetails") or []
if not buckets:
return "Alert only: finding has no bucket details"
bucket = buckets[0]["name"]
if dry_run:
return f"DRY RUN: would turn on Block Public Access for bucket {bucket}"

try:
tags = s3.get_bucket_tagging(Bucket=bucket)["TagSet"]
except ClientError as err:
if err.response["Error"]["Code"] != "NoSuchTagSet":
raise
tags = []
if any((t["Key"], t["Value"]) == SKIP_TAG for t in tags):
return f"Skipped: bucket {bucket} is tagged AutoRemediation=skip"

s3.put_public_access_block(Bucket=bucket, PublicAccessBlockConfiguration=BLOCK_ALL)
return f"Turned on Block Public Access for bucket {bucket}"
Restarting CloudTrail after an attacker stops it:
def handle_cloudtrail_stopped(dry_run):
restarted = []
for trail in cloudtrail.describe_trails(includeShadowTrails=False)["trailList"]:
arn = trail["TrailARN"]
if not cloudtrail.get_trail_status(Name=arn)["IsLogging"]:
if not dry_run:
cloudtrail.start_logging(Name=arn)
restarted.append(trail["Name"])
if not restarted:
return "Alert only: all trails in this Region are already logging"
verb = "DRY RUN: would restart" if dry_run else "Restarted"
return f"{verb} logging for trail(s): {', '.join(restarted)}. Review who stopped it."
Instead of parsing the trail name out of the finding, the function checks every trail in the Region and restarts any that is not logging. That is simpler and also catches a second trail stopped in the same attack. The repository also handles the account-level Block Public Access finding with  s3control.put_public_access_block .
The function lets unexpected AWS errors raise instead of catching them. EventBridge invokes Lambda asynchronously, so a failure is retried and stays visible in CloudWatch metrics, instead of being swallowed by a  try/except .

Step 3: Least-privilege IAM

A remediation function is itself a high-value target, so its role can do only what the code needs: deactivate keys, isolate instances, re-enable S3 and CloudTrail protections, and publish alerts.
 iam.tf  (policy document):
data "aws_iam_policy_document" "remediation" {
statement {
sid = "DisableIamUserKeys"
actions = ["iam:UpdateAccessKey", "iam:ListUserTags"]
resources = ["arn:aws:iam::${data.aws_caller_identity.current.account_id}:user/*"]
}

statement {
sid = "InspectEc2"
actions = ["ec2:DescribeInstances", "ec2:DescribeSecurityGroups"]
resources = ["*"]
}

statement {
sid = "IsolateEc2"
actions = [
"ec2:CreateSecurityGroup",
"ec2:RevokeSecurityGroupEgress",
"ec2:ModifyInstanceAttribute",
"ec2:CreateTags",
]
resources = ["*"]
}

statement {
sid = "BlockPublicS3"
actions = [
"s3:PutBucketPublicAccessBlock",
"s3:GetBucketTagging",
"s3:PutAccountPublicAccessBlock",
]
resources = ["*"]
}

statement {
sid = "RestartCloudTrail"
actions = ["cloudtrail:DescribeTrails", "cloudtrail:GetTrailStatus", "cloudtrail:StartLogging"]
resources = ["*"]
}

statement {
sid = "Notify"
actions = ["sns:Publish"]
resources = [aws_sns_topic.alerts.arn]
}
}
Notice what is missing: no  iam:DeleteAccessKey , no  ec2:TerminateInstances , no  s3:DeleteBucket , no  cloudtrail:StopLogging . Every permission either reads something or turns a protection back on. Even if someone abused this function, the worst it could do is disable keys, isolate instances, or make buckets private, all of which are reversible. EC2  Describe  actions do not support resource-level permissions, which is why they use  * ; in a production account you can narrow the write statements further with conditions such as  aws:ResourceTag .

Step 4: Safety controls

Automation that can lock people out needs brakes. Three controls make this safe to roll out.
1. An alert-only mode. The  mode  variable is validated in Terraform and passed to Lambda as an environment variable:
variable "mode" {
type = string
default = "enforce"
description = "enforce = take action, alert-only = notify without changing anything"

validation {
condition = contains(["enforce", "alert-only"], var.mode)
error_message = "mode must be \"enforce\" or \"alert-only\"."
}
}
For a new account, start with  alert-only . For a week, every email says what the function would have done. If none of those actions would have hurt you, switch to  enforce .
2. Sample findings are always dry runs. GuardDuty marks generated samples with  "sample": true  in  service.additionalInfo . The handler forces a dry run for them, so testing can never disable a real key.
3. An exemption tag. Tag an IAM user, instance, or S3 bucket with  AutoRemediation=skip  to keep it under human control. Use it for break-glass accounts, for servers where isolation would be worse than the threat, and for buckets that really are public, such as a static website. Review the list regularly.

Step 5: Deploy

Copy the example variables, set your email, and apply.
cp terraform.tfvars.example terraform.tfvars
alert_email = "you@example.com"
mode = "enforce"
create_detector = true # false if GuardDuty is already enabled here
terraform init
terraform plan -out tfplan
terraform apply tfplan
AWS sends a subscription email to  alert_email . Click Confirm subscription, or no alerts will arrive.
The stack also creates a test IAM user with one access key and no permissions. It exists only so you can prove the remediation works on a real key in the next step.

Step 6: Verify, safely

You can prove every part of the pipeline without a real attack, in three levels.
Level 1: the full event path with a sample finding. This tests GuardDuty → EventBridge → Lambda → SNS, as a dry run:
aws guardduty create-sample-findings \
--detector-id $(terraform output -raw detector_id) \
--finding-types UnauthorizedAccess:IAMUser/MaliciousIPCaller

aws logs tail /aws/lambda/gd-autoremediate --follow
Within a minute or two you should see a log line with  "action": "DRY RUN: would deactivate access key ..."  and receive an email whose subject starts with  [SAMPLE] .
Always pass  --finding-types . Without it, GuardDuty generates a sample of every finding type at once, which floods your inbox and anything else subscribed to GuardDuty events.
Level 2: real remediation on the test user. Terraform outputs a simulated finding that points at the test user's real key:
terraform output -raw test_event_json > event.json

aws lambda invoke \
--function-name $(terraform output -raw function_name) \
--payload fileb://event.json response.json
cat response.json

aws iam list-access-keys --user-name $(terraform output -raw test_user_name)
The response says  Deactivated access key ... , and  list-access-keys  now shows  "Status": "Inactive" . That is the exact code path a real leaked key would take.
Level 2b: a real public bucket. Create a throwaway bucket, remove its public access protection, and let the function fix it (the  create-bucket  command shown works in us-east-1; other Regions also need  --create-bucket-configuration ):
BUCKET=remediation-test-$RANDOM$RANDOM
aws s3api create-bucket --bucket $BUCKET
aws s3api delete-public-access-block --bucket $BUCKET

cat > s3-event.json <<EOF
{"detail": {"id": "manual-test-2", "type": "Policy:S3/BucketBlockPublicAccessDisabled",
"severity": 2, "service": {"additionalInfo": {}},
"resource": {"resourceType": "S3Bucket", "s3BucketDetails": [{"name": "$BUCKET"}]}}}
EOF

aws lambda invoke \
--function-name $(terraform output -raw function_name) \
--payload fileb://s3-event.json response.json

aws s3api get-public-access-block --bucket $BUCKET
aws s3 rb s3://$BUCKET
All four Block Public Access settings are  true  again. If you skip the manual invoke and simply wait, GuardDuty may raise the real finding on its own after a few minutes, and you can watch the whole loop run without any help.
Level 3: unit tests for every branch. The repository uses  moto  to mock AWS and covers 14 cases, including key deactivation, instance isolation with an empty egress list, public bucket blocking, the skip tag on users, instances, and buckets, account-level Block Public Access, restarting a stopped trail, inbound findings, assumed-role credentials, sample dry runs, and alert-only mode.
pip install -r requirements-dev.txt
pytest -q tests
# 14 passed
The included GitHub Actions workflow runs  terraform fmt ,  terraform validate , and these tests on every pull request.

Production considerations and honest limits

This pattern is a strong first responder, not a complete incident response plan. These are the limits to know before relying on it.
  • Security groups do not cut existing connections. Security group connection tracking can keep an already-established connection alive after you swap groups. For full containment, also apply a deny-all network ACL to the instance's subnet, or stop the instance after taking EBS snapshots.
  • Only the primary network interface is isolated.  modify_instance_attribute  changes the security groups of the primary interface. Instances with extra interfaces need each one updated.
  • A deactivated key is not a cleaned-up account. The attacker may have created new users, keys, or roles. Review CloudTrail for the key's activity before re-enabling anything.
  • Assumed-role credentials need a different playbook. For findings on temporary credentials, revoke active sessions on the role (an  aws:TokenIssueTime  deny policy) after a human confirms the finding.
  • One account, one Region. GuardDuty and EventBridge are Regional. For an organization, use a delegated GuardDuty administrator and deploy this stack per Region, or forward findings to a central account.
  • Watch the watcher. Add a CloudWatch alarm on the function's  Errors  metric, so a broken remediation is noticed before the next real incident.

Troubleshooting

Symptom
Likely cause
Fix
 terraform apply  fails creating the detector
GuardDuty is already enabled in this Region
Set  create_detector = false 
No email at all
SNS subscription not confirmed
Click the confirmation link, or re-run  terraform apply  to resend it
Sample finding does not invoke Lambda
Its severity is below  min_severity  and it is not in  remediable_types 
Use a High finding type, such as  UnauthorizedAccess:IAMUser/MaliciousIPCaller 
 AccessDenied  on  UpdateAccessKey  in the logs
Role policy not attached yet, or changed
Run  terraform apply  and check the  DisableIamUserKeys  statement
Level 2 test returns  DRY RUN 
 mode  is set to  alert-only 
Set  mode = "enforce"  and apply
Hundreds of emails after testing
 create-sample-findings  ran without  --finding-types 
Always pass a single finding type

Clean up

terraform destroy
This removes the function, rule, topic, role, and test user. If Terraform created the detector, it also disables GuardDuty in that Region, so set  create_detector = false  first if you want to keep it running. If any test instance was quarantined, delete the  guardduty-quarantine  security group manually.

Conclusion

When that key leaked, the hardest part was the waiting: knowing something was wrong, but not knowing how long it had been wrong. OIDC removed the keys I could remove. This project covers the ones that are left, and a few other incidents that should never wait for a human: public buckets, stopped audit logs, and instances working for someone else.
The rule behind it fits in one sentence: fix automatically when the fix is reversible and the resource is clearly compromised, and keep humans in charge of everything else. Deploy it in  alert-only  mode, read a week of emails, and then decide which incidents you trust enough to automate. Which one would you add next?
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article