AWS - EC2, EBS, ELB, SSM, VPC & VPN Перерахування

Tip

Вивчайте та практикуйте AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Вивчайте та практикуйте GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
Вивчайте та практикуйте Az Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Підтримайте HackTricks

VPC & Мережі

Дізнайтеся, що таке VPC та про його компоненти у:

AWS - VPC & Networking Basic Information

EC2

Amazon EC2 використовується для запуску віртуальних серверів. Воно дозволяє налаштовувати безпеку, мережеві параметри та керувати зберіганням. Гнучкість Amazon EC2 проявляється в його здатності масштабувати ресурси вгору та вниз, ефективно адаптуючись до змін вимог або пікової популярності. Ця можливість зменшує потребу точно прогнозувати трафік.

Цікаві об’єкти для перерахування в EC2:

  • Віртуальні машини
  • SSH Keys
  • User Data
  • Існуючі EC2s/AMIs/Snapshots
  • Networking
  • Мережі
  • Підмережі
  • Публічні IP
  • Відкриті порти
  • Інтегровані підключення з іншими мережами поза AWS

Профілі інстансів

Використання ролей для надання дозволів додаткам, що працюють на EC2 інстансах, вимагає трохи додаткової конфігурації. Додаток, що працює на EC2 інстансі, відокремлений від AWS віртуалізованою операційною системою. Через це додаткового рівня відокремлення потрібно зробити ще один крок, щоб призначити роль AWS та її пов’язані дозволи EC2 інстансу і зробити їх доступними для додатків.

Цим додатковим кроком є створення профілю інстансу, прикріпленого до інстансу. Профіль інстансу містить роль і може надати тимчасові облікові дані цієї ролі додатку, що працює на інстансі. Ці тимчасові облікові дані потім можуть використовуватися в API-викликах додатку для доступу до ресурсів і для обмеження доступу лише до тих ресурсів, які вказує роль. Зауважте, що лише одна роль може бути призначена EC2 інстансу одночасно, і всі додатки на інстансі використовують ту саму роль і дозволи.

Endpoint метаданих

Метадані AWS EC2 — це інформація про інстанс Amazon Elastic Compute Cloud (EC2), доступна інстансу під час виконання. Ці метадані надають відомості про інстанс, такі як його ID інстансу, зона доступності, у якій він працює, IAM роль, пов’язана з інстансом, та ім’я хоста інстансу.

Cloud SSRF - HackTricks

Перерахування

# Get EC2 instances
aws ec2 describe-instances
aws ec2 describe-instance-status #Get status from running instances

# Get user data from each ec2 instance
for instanceid in $(aws ec2 describe-instances --profile <profile> --region us-west-2 | grep -Eo '"i-[a-zA-Z0-9]+' | tr -d '"'); do
echo "Instance ID: $instanceid"
aws ec2 describe-instance-attribute --profile <profile> --region us-west-2 --instance-id "$instanceid" --attribute userData | jq ".UserData.Value" | tr -d '"' | base64 -d
echo ""
echo "-------------------"
done

# Instance profiles
aws iam list-instance-profiles
aws iam list-instance-profiles-for-role --role-name <name>

# Get tags
aws ec2 describe-tags

# Get volumes
aws ec2 describe-volume-status
aws ec2 describe-volumes

# Get snapshots
aws ec2 describe-snapshots --owner-ids self

# Scheduled instances
aws ec2 describe-scheduled-instances

# Get custom images
aws ec2 describe-images --owners self

# Get Elastic IPs
aws ec2 describe-addresses

# Get current output
aws ec2 get-console-output --instance-id [id]

# Get a JPG-format screenshot of a running instance
aws ec2 get-console-screenshot --instance [id]

# Get VPN customer gateways
aws ec2 describe-customer-gateways
aws ec2 describe-vpn-gateways
aws ec2 describe-vpn-connections

# List conversion tasks to upload/download VMs
aws ec2 describe-conversion-tasks
aws ec2 describe-import-image-tasks

# Get Bundle Tasks
aws ec2 describe-bundle-tasks

# Get Classic Instances
aws ec2 describe-classic-link-instances

# Get Dedicated Hosts
aws ec2 describe-hosts

# Get SSH Key Pairs
aws ec2 describe-key-pairs

# Get Internet Gateways
aws ec2 describe-internet-gateways

# Get NAT Gateways
aws ec2 describe-nat-gateways

# Get subnetworks
aws ec2 describe-subnets

