Lesson 10 of 30Identity and security
AWS Security Services and Incident Response
Turn on the security baseline every account needs, read GuardDuty and Security Hub findings, and run the leaked access key playbook step by step.
It is 02:40 on a Sunday and an email from AWS says an access key belonging to your account was found in a public GitHub repository. Twenty minutes later your budget alarm fires: something is launching large instances in a Region nobody at the company uses. What you do in the next hour depends almost entirely on what you switched on months ago. With CloudTrail, GuardDuty and a central log archive in place, this is a stressful but bounded incident. Without them, you are guessing. This lesson covers the security services a cloud engineer is expected to know by name, what each one actually detects, and the incident runbook you will be glad you rehearsed.
The baseline: what every account turns on
Security teams talk about a baseline: the set of services enabled in every account and every Region before any workload lands. The exact list varies by company, but this core shows up almost everywhere.
| Service | What it watches | A real finding looks like | Question it answers |
|---|---|---|---|
| CloudTrail (organization trail) | Every API call, from every principal | DeleteTrail by assumed-role/dev/sam at 14:02 | Who did what, when, from where? |
| GuardDuty | CloudTrail, VPC flow, DNS and more, for threats | CryptoCurrency:EC2/BitcoinTool.B!DNS | Is something malicious happening now? |
| Security Hub CSPM | Configuration against best-practice controls | [S3.8] S3 general purpose buckets should block public access FAILED | What is configured badly? |
| AWS Config | Every resource's configuration over time | Security group sg-0a1 changed to allow 22 from 0.0.0.0/0 | What did this resource look like last Tuesday? |
| IAM Access Analyzer | Resource policies and unused permissions | Bucket exports is shared with account 999988887777 | Who outside my org can reach this? |
| Budgets and a billing alarm | Spend | Forecast 400% over budget | Is something costing money it should not? |
You met CloudTrail in Monitoring and Logs and Access Analyzer in IAM. What changes at company scale is where these run. In the layout from Multiple Accounts, Organizations and SSO, a dedicated security account is the delegated administrator for GuardDuty, Security Hub, Config and Access Analyzer. Findings from every member account flow there, CloudTrail logs land in a locked log archive account, and nobody in a workload account can switch any of it off, because an SCP denies guardduty:DeleteDetector, cloudtrail:StopLogging and friends.
Two traps catch teams early:
- GuardDuty, Config and Security Hub are Regional. Enabling them only in
eu-west-2leaves every other Region dark. Attackers with stolen keys go to Regions you do not use precisely because nobody looks there. Enable everywhere, or block unused Regions with an SCP onaws:RequestedRegion. - Detection only starts when you turn it on. Security Hub CSPM does not retroactively evaluate findings from before it was enabled, and GuardDuty has no history to analyze from before day one. The time to switch them on is before the incident.
Four kinds of signal
It helps to sort the services by the kind of question they answer, because interviewers love to ask "which service would you use for X" and the names blur together.
- Threat detection: something bad is happening. GuardDuty. It watches behavior and raises a finding when a principal or resource acts like an attacker.
- Posture: something is configured in a way that invites trouble. AWS Config records configuration; Security Hub CSPM runs controls against it and scores you.
- Vulnerability: software has a known flaw. Amazon Inspector scans EC2 instances, ECR images and Lambda functions for CVEs and exposed network paths.
- Data: sensitive data is somewhere it should not be. Amazon Macie scans S3 for PII, credentials and financial data.
Then there are tools for investigation (Amazon Detective builds a graph of activity around a finding) and for protection at the edge (WAF, Shield, Firewall Manager), covered below. Since December 2025 the service called AWS Security Hub is a newer, unified console that correlates GuardDuty, Inspector, Macie and posture signals into prioritized exposure findings, and the original posture product is now named Security Hub CSPM. Older blog posts say "Security Hub" and mean the CSPM part. Check which one a runbook refers to.
Raw signal: API calls, network flows, DNS queries and configuration snapshots. Nobody reads these directly at scale.
GuardDuty: how it actually detects
GuardDuty is a managed threat detector. Its foundational data sources are CloudTrail management events, VPC flow logs and Route 53 Resolver DNS query logs. It reads these from AWS's side, independently of your own trails and flow logs, so enabling it is one switch. Optional protection plans add more signal: S3 data events, EKS audit logs, runtime monitoring agents on EC2, ECS and EKS, malware scanning of EBS volumes and new S3 objects, RDS login activity, and Lambda network activity.
Finding names follow a pattern you can read once you know it: ThreatPurpose:ResourceType/ThreatFamily.Mechanism!Artifact. A few you will see in real accounts:
UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS: credentials created for an EC2 instance role are being used from an IP outside AWS. Someone stole them, usually through SSRF against the instance metadata service.CryptoCurrency:EC2/BitcoinTool.B!DNS: an instance is resolving domains associated with mining pools.Recon:IAMUser/MaliciousIPCaller: API calls from an IP on a threat list.Policy:IAMUser/RootCredentialUsage: someone used the root user. Often legitimate, always worth a look.Stealth:IAMUser/CloudTrailLoggingDisabled: someone switched off a trail. Attackers do this early.AttackSequence:IAM/CompromisedCredentials: Extended Threat Detection has correlated several signals over time into one multi-stage attack.
Severity is a number. GuardDuty maps 1.0 to 3.9 to Low, 4.0 to 6.9 to Medium, 7.0 to 8.9 to High and 9.0 to 10.0 to Critical (attack sequences). Route on the number, not the label.
Two practical habits. First, generate sample findings (aws guardduty create-sample-findings) when you build alerting, so you can test the pipeline without waiting for an attack. Second, tune with suppression rules and trusted IP lists instead of ignoring the console: a pen-test vendor's IPs or a known scanner should be auto-archived with a written reason, so a real finding never drowns in noise.
Posture: Config, Security Hub CSPM and the standards
AWS Config runs a configuration recorder that captures a configuration item each time a resource changes. That history answers questions CloudTrail alone cannot: CloudTrail says AuthorizeSecurityGroupIngress happened, Config shows the full rule set before and after. Config rules evaluate resources against a check (managed rules like s3-bucket-public-read-prohibited, or your own Lambda or Guard rules), and conformance packs bundle rules plus remediation into a deployable unit you can push across an organization.
Security Hub CSPM sits on top. You enable standards, the most common being AWS Foundational Security Best Practices (FSBP), plus CIS, PCI DSS or NIST if your compliance team needs them. Each standard is a set of controls, and most controls run as service-linked Config rules, which is why Security Hub CSPM needs Config recording enabled. Control IDs are worth recognizing because they appear in tickets: [IAM.4] IAM root user access key should not exist, [CloudTrail.1] for a multi-Region trail, [EC2.19] for security groups open on high-risk ports, [S3.8] for block public access, [RDS.3] for encryption at rest.
So when do you use which? Use Security Hub CSPM controls as your default scoreboard, because they are curated and cross-account. Write your own Config rules (or conformance packs) for company-specific policy: "every bucket must have a data-classification tag", "only approved AMIs". Config also bills per configuration item recorded, so think before recording high-churn resource types in every account.
This is also what auditors ask for. In a SOC 2 or ISO 27001 audit, "show me that every database is encrypted and that you would know if one were not" is answered with the Config history and a Security Hub control report, and "show me who changed production access in Q3" is answered with the organization trail. Evidence that a system produces automatically beats screenshots every time.
The specialists: Inspector, Macie and Detective
Amazon Inspector continuously scans EC2 instances (through the SSM agent or agentless snapshot scanning), container images in ECR, and Lambda functions (dependencies, and optionally your code). It rescans when a new CVE is published, not just when you push, and it scores findings with network reachability in mind: a critical CVE on an instance reachable from the internet ranks above the same CVE on an isolated one. Teams wire Inspector ECR findings into CI so an image with a fixable critical CVE fails the build.
Amazon Macie discovers sensitive data in S3: names, card numbers, credentials, national IDs. Its automated discovery samples across buckets so you learn where PII lives, which is half of any privacy request ("delete everything we hold on this customer").
Amazon Detective takes a GuardDuty finding and shows the surrounding activity: what else this role did, which IPs it talked to, how that compares with its normal baseline. It shortens investigations; it does not detect anything on its own.
At the edge: WAF, Shield and Firewall Manager
AWS WAF attaches a web ACL to CloudFront, an ALB, API Gateway, AppSync or Cognito and inspects HTTP requests. In practice you start with AWS managed rule groups: AWSManagedRulesCommonRuleSet (broad OWASP-style protection), AWSManagedRulesKnownBadInputsRuleSet, AWSManagedRulesSQLiRuleSet and the IP reputation list. Add a rate-based rule that blocks an IP (or a header, or a session cookie) making more than N requests in a window, which stops credential stuffing against /login cold. Always deploy new rules in Count mode first and read the logs; a rule that blocks your own mobile app's user agent is a self-inflicted outage.
AWS Shield Standard is automatic and free for everyone: it absorbs common network and transport layer DDoS attacks. Shield Advanced is a paid subscription for large or high-profile targets: application layer DDoS detection, access to the Shield Response Team, and cost protection for scaling during an attack. Firewall Manager lets a security team push WAF rules, Shield Advanced protection and security group policies across every account in the organization from one place.
Match each question to the service that answers it.
Runbook: a leaked access key
This is the incident juniors are most likely to cause and seniors most likely to run, so learn it as a sequence.
1. AWS notices first, often within minutes. AWS scans public code hosts for access keys. When it finds yours it emails the account contact, opens a support case, and attaches the managed policy AWSCompromisedKeyQuarantineV3 to the IAM user. That policy denies high-risk actions such as ec2:RunInstances, iam:CreateUser, iam:CreateAccessKey, iam:PassRole, lambda:CreateFunction and s3:DeleteBucket. It limits damage; it does not end the incident. Do not remove it until you are done.
2. Identify the key. aws sts get-access-key-info --access-key-id AKIA... returns the owning account ID for any key. aws iam list-access-keys --user-name ... and the credential report show which user owns it and when it was last used.
3. Contain. Deactivate the key. Then remember that the attacker may have used it to call GetSessionToken, minting temporary credentials that live up to 36 hours and carry the user's permissions. Temporary credentials are evaluated against the user's policies on every request, so attach AWSDenyAll (or an inline deny-all) to the user. For a compromised role, use Revoke active sessions, which adds a deny on aws:TokenIssueTime.
aws iam update-access-key --user-name ci-legacy --access-key-id AKIAEXAMPLELEAKED01 --status Inactiveaws iam attach-user-policy --user-name ci-legacy --policy-arn arn:aws:iam::aws:policy/AWSDenyAllaws cloudtrail lookup-events --region us-east-1 --lookup-attributes AttributeKey=AccessKeyId,AttributeValue=AKIAEXAMPLELEAKED014. Investigate in every Region. lookup-events covers 90 days of management events for one Region per call, so loop over Regions, or better, query the organization trail in the log archive with Athena or CloudTrail Lake. IAM and STS calls on global endpoints are logged in us-east-1. Look for persistence: new users, access keys, login profiles, roles with trust policies naming outside accounts, Lambda functions, and instances in Regions you never use.
Press Run (⌘ Enter) to see what happens.The output reads like a real attack: confirm the key works, look around, create a backdoor user with its own key, try to launch miners, and mint session credentials that outlive the original key. Every successful persistence call is something you must undo, because deactivating the leaked key does nothing to the new user's new key.
5. Eradicate and recover. Delete the backdoor user and its keys, terminate rogue instances in every Region, remove unknown roles and functions, and rotate any secret the user could read. Purging the key from git history is good hygiene but the key is burned regardless. Reply to the support case with what you did; it is also the place to raise any unexpected charges.
6. Fix the cause. Ask why a long-lived key existed. The durable fix is to remove it: OIDC for CI, roles for workloads, IAM Identity Center for humans.
Order the leaked-key response from first to last.
- Tap the steps below in the right order.
The leaked key is deactivated. How many sets of credentials can the attacker still use?
credentials = [
{"kind": "leaked access key", "active": True},
{"kind": "session from GetSessionToken", "active": True},
{"kind": "new user's access key", "active": True},
]
credentials[0]["active"] = False # you deactivated the leaked key
print(sum(c["active"] for c in credentials))Detection as code with EventBridge
Every GuardDuty finding and every Security Hub finding is published to EventBridge in the account where it is aggregated. A rule with an event pattern decides what happens next. Numeric matching keeps the pattern short:
{
"source": ["aws.guardduty"],
"detail-type": ["GuardDuty Finding"],
"detail": { "severity": [{ "numeric": [">=", 7] }] }
}Targets are usually an SNS topic wired to chat and the paging tool, plus a Lambda for a small set of automatic responses. Good candidates for automation are narrow and reversible: re-enable S3 Block Public Access when a bucket turns public, tag and snapshot an instance flagged for mining and swap its security group for an isolation group that allows nothing, or disable an IAM user's keys when GuardDuty reports exfiltrated credentials. Bad candidates are anything that can take production down on a false positive. Start every rule as "notify only", watch it for a few weeks, then automate what proved reliable.
GuardDuty keeps findings for 90 days. Export them to S3 in the log archive if you need a longer record, which most compliance programs do.
Shared responsibility, service by service
The shared responsibility model from Cloud Basics gets concrete once you map it to these tools:
| You run on | AWS secures | You still own | Tool that helps |
|---|---|---|---|
| EC2 | Hardware, hypervisor, network | OS patches, agents, open ports, instance role scope | Inspector, GuardDuty Runtime, Config |
| ECS on Fargate, Lambda | Host OS and runtime patching | Your image or package dependencies, task or function role | Inspector (ECR, Lambda) |
| S3 | Durability, encryption at rest by default | Bucket policies, public access, what data you put there | Access Analyzer, Macie, Config |
| RDS | Engine patching (in your window), backups you enable | Network exposure, credentials, encryption choice | Security Hub controls |
The pattern: the more managed the service, the less you patch, but identity and data exposure are always yours.
- GuardDuty
- Managed threat detection that analyzes CloudTrail, VPC flow and DNS data (plus optional protection plans) and raises findings.
- Security Hub CSPM
- Posture management that runs controls from standards like FSBP and CIS against your accounts and aggregates findings. Formerly just 'Security Hub'.
- AWS Config
- Records configuration items for resources over time and evaluates them with Config rules and conformance packs.
- delegated administrator
- A member account (usually security) that manages a security service for the whole organization.
- AWSCompromisedKeyQuarantineV3
- AWS managed deny policy AWS attaches to an IAM user whose key was found exposed, blocking high-risk actions.
- rate-based rule
- A WAF rule that blocks or counts requests from a source once it exceeds a request count in a time window.
- suppression rule
- A GuardDuty filter that auto-archives findings you have reviewed and accepted as expected.