npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
When to Use
- When establishing continuous threat detection for new or existing AWS accounts
- When investigating GuardDuty findings related to compromised instances, credential abuse, or data exfiltration
- When building automated incident response playbooks triggered by GuardDuty findings
- When extending threat coverage to container workloads running on EKS, ECS, or Fargate
- When enabling malware scanning for EBS volumes attached to suspicious EC2 instances
Do not use for Azure or GCP threat detection (see securing-azure-with-microsoft-defender or auditing-gcp-security-posture), for static code analysis, or for compliance posture monitoring (see implementing-aws-security-hub).
Prerequisites
- AWS account with GuardDuty administrative permissions (guardduty:*)
- AWS CloudTrail, VPC Flow Logs, and DNS query logs enabled (GuardDuty consumes these automatically)
- AWS Organizations configured if deploying GuardDuty across a multi-account estate
- EventBridge and Lambda configured for automated response workflows
Workflow
Step 1: Enable GuardDuty and Protection Plans
Activate GuardDuty at the organization level using a delegated administrator account. Enable all protection plans including S3 Protection, EKS Audit Log Monitoring, Runtime Monitoring, Malware Protection, RDS Login Activity, and Lambda Network Activity Monitoring.
# Enable GuardDuty as organization delegated administrator
aws guardduty create-detector \
--enable \
--finding-publishing-frequency FIFTEEN_MINUTES \
--data-sources '{
"S3Logs": {"Enable": true},
"Kubernetes": {"AuditLogs": {"Enable": true}},
"MalwareProtection": {"ScanEc2InstanceWithFindings": {"EbsVolumes": true}}
}'
# Enable Runtime Monitoring for EC2 and ECS
aws guardduty update-detector \
--detector-id <detector-id> \
--features '[
{"Name": "RUNTIME_MONITORING", "Status": "ENABLED",
"AdditionalConfiguration": [
{"Name": "ECS_FARGATE_AGENT_MANAGEMENT", "Status": "ENABLED"},
{"Name": "EC2_AGENT_MANAGEMENT", "Status": "ENABLED"}
]}
]'
# Designate delegated admin for multi-account
aws guardduty enable-organization-admin-account \
--admin-account-id 111122223333Step 2: Configure Multi-Account Aggregation
Automatically enroll all organization member accounts and configure finding export to a centralized S3 bucket for retention and SIEM ingestion.
# Auto-enable GuardDuty for all org members
aws guardduty update-organization-configuration \
--detector-id <detector-id> \
--auto-enable-organization-members ALL \
--features '[
{"Name": "S3_DATA_EVENTS", "AutoEnable": "ALL"},
{"Name": "EKS_AUDIT_LOGS", "AutoEnable": "ALL"},
{"Name": "RUNTIME_MONITORING", "AutoEnable": "ALL"}
]'
# Configure finding export to S3
aws guardduty create-publishing-destination \
--detector-id <detector-id> \
--destination-type S3 \
--destination-properties '{
"DestinationArn": "arn:aws:s3:::guardduty-findings-centralized",
"KmsKeyArn": "arn:aws:kms:us-east-1:123456789012:key/key-id"
}'Step 3: Interpret Finding Types and Severity Levels
GuardDuty classifies findings into four severity levels: Critical, High, Medium, and Low. Each finding type follows the format ThreatPurpose:ResourceType/ThreatName. Extended Threat Detection generates attack sequence findings that correlate multiple events across time.
Key finding categories:
- Recon: Port scanning, API enumeration (e.g., Recon:EC2/PortProbeUnprotectedPort)
- UnauthorizedAccess: Credential abuse, console logins from unusual locations
- CryptoCurrency: Mining activity detected on instances (e.g., CryptoCurrency:EC2/BitcoinTool.B)
- Impact: Resource hijacking, data destruction attempts
- AttackSequence: Multi-stage attacks correlating initial access through lateral movement to impact (Critical severity)
Step 4: Build Automated Response with EventBridge
Create EventBridge rules that route GuardDuty findings to Lambda functions for automated containment actions such as isolating compromised EC2 instances, revoking IAM credentials, or blocking malicious IP addresses.
# EventBridge rule for high/critical GuardDuty findings
aws events put-rule \
--name GuardDutyHighSeverity \
--event-pattern '{
"source": ["aws.guardduty"],
"detail-type": ["GuardDuty Finding"],
"detail": {
"severity": [{"numeric": [">=", 7]}]
}
}'
# Target Lambda function for auto-remediation
aws events put-targets \
--rule GuardDutyHighSeverity \
--targets '[{
"Id": "AutoRemediateTarget",
"Arn": "arn:aws:lambda:us-east-1:123456789012:function/guardduty-auto-remediate"
}]'Auto-remediation Lambda example for isolating a compromised EC2 instance:
import boto3
def lambda_handler(event, context):
finding = event['detail']
finding_type = finding['type']
severity = finding['severity']
if finding_type.startswith('UnauthorizedAccess:EC2') and severity >= 7:
instance_id = finding['resource']['instanceDetails']['instanceId']
ec2 = boto3.client('ec2')
# Create isolation security group (no inbound/outbound rules)
vpc_id = finding['resource']['instanceDetails']['networkInterfaces'][0]['vpcId']
isolation_sg = ec2.create_security_group(
GroupName=f'isolation-{instance_id}',
Description='GuardDuty auto-isolation',
VpcId=vpc_id
)
# Replace all security groups with isolation group
ec2.modify_instance_attribute(
InstanceId=instance_id,
Groups=[isolation_sg['GroupId']]
)
# Tag instance for investigation
ec2.create_tags(
Resources=[instance_id],
Tags=[{'Key': 'SecurityStatus', 'Value': 'ISOLATED'},
{'Key': 'GuardDutyFinding', 'Value': finding_type}]
)
return {'status': 'isolated', 'instance': instance_id}Step 5: Investigate Extended Threat Detection Attack Sequences
Review Critical-severity attack sequence findings that correlate multiple signals across EC2, ECS, and EKS. These findings represent multi-stage attacks such as initial access through compromised credentials followed by persistence, lateral movement, and crypto mining.
# List critical attack sequence findings
aws guardduty list-findings \
--detector-id <detector-id> \
--finding-criteria '{
"Criterion": {
"severity": {"Gte": 9},
"type": {"Eq": ["AttackSequence:EC2/CompromisedInstanceGroup",
"AttackSequence:ECS/CompromisedCluster",
"AttackSequence:EKS/CompromisedCluster"]}
}
}'
# Get full finding details with attack sequence timeline
aws guardduty get-findings \
--detector-id <detector-id> \
--finding-ids <finding-id>Step 6: Integrate with Security Hub and SIEM
Forward GuardDuty findings to AWS Security Hub for centralized aggregation and to external SIEM platforms via S3 export or Amazon Security Lake for long-term retention and cross-source correlation.
# Verify GuardDuty integration with Security Hub
aws securityhub get-enabled-standards
# Enable Amazon Security Lake with GuardDuty as a source
aws securitylake create-data-lake \
--configurations '[{
"region": "us-east-1",
"lifecycleConfiguration": {
"expiration": {"days": 365}
}
}]'Key Concepts
| Term | Definition |
|---|---|
| Extended Threat Detection | GuardDuty capability that correlates multiple signals across time to detect multi-stage attacks, generating Critical-severity attack sequence findings |
| Runtime Monitoring | Protection plan that deploys a security agent to EC2 instances, ECS tasks, and EKS pods to detect runtime threats at the OS level |
| Finding Severity | Four-tier classification (Low, Medium, High, Critical) where Critical indicates confirmed multi-stage attacks requiring immediate response |
| Malware Protection | On-demand and automatic EBS volume scanning triggered by suspicious EC2 behavior to detect malware without agent installation |
| Delegated Administrator | Organization member account designated to manage GuardDuty across all accounts in an AWS Organization |
| Suppression Rule | Filter that automatically archives findings matching specific criteria to reduce noise from known benign activity |
| Threat Intelligence | IP reputation lists and domain threat feeds used by GuardDuty to identify communication with known malicious infrastructure |
Tools & Systems
- Amazon GuardDuty: Core threat detection service analyzing CloudTrail, VPC Flow Logs, DNS logs, and runtime telemetry
- Amazon EventBridge: Serverless event bus for routing GuardDuty findings to automated response targets
- AWS Security Hub: Centralized security findings aggregation supporting automated remediation workflows
- Amazon Security Lake: OCSF-normalized data lake for long-term security log retention and cross-service correlation
- Amazon Detective: Graph-based investigation service that visualizes relationships between GuardDuty findings, resources, and API activity
Common Scenarios
Scenario: Cryptocurrency Mining Detected on ECS Cluster
Context: GuardDuty generates a CryptoCurrency:Runtime/BitcoinTool.B finding with High severity targeting an ECS Fargate task. Runtime Monitoring detected the execution of a mining binary within a container.
Approach:
- Review the finding details to identify the ECS cluster, task definition, and container image
- Stop the affected ECS task immediately and quarantine the container image in ECR
- Check CloudTrail for the ecs:RegisterTaskDefinition and ecs:RunTask calls to identify who deployed the malicious image
- Scan the Docker image with ECR enhanced scanning to identify the embedded mining binary
- Review IAM credentials used to push the image and revoke compromised access
- Update ECR image scanning policies to block images with known mining signatures
Pitfalls: Stopping the task without preserving the container image loses forensic evidence. Failing to trace back to the RegisterTaskDefinition API call misses the initial compromise vector.
Output Format
GuardDuty Threat Detection Summary
====================================
Account: 123456789012 (production)
Region: us-east-1
Period: 2025-02-01 to 2025-02-23
CRITICAL FINDINGS (Immediate Action Required):
[CRIT-001] AttackSequence:EC2/CompromisedInstanceGroup
- Instances: i-0abc123def, i-0def456abc
- Attack Chain: Credential theft -> Persistence -> Crypto mining
- First Signal: 2025-02-15T08:23:00Z
- Duration: 4 hours across 3 stages
- Status: Auto-isolated via Lambda
HIGH FINDINGS:
[HIGH-001] UnauthorizedAccess:IAMUser/MaliciousIPCaller
- Principal: arn:aws:iam::123456789012:user/ci-deploy
- Source IP: 198.51.100.42 (Tor exit node)
- API Calls: 47 calls to ec2:RunInstances
- Status: Access key deactivated
[HIGH-002] CryptoCurrency:Runtime/BitcoinTool.B
- Resource: ECS Task arn:aws:ecs:us-east-1:123456789012:task/cluster/task-id
- Image: 123456789012.dkr.ecr.us-east-1.amazonaws.com/app:v2.1
- Process: /tmp/.hidden/xmrig --pool stratum+tcp://pool.example.com:3333
- Status: Task stopped, image quarantined
STATISTICS:
Total Findings: 23
Critical: 1 | High: 3 | Medium: 8 | Low: 11
Auto-Remediated: 4
Pending Investigation: 2References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 1
api-reference.md2.2 KB
Amazon GuardDuty API Reference
GuardDuty CLI - Core Operations
# Enable GuardDuty
aws guardduty create-detector --enable \
--finding-publishing-frequency FIFTEEN_MINUTES \
--data-sources '{"S3Logs":{"Enable":true},"Kubernetes":{"AuditLogs":{"Enable":true}}}'
# Get detector ID
aws guardduty list-detectors --query 'DetectorIds[0]' --output text
# Get detector status
aws guardduty get-detector --detector-id $DETECTOR_ID
# Enable Runtime Monitoring
aws guardduty update-detector --detector-id $DETECTOR_ID \
--features '[{"Name":"RUNTIME_MONITORING","Status":"ENABLED","AdditionalConfiguration":[{"Name":"ECS_FARGATE_AGENT_MANAGEMENT","Status":"ENABLED"}]}]'Finding Management
# List findings by severity
aws guardduty list-findings --detector-id $DET \
--finding-criteria '{"Criterion":{"severity":{"Gte":7}}}' \
--sort-criteria '{"AttributeName":"severity","OrderBy":"DESC"}'
# Get finding details
aws guardduty get-findings --detector-id $DET --finding-ids id1 id2
# Archive findings
aws guardduty archive-findings --detector-id $DET --finding-ids id1
# Create suppression filter
aws guardduty create-filter --detector-id $DET \
--name "SuppressDevVPC" --action ARCHIVE \
--finding-criteria '{"Criterion":{"resource.instanceDetails.networkInterfaces.subnetId":{"Eq":["subnet-dev"]}}}'GuardDuty Finding Severity Levels
| Range | Level | Action |
|---|---|---|
| 7.0 - 8.9 | HIGH | Immediate investigation |
| 4.0 - 6.9 | MEDIUM | Investigation within 24h |
| 1.0 - 3.9 | LOW | Review during business hours |
Key Finding Type Prefixes
| Prefix | Source |
|---|---|
Recon: |
Reconnaissance activity |
UnauthorizedAccess: |
Credential or access abuse |
CryptoCurrency: |
Mining activity |
Trojan: |
Malware communication |
Impact: |
Resource abuse |
Exfiltration: |
Data theft |
Persistence: |
Backdoor/persistence |
EventBridge Rule for GuardDuty
{
"source": ["aws.guardduty"],
"detail-type": ["GuardDuty Finding"],
"detail": {
"severity": [{"numeric": [">=", 7]}]
}
}Threat Intel Set
aws guardduty create-threat-intel-set --detector-id $DET \
--name "CustomBadIPs" --format TXT \
--location s3://bucket/threat-ips.txt --activateScripts 1
agent.py6.5 KB
#!/usr/bin/env python3
"""Amazon GuardDuty threat detection and response automation agent."""
import json
import subprocess
import sys
from datetime import datetime
def aws_cli(args):
"""Execute AWS CLI command and return parsed JSON."""
cmd = ["aws"] + args + ["--output", "json"]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode == 0:
return json.loads(result.stdout) if result.stdout.strip() else {}
return {"error": result.stderr.strip()}
except Exception as e:
return {"error": str(e)}
def get_detector_id():
"""Retrieve the GuardDuty detector ID."""
result = aws_cli(["guardduty", "list-detectors"])
ids = result.get("DetectorIds", [])
return ids[0] if ids else None
def enable_guardduty():
"""Enable GuardDuty with all protection plans."""
result = aws_cli([
"guardduty", "create-detector",
"--enable",
"--finding-publishing-frequency", "FIFTEEN_MINUTES",
"--data-sources", json.dumps({
"S3Logs": {"Enable": True},
"Kubernetes": {"AuditLogs": {"Enable": True}},
"MalwareProtection": {"ScanEc2InstanceWithFindings": {"EbsVolumes": True}},
}),
])
return result
def get_detector_status(detector_id=None):
"""Get GuardDuty detector configuration and status."""
if not detector_id:
detector_id = get_detector_id()
if not detector_id:
return {"error": "No detector found. Run enable_guardduty first."}
return aws_cli(["guardduty", "get-detector", "--detector-id", detector_id])
def list_findings(detector_id=None, severity_min=4.0, max_results=50):
"""List active GuardDuty findings filtered by minimum severity."""
if not detector_id:
detector_id = get_detector_id()
if not detector_id:
return {"error": "No detector found"}
criteria = {
"Criterion": {
"severity": {"Gte": int(severity_min)},
"service.archived": {"Eq": ["false"]},
}
}
result = aws_cli([
"guardduty", "list-findings",
"--detector-id", detector_id,
"--finding-criteria", json.dumps(criteria),
"--max-results", str(max_results),
"--sort-criteria", json.dumps({"AttributeName": "severity", "OrderBy": "DESC"}),
])
return result
def get_finding_details(detector_id, finding_ids):
"""Get detailed information about specific findings."""
if isinstance(finding_ids, str):
finding_ids = [finding_ids]
result = aws_cli([
"guardduty", "get-findings",
"--detector-id", detector_id,
"--finding-ids"] + finding_ids[:25]
)
findings = []
for f in result.get("Findings", []):
resource = f.get("Resource", {})
service = f.get("Service", {})
findings.append({
"id": f.get("Id"),
"type": f.get("Type"),
"severity": f.get("Severity"),
"title": f.get("Title"),
"description": f.get("Description", "")[:200],
"region": f.get("Region"),
"account_id": f.get("AccountId"),
"resource_type": resource.get("ResourceType"),
"instance_id": resource.get("InstanceDetails", {}).get("InstanceId"),
"action": service.get("Action", {}),
"first_seen": service.get("EventFirstSeen"),
"last_seen": service.get("EventLastSeen"),
"count": service.get("Count"),
})
return findings
def archive_finding(detector_id, finding_ids):
"""Archive (suppress) GuardDuty findings."""
if isinstance(finding_ids, str):
finding_ids = [finding_ids]
return aws_cli([
"guardduty", "archive-findings",
"--detector-id", detector_id,
"--finding-ids"] + finding_ids
)
def create_ip_threat_intel_set(detector_id, name, s3_uri):
"""Create a custom threat intelligence IP set."""
return aws_cli([
"guardduty", "create-threat-intel-set",
"--detector-id", detector_id,
"--name", name,
"--format", "TXT",
"--location", s3_uri,
"--activate",
])
def create_suppression_filter(detector_id, name, criterion):
"""Create a suppression filter to auto-archive known benign findings."""
return aws_cli([
"guardduty", "create-filter",
"--detector-id", detector_id,
"--name", name,
"--action", "ARCHIVE",
"--finding-criteria", json.dumps({"Criterion": criterion}),
])
def generate_report(detector_id=None):
"""Generate a GuardDuty findings summary report."""
if not detector_id:
detector_id = get_detector_id()
if not detector_id:
return {"error": "No detector found"}
findings_result = list_findings(detector_id, severity_min=1)
finding_ids = findings_result.get("FindingIds", [])
details = []
if finding_ids:
details = get_finding_details(detector_id, finding_ids[:25])
severity_dist = {"HIGH": 0, "MEDIUM": 0, "LOW": 0}
type_counts = {}
for f in details:
sev = f.get("severity", 0)
if sev >= 7:
severity_dist["HIGH"] += 1
elif sev >= 4:
severity_dist["MEDIUM"] += 1
else:
severity_dist["LOW"] += 1
ftype = f.get("type", "unknown")
type_counts[ftype] = type_counts.get(ftype, 0) + 1
return {
"timestamp": datetime.utcnow().isoformat() + "Z",
"detector_id": detector_id,
"total_active_findings": len(finding_ids),
"severity_distribution": severity_dist,
"finding_types": type_counts,
"critical_findings": [f for f in details if f.get("severity", 0) >= 7],
}
if __name__ == "__main__":
action = sys.argv[1] if len(sys.argv) > 1 else "report"
det = get_detector_id()
if action == "report":
print(json.dumps(generate_report(det), indent=2, default=str))
elif action == "enable":
print(json.dumps(enable_guardduty(), indent=2))
elif action == "status":
print(json.dumps(get_detector_status(det), indent=2))
elif action == "findings":
sev = float(sys.argv[2]) if len(sys.argv) > 2 else 4.0
print(json.dumps(list_findings(det, sev), indent=2))
elif action == "details" and len(sys.argv) > 2:
print(json.dumps(get_finding_details(det, sys.argv[2:]), indent=2, default=str))
elif action == "archive" and len(sys.argv) > 2:
print(json.dumps(archive_finding(det, sys.argv[2:]), indent=2))
else:
print("Usage: agent.py [report|enable|status|findings [min_severity]|details <id>|archive <id>]")