# Get FW rules
aws ec2 describe-network-acls

# Get security groups
aws ec2 describe-security-groups

# Get interfaces
aws ec2 describe-network-interfaces

# Get routes table
aws ec2 describe-route-tables

# Get VPCs
aws ec2 describe-vpcs
aws ec2 describe-vpc-peering-connections

Неавторизований доступ

AWS - EC2 Unauthenticated Enum

Privesc

На наступній сторінці ви можете дізнатися, як зловживати дозволами EC2 для підвищення привілеїв:

AWS - EC2 Privesc

Post-Exploitation

AWS - EC2, EBS, SSM & VPC Post Exploitation

EBS

Amazon EBS (Elastic Block Store) snapshots фактично є статичними резервними копіями томів AWS EBS. Іншими словами, це копії дисків, підключених до EC2 Instance у певний момент часу. EBS snapshots можна копіювати між регіонами та акаунтами, або навіть завантажувати й запускати локально.

Snapshots можуть містити чутливу інформацію, таку як вихідний код або APi keys, тому, якщо є можливість, рекомендується їх перевірити.

Різниця AMI & EBS

An AMI is used to launch an EC2 instance, while an EC2 Snapshot is used to backup and recover data stored on an EBS volume. While an EC2 Snapshot can be used to create a new AMI, it is not the same thing as an AMI, and it does not include information about the operating system, application server, or other software required to run an application.

Privesc

На наступній сторінці ви можете дізнатися, як зловживати дозволами EBS для підвищення привілеїв:

AWS - EBS Privesc

SSM

Amazon Simple Systems Manager (SSM) дозволяє віддалено керувати флотом EC2 інстансів, щоб значно спростити їх адміністрування. Кожен з цих інстансів має працювати зі службою SSM Agent — саме ця служба отримуватиме дії та виконуватиме їх через AWS API.

SSM Agent дозволяє Systems Manager оновлювати, керувати та налаштовувати ці ресурси. Аґент обробляє запити від сервісу Systems Manager у AWS Cloud, а потім виконує їх відповідно до вказівок у запиті.

The SSM Agent comes preinstalled in some AMIs or you need to manually install them on the instances. Also, the IAM Role used inside the instance needs to have the policy AmazonEC2RoleforSSM attached to be able to communicate.

Enumeration

aws ssm describe-instance-information
aws ssm describe-parameters
aws ssm describe-sessions --state [Active|History]
aws ssm describe-instance-patches --instance-id <id>
aws ssm describe-instance-patch-states --instance-ids <id>
aws ssm describe-instance-associations-status --instance-id <id>

Ви можете перевірити на інстансі EC2, чи запущений Systems Manager, просто виконавши:

ps aux | grep amazon-ssm

Privesc

На наступній сторінці ви можете дізнатися, як abuse SSM permissions to escalate privileges:

AWS - SSM Privesc

Perssistence

На наступній сторінці ви можете дізнатися, як abuse SSM permissions to achieve persistence:

AWS - SSM Perssitence

ELB

Elastic Load Balancing (ELB) — це сервіс балансування навантаження для розгортань на Amazon Web Services (AWS). ELB автоматично розподіляє вхідний трафік застосунків та масштабує ресурси, щоб задовольнити потреби у трафіку.

# List internet-facing ELBs
aws elb describe-load-balancers
aws elb describe-load-balancers | jq '.LoadBalancerDescriptions[]| select( .Scheme | contains("internet-facing"))|.DNSName'

# DONT FORGET TO CHECK VERSION 2
aws elbv2 describe-load-balancers
aws elbv2 describe-load-balancers | jq '.LoadBalancers[].DNSName'
aws elbv2 describe-listeners --load-balancer-arn <load_balancer_arn>

Launch Templates & Autoscaling Groups

Enumeration

# Launch templates
aws ec2 describe-launch-templates
aws ec2 describe-launch-templates --launch-template-id <launch_template_id>
## Get details, like user data
aws ec2 describe-launch-template-versions --launch-template-id <launch_template_id>

# Autoscaling
aws autoscaling describe-auto-scaling-groups
aws autoscaling describe-auto-scaling-instances
aws autoscaling describe-launch-configurations
aws autoscaling describe-load-balancer-target-groups
aws autoscaling describe-load-balancers

Nitro

