Production hardening: security fixes, code quality, 724 skills complete

- Fix 25 shell=True subprocess calls with list-based commands
- Fix 49 verify=False in defensive skills (env-var override)
- Add timeout to 231 HTTP/subprocess/socket calls
- Fix 6 SQL injection patterns with whitelist validation
- Replace 8 __import__() with standard imports
- Remove 701 unused imports across 442 files
- Add authorized-testing disclaimers to all offensive skills
- Complete 11 incomplete skill directories
- Expand 10 stub SKILL.md files with full content
- Fix 2 YAML parse errors in frontmatter
- Fix 5 pre-existing syntax errors
- Convert 22 hardcoded paths/ports to environment variables
- Back up 21 redundant skill pairs to .bak
- Fix 2 global declaration errors
- 724/724 skills with full folder anatomy (SKILL.md + agent.py + api-reference.md + LICENSE)
- 0 compile errors across all 724 agent.py files
This commit is contained in:
mukul975
2026-03-19 13:26:49 +01:00
parent 63b442d347
commit c47eed6a64
900 changed files with 23085 additions and 2720 deletions
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,318 @@
---
name: detecting-cloud-cryptomining-activity
description: >
Detecting unauthorized cryptocurrency mining activity in cloud environments by analyzing
compute usage anomalies, network traffic to mining pools, GuardDuty findings, and
container workload behavior using AWS, Azure, and GCP native security services.
domain: cybersecurity
subdomain: cloud-security
tags: [cloud-security, cryptomining, threat-detection, guardduty, cost-anomaly, incident-response]
version: "1.0"
author: mahipal
license: Apache-2.0
---
# Detecting Cloud Cryptomining Activity
## When to Use
- When investigating unexpected spikes in cloud compute costs or CPU utilization
- When GuardDuty, Defender for Cloud, or SCC reports cryptocurrency-related findings
- When monitoring for compromised credentials being used to launch mining instances
- When building detection rules for unauthorized workload deployment in cloud environments
- When responding to alerts about network connections to known mining pool infrastructure
**Do not use** for detecting cryptomining on endpoints or on-premises servers (use EDR tools), for investigating the financial impact of mining (use cloud cost management tools), or for blocking mining at the network level (use DNS filtering and firewall rules).
## Prerequisites
- AWS GuardDuty enabled across all accounts and regions
- Azure Defender for Cloud with server and container plans enabled
- GCP Security Command Center with Event Threat Detection enabled
- CloudTrail, Azure Activity Log, and GCP Audit Log enabled for API monitoring
- Cloud cost monitoring and alerting configured (AWS Cost Anomaly Detection, Azure Cost Management)
- Network flow logs enabled (VPC Flow Logs, NSG Flow Logs, VPC Flow Logs)
## Workflow
### Step 1: Identify GuardDuty Cryptocurrency Findings (AWS)
Query GuardDuty for cryptocurrency-specific finding types that indicate mining activity.
```bash
# List active cryptocurrency-related findings
aws guardduty list-findings \
--detector-id $(aws guardduty list-detectors --query 'DetectorIds[0]' --output text) \
--finding-criteria '{
"Criterion": {
"type": {
"Eq": [
"CryptoCurrency:EC2/BitcoinTool.B!DNS",
"CryptoCurrency:EC2/BitcoinTool.B",
"CryptoCurrency:Runtime/BitcoinTool.B!DNS",
"CryptoCurrency:Runtime/BitcoinTool.B",
"CryptoCurrency:Lambda/BitcoinTool.B"
]
},
"service.archived": {"Eq": ["false"]}
}
}' --output json
# Get detailed findings
FINDING_IDS=$(aws guardduty list-findings \
--detector-id $(aws guardduty list-detectors --query 'DetectorIds[0]' --output text) \
--finding-criteria '{"Criterion":{"type":{"Eq":["CryptoCurrency:EC2/BitcoinTool.B!DNS"]}}}' \
--query 'FindingIds' --output json)
aws guardduty get-findings \
--detector-id $(aws guardduty list-detectors --query 'DetectorIds[0]' --output text) \
--finding-ids $FINDING_IDS \
--query 'Findings[*].{Type:Type,Severity:Severity,Resource:Resource.InstanceDetails.InstanceId,RemoteIP:Service.Action.NetworkConnectionAction.RemoteIpDetails.IpAddressV4,Domain:Service.Action.DnsRequestAction.Domain}' \
--output table
```
### Step 2: Detect Compute Usage Anomalies
Monitor for unexpected compute resource provisioning and CPU utilization spikes that indicate mining.
```bash
# AWS: Find recently launched large instances (mining often uses c5/p3/g4 instances)
aws ec2 describe-instances \
--filters "Name=instance-state-name,Values=running" \
--query 'Reservations[*].Instances[*].[InstanceId,InstanceType,LaunchTime,Tags[?Key==`Name`].Value|[0]]' \
--output table | grep -E "c5\.|c6\.|p3\.|p4\.|g4\.|g5\."
# AWS: Check for high CPU utilization
aws cloudwatch get-metric-statistics \
--namespace AWS/EC2 \
--metric-name CPUUtilization \
--dimensions Name=InstanceId,Value=i-SUSPECT_INSTANCE \
--start-time 2026-02-22T00:00:00Z \
--end-time 2026-02-23T00:00:00Z \
--period 3600 \
--statistics Average \
--query 'Datapoints[*].[Timestamp,Average]' --output table
# AWS: Check Cost Anomaly Detection
aws ce get-anomalies \
--date-interval '{"StartDate":"2026-02-16","EndDate":"2026-02-23"}' \
--query 'Anomalies[*].[AnomalyId,AnomalyScore.MaxScore,Impact.TotalImpact,RootCauses[0].Service]' \
--output table
# Azure: Find VMs with unusual CPU patterns
az monitor metrics list \
--resource /subscriptions/SUB_ID/resourceGroups/RG/providers/Microsoft.Compute/virtualMachines/VM_NAME \
--metric "Percentage CPU" \
--interval PT1H \
--start-time 2026-02-22T00:00:00Z \
--end-time 2026-02-23T00:00:00Z
```
### Step 3: Analyze Network Traffic for Mining Pool Connections
Identify network connections to known cryptocurrency mining pools and Stratum protocol traffic.
```bash
# Query VPC Flow Logs for connections to known mining pool ports (3333, 4444, 8333, 14444)
# AWS: Using CloudWatch Logs Insights
aws logs start-query \
--log-group-name vpc-flow-logs \
--start-time $(date -d "24 hours ago" +%s) \
--end-time $(date +%s) \
--query-string '
fields @timestamp, srcAddr, dstAddr, dstPort, bytes
| filter dstPort in [3333, 4444, 8333, 14444, 14433, 45700]
| sort bytes desc
| limit 100
'
# Check DNS queries for mining pool domains
aws logs start-query \
--log-group-name route53-resolver-logs \
--start-time $(date -d "24 hours ago" +%s) \
--end-time $(date +%s) \
--query-string '
fields @timestamp, query_name, srcids.instance
| filter query_name like /pool|mining|xmr|monero|nicehash|ethermine|f2pool|nanopool/
| limit 100
'
# GCP: Query VPC Flow Logs for mining connections
gcloud logging read '
resource.type="gce_subnetwork"
AND jsonPayload.connection.dest_port=(3333 OR 4444 OR 8333 OR 14444)
AND timestamp>="2026-02-22T00:00:00Z"
' --limit=50 --format=json
```
### Step 4: Investigate Container and Serverless Mining
Check for cryptomining within container workloads and serverless functions.
```bash
# EKS/Kubernetes: Find pods with high CPU usage
kubectl top pods --all-namespaces --sort-by=cpu | head -20
# Find suspicious container images
kubectl get pods --all-namespaces -o json | python3 -c "
import json, sys
data = json.load(sys.stdin)
suspicious = ['xmrig', 'monero', 'miner', 'crypto', 'pool', 'hashrate']
for pod in data['items']:
ns = pod['metadata']['namespace']
name = pod['metadata']['name']
for container in pod['spec'].get('containers', []):
image = container.get('image', '').lower()
if any(s in image for s in suspicious):
print(f'SUSPICIOUS: {ns}/{name} -> image: {container[\"image\"]}')
"
# Check Lambda function for mining (unusual duration and memory)
aws lambda list-functions --query 'Functions[*].[FunctionName,MemorySize,Timeout]' --output table
aws cloudwatch get-metric-statistics \
--namespace AWS/Lambda \
--metric-name Duration \
--dimensions Name=FunctionName,Value=SUSPECT_FUNCTION \
--start-time 2026-02-22T00:00:00Z \
--end-time 2026-02-23T00:00:00Z \
--period 3600 \
--statistics Average Maximum
```
### Step 5: Trace the Attack Vector
Investigate how the mining infrastructure was deployed by analyzing API logs and credential usage.
```bash
# AWS: Find who launched suspect instances
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=ResourceType,AttributeValue=AWS::EC2::Instance \
--start-time 2026-02-20T00:00:00Z \
--query 'Events[?contains(Resources[0].ResourceName, `i-SUSPECT`)].[EventTime,EventName,Username,SourceIPAddress]' \
--output table
# Check for leaked credentials being used
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=AccessKeyId,AttributeValue=AKIA_SUSPECT_KEY \
--query 'Events[*].[EventTime,EventName,SourceIPAddress,EventSource]' \
--output table
# Check for unusual API calls (RunInstances from new IPs)
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventName,AttributeValue=RunInstances \
--start-time 2026-02-20T00:00:00Z \
--query 'Events[*].[EventTime,Username,SourceIPAddress]' \
--output table
```
### Step 6: Contain and Remediate
Isolate mining resources, revoke compromised credentials, and implement preventive controls.
```bash
# Terminate mining instances
aws ec2 terminate-instances --instance-ids i-MINING_INSTANCE_1 i-MINING_INSTANCE_2
# Deactivate compromised credentials
aws iam update-access-key --user-name compromised-user \
--access-key-id AKIA_COMPROMISED --status Inactive
# Add SCP to prevent large instance types in non-production accounts
cat > mining-prevention-scp.json << 'EOF'
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Deny",
"Action": "ec2:RunInstances",
"Resource": "arn:aws:ec2:*:*:instance/*",
"Condition": {
"ForAnyValue:StringLike": {
"ec2:InstanceType": ["p3.*", "p4.*", "g4.*", "g5.*"]
}
}
}]
}
EOF
# Set up billing alarm for early detection
aws cloudwatch put-metric-alarm \
--alarm-name high-ec2-spend \
--metric-name EstimatedCharges \
--namespace AWS/Billing \
--statistic Maximum \
--period 21600 \
--threshold 500 \
--comparison-operator GreaterThanThreshold \
--alarm-actions arn:aws:sns:us-east-1:ACCOUNT:billing-alerts
```
## Key Concepts
| Term | Definition |
|------|------------|
| Cryptomining | Unauthorized use of cloud compute resources to mine cryptocurrency, typically Monero (XMR) due to its CPU-mining efficiency and privacy features |
| Stratum Protocol | Mining pool communication protocol typically running on ports 3333, 4444, or 14444 used to coordinate mining work between miners and pools |
| GuardDuty CryptoCurrency Finding | AWS threat detection finding that identifies EC2, EKS, or Lambda resources communicating with known cryptocurrency mining infrastructure |
| Cost Anomaly Detection | AWS service that uses machine learning to detect unusual spending patterns that may indicate unauthorized resource provisioning |
| Compute Abuse | Unauthorized use of cloud compute resources, commonly via compromised credentials or exploited applications, for cryptomining or other purposes |
| Service Control Policy | AWS Organizations policy that can restrict instance types or regions to prevent attackers from launching GPU/compute-optimized mining instances |
## Tools & Systems
- **AWS GuardDuty**: Threat detection service with specific finding types for cryptocurrency mining activity on EC2, EKS, and Lambda
- **Azure Defender for Cloud**: Detects cryptomining through behavioral analysis and network threat intelligence
- **GCP Event Threat Detection**: SCC component that identifies cryptocurrency mining via network analysis and process monitoring
- **CloudTrail / Activity Log / Audit Log**: API audit logs for tracing how mining resources were provisioned
- **VPC Flow Logs**: Network flow data for identifying connections to mining pool infrastructure
## Common Scenarios
### Scenario: Compromised AWS Access Key Used to Launch GPU Mining Fleet
**Context**: A billing alarm triggers after a weekend spike from $200/day to $15,000/day. Investigation reveals 50 p3.8xlarge instances running across four regions, all launched by an access key belonging to a developer.
**Approach**:
1. Query GuardDuty for CryptoCurrency findings to confirm mining activity
2. Terminate all mining instances across all regions immediately
3. Deactivate the compromised access key and check CloudTrail for the source IP
4. Discover the key was exposed in a public GitHub repository via TruffleHog scan
5. Rotate all credentials for the compromised user
6. Implement SCP to deny GPU instance types in non-production accounts
7. Enable AWS Cost Anomaly Detection with automated alerts
8. Set up git-secrets pre-commit hooks across the development team
**Pitfalls**: Cryptominers often launch instances in regions where the account has no monitoring. Enable GuardDuty in ALL regions. Mining instances may use spot requests that persist after instance termination, so also cancel any active spot fleet requests and auto-scaling groups created by the attacker.
## Output Format
```
Cloud Cryptomining Incident Report
=====================================
Account: 123456789012 (Production)
Detection Date: 2026-02-23
Alert Source: AWS Cost Anomaly Detection + GuardDuty
INCIDENT SUMMARY:
Mining instances launched: 50 (p3.8xlarge)
Regions affected: us-east-1, us-west-2, eu-west-1, ap-southeast-1
Duration: ~48 hours (Feb 21 14:00 UTC to Feb 23 10:00 UTC)
Estimated cost impact: $28,400
Cryptocurrency mined: Monero (XMR)
ATTACK VECTOR:
Compromised credential: AKIA...WXYZ (developer-user)
Exposure method: Hardcoded in public GitHub repository
First unauthorized API call: Feb 21 13:47 UTC from IP 185.x.x.x
GUARDDUTY FINDINGS:
CryptoCurrency:EC2/BitcoinTool.B!DNS: 50 findings
UnauthorizedAccess:EC2/TorIPCaller: 3 findings
CONTAINMENT ACTIONS:
[x] All mining instances terminated
[x] Compromised access key deactivated
[x] New access key issued via Secrets Manager
[x] SCP applied to deny GPU instance types
[x] Cost anomaly alerting configured
[x] GuardDuty enabled in all regions
```
@@ -0,0 +1,78 @@
# Cloud Cryptomining Detection API Reference
## GuardDuty - Cryptocurrency Finding Types
| Finding Type | Signal |
|-------------|--------|
| `CryptoCurrency:EC2/BitcoinTool.B!DNS` | EC2 querying crypto domains |
| `CryptoCurrency:EC2/BitcoinTool.B` | EC2 communicating with mining pools |
| `CryptoCurrency:Runtime/BitcoinTool.B!DNS` | Container DNS to mining domain |
| `CryptoCurrency:Runtime/BitcoinTool.B` | Container network to mining pool |
| `Impact:EC2/BitcoinDomainRequest.Reputation` | Known mining domain access |
## GuardDuty CLI
```bash
# Get detector ID
aws guardduty list-detectors --query 'DetectorIds[0]' --output text
# List crypto findings
aws guardduty list-findings --detector-id $DET \
--finding-criteria '{"Criterion":{"type":{"Eq":["CryptoCurrency:EC2/BitcoinTool.B!DNS"]}}}'
# Get finding details
aws guardduty get-findings --detector-id $DET --finding-ids id1 id2
```
## AWS Cost Anomaly Detection
```bash
# Create cost anomaly monitor
aws ce create-anomaly-monitor --anomaly-monitor '{
"MonitorName": "EC2CostSpike",
"MonitorType": "DIMENSIONAL",
"MonitorDimension": "SERVICE"
}'
# Create alert subscription
aws ce create-anomaly-subscription --anomaly-subscription '{
"SubscriptionName": "CryptoAlert",
"MonitorArnList": ["arn:aws:ce::123456789012:anomalymonitor/monitor-id"],
"Subscribers": [{"Address": "soc@company.com", "Type": "EMAIL"}],
"Threshold": 100.0,
"Frequency": "IMMEDIATE"
}'
```
## Known Mining Pool Ports
```
3333 - Stratum protocol (common)
4444 - Mining proxy
5555 - Monero (XMR)
7777 - Alt-coin mining
8888 - Multi-pool
9999 - Mining proxy
14444 - XMRig default
45700 - MoneroOcean
```
## VPC Flow Logs Query (CloudWatch Insights)
```
fields @timestamp, srcaddr, dstaddr, dstport, action
| filter dstport in [3333, 4444, 5555, 7777, 14444, 45700]
| sort @timestamp desc
| limit 50
```
## EC2 Instance Remediation
```bash
# Terminate mining instance
aws ec2 terminate-instances --instance-ids i-0123456789abcdef0
# Revoke security group ingress on mining ports
aws ec2 revoke-security-group-ingress --group-id sg-xxx \
--protocol tcp --port 3333 --cidr 0.0.0.0/0
```
@@ -0,0 +1,163 @@
#!/usr/bin/env python3
"""Cloud cryptomining detection agent using AWS GuardDuty and CloudWatch."""
import json
import subprocess
import sys
from datetime import datetime
CRYPTO_FINDING_TYPES = [
"CryptoCurrency:EC2/BitcoinTool.B!DNS",
"CryptoCurrency:EC2/BitcoinTool.B",
"CryptoCurrency:Runtime/BitcoinTool.B!DNS",
"CryptoCurrency:Runtime/BitcoinTool.B",
"CryptoCurrency:Lambda/BitcoinTool.B",
"Impact:EC2/BitcoinDomainRequest.Reputation",
"Impact:Runtime/BitcoinDomainRequest.Reputation",
]
MINING_POOL_PORTS = [3333, 4444, 5555, 7777, 8888, 9999, 14444, 45700]
def aws_cli(args):
"""Execute an 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_guardduty_detector():
"""Get the GuardDuty detector ID."""
result = aws_cli(["guardduty", "list-detectors"])
detectors = result.get("DetectorIds", [])
return detectors[0] if detectors else None
def list_crypto_findings(detector_id=None):
"""List GuardDuty findings related to cryptocurrency mining."""
if not detector_id:
detector_id = get_guardduty_detector()
if not detector_id:
return {"error": "No GuardDuty detector found"}
criteria = {"Criterion": {"type": {"Eq": CRYPTO_FINDING_TYPES}, "service.archived": {"Eq": ["false"]}}}
result = aws_cli([
"guardduty", "list-findings",
"--detector-id", detector_id,
"--finding-criteria", json.dumps(criteria),
])
finding_ids = result.get("FindingIds", [])
if not finding_ids:
return {"detector_id": detector_id, "findings": [], "count": 0}
details = aws_cli([
"guardduty", "get-findings",
"--detector-id", detector_id,
"--finding-ids"] + finding_ids[:25]
)
findings = []
for f in details.get("Findings", []):
resource = f.get("Resource", {})
instance = resource.get("InstanceDetails", {})
findings.append({
"id": f.get("Id"),
"type": f.get("Type"),
"severity": f.get("Severity"),
"title": f.get("Title"),
"instance_id": instance.get("InstanceId"),
"instance_type": instance.get("InstanceType"),
"region": f.get("Region"),
"updated_at": f.get("UpdatedAt"),
})
return {"detector_id": detector_id, "count": len(findings), "findings": findings}
def check_ec2_cpu_anomalies(threshold_percent=90):
"""Find EC2 instances with sustained high CPU (potential mining)."""
result = aws_cli([
"cloudwatch", "get-metric-data",
"--metric-data-queries", json.dumps([{
"Id": "cpu",
"MetricStat": {
"Metric": {
"Namespace": "AWS/EC2",
"MetricName": "CPUUtilization",
},
"Period": 3600,
"Stat": "Average",
},
}]),
"--start-time", (datetime.utcnow().replace(hour=0, minute=0, second=0)).isoformat() + "Z",
"--end-time", datetime.utcnow().isoformat() + "Z",
])
return result
def check_cost_anomalies():
"""Check for cost anomaly detections that may indicate mining."""
result = aws_cli([
"ce", "get-anomalies",
"--date-interval", json.dumps({
"StartDate": datetime.utcnow().strftime("%Y-%m-01"),
"EndDate": datetime.utcnow().strftime("%Y-%m-%d"),
}),
])
return result
def check_vpc_flow_mining_ports(log_group="/aws/vpc/flowlogs"):
"""Query CloudWatch Logs for connections to known mining pool ports."""
ports_filter = " || ".join([f"dstport = {p}" for p in MINING_POOL_PORTS])
query = f'fields @timestamp, srcaddr, dstaddr, dstport, action | filter ({ports_filter}) | sort @timestamp desc | limit 50'
result = aws_cli([
"logs", "start-query",
"--log-group-name", log_group,
"--start-time", str(int((datetime.utcnow().replace(hour=0)).timestamp())),
"--end-time", str(int(datetime.utcnow().timestamp())),
"--query-string", query,
])
return result
def terminate_mining_instance(instance_id):
"""Terminate a confirmed cryptomining EC2 instance."""
result = aws_cli(["ec2", "terminate-instances", "--instance-ids", instance_id])
return {
"action": "terminate_instance",
"instance_id": instance_id,
"result": result,
"timestamp": datetime.utcnow().isoformat() + "Z",
}
def generate_report():
"""Generate a comprehensive cryptomining detection report."""
return {
"timestamp": datetime.utcnow().isoformat() + "Z",
"guardduty_findings": list_crypto_findings(),
"cost_anomalies": check_cost_anomalies(),
}
if __name__ == "__main__":
action = sys.argv[1] if len(sys.argv) > 1 else "report"
if action == "report":
print(json.dumps(generate_report(), indent=2, default=str))
elif action == "findings":
print(json.dumps(list_crypto_findings(), indent=2, default=str))
elif action == "costs":
print(json.dumps(check_cost_anomalies(), indent=2, default=str))
elif action == "flow-logs":
lg = sys.argv[2] if len(sys.argv) > 2 else "/aws/vpc/flowlogs"
print(json.dumps(check_vpc_flow_mining_ports(lg), indent=2, default=str))
elif action == "terminate" and len(sys.argv) > 2:
print(json.dumps(terminate_mining_instance(sys.argv[2]), indent=2, default=str))
else:
print("Usage: agent.py [report|findings|costs|flow-logs [log-group]|terminate <instance-id>]")