AWS Nitro — це сукупність інноваційних технологій, що формують базову платформу для AWS EC2 instances. Запроваджений Amazon для підвищення безпеки, продуктивності та надійності, Nitro використовує кастомні апаратні компоненти та легкий гіпервізор. Він абстрагує велику частину традиційної функціональності віртуалізації до виділеного апаратного та програмного забезпечення, мінімізуючи атакову поверхню та покращуючи ефективність використання ресурсів. Завантажуючи функції віртуалізації, Nitro дозволяє EC2 instances забезпечувати майже bare-metal продуктивність, що робить його особливо корисним для ресурсомістких застосунків. Додатково, Nitro Security Chip спеціально гарантує безпеку апаратного забезпечення та прошивки, ще більше зміцнюючи його надійну архітектуру.

Get more information and how to enumerate it from:

AWS - Nitro Enum

VPN

VPN дозволяє підключати вашу локальну мережу (site-to-site VPN) або ноутбуки працівників (Client VPN) до AWS VPC, щоб сервіси були доступні без необхідності виставляти їх в інтернет.

Основні компоненти AWS VPN

  1. Customer Gateway:
  • A Customer Gateway is a resource that you create in AWS to represent your side of a VPN connection.
  • It is essentially a physical device or software application on your side of the Site-to-Site VPN connection.
  • You provide routing information and the public IP address of your network device (such as a router or a firewall) to AWS to create a Customer Gateway.
  • It serves as a reference point for setting up the VPN connection and doesn’t incur additional charges.
  1. Virtual Private Gateway:
  • A Virtual Private Gateway (VPG) is the VPN concentrator on the Amazon side of the Site-to-Site VPN connection.
  • It is attached to your VPC and serves as the target for your VPN connection.
  • VPG is the AWS side endpoint for the VPN connection.
  • It handles the secure communication between your VPC and your on-premises network.
  1. Site-to-Site VPN Connection:
  • A Site-to-Site VPN connection connects your on-premises network to a VPC through a secure, IPsec VPN tunnel.
  • This type of connection requires a Customer Gateway and a Virtual Private Gateway.
  • It’s used for secure, stable, and consistent communication between your data center or network and your AWS environment.
  • Typically used for regular, long-term connections and is billed based on the amount of data transferred over the connection.
  1. Client VPN Endpoint:
  • A Client VPN endpoint is a resource that you create in AWS to enable and manage client VPN sessions.
  • It is used for allowing individual devices (like laptops, smartphones, etc.) to securely connect to AWS resources or your on-premises network.
  • It differs from Site-to-Site VPN in that it is designed for individual clients rather than connecting entire networks.
  • With Client VPN, each client device uses a VPN client software to establish a secure connection.

You can find more information about the benefits and components of AWS VPNs here.

Enumeration

# VPN endpoints
## Check used subnetwork, authentication, SGs, connected...
aws ec2 describe-client-vpn-endpoints

## Get AWS network info related to the vpn endpoint
aws ec2 describe-client-vpn-target-networks --client-vpn-endpoint-id <id>

## Get AWS subnet & ip range the VPN iconnected to
aws ec2 describe-client-vpn-routes --client-vpn-endpoint-id <id>

## Check authorization rules
aws ec2 describe-client-vpn-authorization-rules --client-vpn-endpoint-id <id>

## Get current connections to the VPN endpoint
aws ec2 describe-client-vpn-connections --client-vpn-endpoint-id <id>

# Get VPN gateways and check with which VPC each is connected
aws ec2 describe-vpn-gateways

# Get VPN site-to-site connections
aws ec2 describe-vpn-connections

Local Enumeration

Local Temporary Credentials

When AWS VPN Client is used to connect to a VPN, the user will usually увійде в AWS to get access to the VPN. Then, some облікові дані AWS створюються та зберігаються локально to establish the VPN connection. These credentials are зберігаються в $HOME/.config/AWSVPNClient/TemporaryCredentials/<region>/temporary-credentials.txt and contains an AccessKey, a SecretKey and a Token.

The credentials belong to the user arn:aws:sts::<acc-id>:assumed-role/aws-vpn-client-metrics-analytics-access-role/CognitoIdentityCredentials (TODO: дослідити більше щодо дозволів цих облікових даних).

opvn config files

If a VPN connection було встановлено you should search for .opvn config files in the system. Moreover, one place where you could find the configurations is in $HOME/.config/AWSVPNClient/OpenVpnConfigs

Post Exploitaiton

AWS - VPN Post Exploitation

References

Tip

Вивчайте та практикуйте AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Вивчайте та практикуйте GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
Вивчайте та практикуйте Az Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Підтримайте HackTricks