AWS - IAM, Identity Center & SSO Enum

Tip

Impara & pratica AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Impara & pratica GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
Impara & pratica Az Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Sostieni HackTricks

IAM

Puoi trovare una descrizione di IAM in:

AWS - Basic Information

Enumerazione

Permessi principali necessari:

  • iam:ListPolicies, iam:GetPolicy and iam:GetPolicyVersion
  • iam:ListRoles
  • iam:ListUsers
  • iam:ListGroups
  • iam:ListGroupsForUser
  • iam:ListAttachedUserPolicies
  • iam:ListAttachedRolePolicies
  • iam:ListAttachedGroupPolicies
  • iam:ListUserPolicies and iam:GetUserPolicy
  • iam:ListGroupPolicies and iam:GetGroupPolicy
  • iam:ListRolePolicies and iam:GetRolePolicy
# All IAMs
## Retrieves  information about all IAM users, groups, roles, and policies
## in your Amazon Web Services account, including their relationships  to
## one another. Use this operation to obtain a snapshot of the configura-
## tion of IAM permissions (users, groups, roles, and  policies)  in  your
## account.
aws iam get-account-authorization-details

# List users
aws iam get-user #Get current user information
aws iam list-users
aws iam list-ssh-public-keys #User keys for CodeCommit
aws iam get-ssh-public-key --user-name <username> --ssh-public-key-id <id> --encoding SSH #Get public key with metadata
aws iam list-service-specific-credentials #Get special permissions of the IAM user over specific services
aws iam get-user --user-name <username> #Get metadata of user, included permissions boundaries
aws iam list-access-keys #List created access keys
## inline policies
aws iam list-user-policies --user-name <username> #Get inline policies of the user
aws iam get-user-policy --user-name <username> --policy-name <policyname> #Get inline policy details
## attached policies
aws iam list-attached-user-policies --user-name <username> #Get policies of user, it doesn't get inline policies

# List groups
aws iam list-groups #Get groups
aws iam list-groups-for-user --user-name <username> #Get groups of a user
aws iam get-group --group-name <name> #Get group name info
## inline policies
aws iam list-group-policies --group-name <username> #Get inline policies of the group
aws iam get-group-policy --group-name <username> --policy-name <policyname> #Get an inline policy info
## attached policies
aws iam list-attached-group-policies --group-name <name> #Get policies of group, it doesn't get inline policies

# List roles
aws iam list-roles #Get roles
aws iam get-role --role-name <role-name> #Get role
## inline policies
aws iam list-role-policies --role-name <name> #Get inline policies of a role
aws iam get-role-policy --role-name <name> --policy-name <name> #Get inline policy details
## attached policies
aws iam list-attached-role-policies --role-name <role-name> #Get policies of role, it doesn't get inline policies

# List policies
aws iam list-policies [--only-attached] [--scope Local]
aws iam list-policies-granting-service-access --arn <identity> --service-namespaces <svc> # Get list of policies that give access to the user to the service
## Get policy content
aws iam get-policy --policy-arn <policy_arn>
aws iam list-policy-versions --policy-arn <arn>
aws iam get-policy-version --policy-arn <arn:aws:iam::975426262029:policy/list_apigateways> --version-id <VERSION_X>

# Enumerate providers
aws iam list-saml-providers
aws iam get-saml-provider --saml-provider-arn <ARN>
aws iam list-open-id-connect-providers
aws iam get-open-id-connect-provider --open-id-connect-provider-arn <ARN>

# Password Policy
aws iam get-account-password-policy

# MFA
aws iam list-mfa-devices
aws iam list-virtual-mfa-devices

Conferma discreta dei permessi tramite fallimenti intenzionali

Quando List* o le API del simulatore sono bloccate, puoi confermare i permessi che effettuano modifiche senza creare risorse durature forzando errori di validazione prevedibili. AWS valuta comunque IAM prima di restituire questi errori, quindi vedere l’errore dimostra che il chiamante possiede l’azione:

# Confirm iam:CreateUser without creating a new principal (fails only after authz)
aws iam create-user --user-name <existing_user>  # -> EntityAlreadyExistsException

# Confirm iam:CreateLoginProfile while learning password policy requirements
aws iam create-login-profile --user-name <target_user> --password lower --password-reset-required  # -> PasswordPolicyViolationException

Questi tentativi generano comunque eventi CloudTrail (con errorCode impostato) ma evitano di lasciare nuovi artefatti IAM, rendendoli utili per la validazione dei permessi a basso rumore durante la recon interattiva.

Permissions Brute Force

Se sei interessato ai tuoi permessi ma non hai accesso per interrogare IAM, puoi sempre eseguire un brute-force su di essi.

bf-aws-permissions

Lo strumento bf-aws-permissions è semplicemente uno script bash che, usando il profilo indicato, eseguirà tutte le azioni list*, describe*, get* che riesce a trovare tramite i messaggi di help del cli aws e restituirà le esecuzioni riuscite.

# Bruteforce permissions
bash bf-aws-permissions.sh -p default > /tmp/bf-permissions-verbose.txt

bf-aws-perms-simulate

Lo strumento bf-aws-perms-simulate può trovare i permessi correnti (o quelli di altri principals) se hai il permesso iam:SimulatePrincipalPolicy

# Ask for permissions
python3 aws_permissions_checker.py --profile <AWS_PROFILE> [--arn <USER_ARN>]

Perms2ManagedPolicies

Se hai trovato alcuni permessi che il tuo utente possiede, e pensi che vengano concessi da un ruolo gestito AWS (e non da uno personalizzato). Puoi usare lo strumento aws-Perms2ManagedRoles per controllare tutti i ruoli gestiti AWS che concedono i permessi che hai scoperto di avere.

# Run example with my profile
python3 aws-Perms2ManagedPolicies.py --profile myadmin --permissions-file example-permissions.txt

Warning

È possibile “capire” se le autorizzazioni che hai sono concesse da un ruolo gestito da AWS se, ad esempio, noti che hai permessi su servizi che non vengono utilizzati.

Cloudtrail2IAM

CloudTrail2IAM è uno strumento Python che analizza i log di AWS CloudTrail per estrarre e riassumere le azioni eseguite da tutti o solo da uno specifico utente o ruolo. Lo strumento analizzerà ogni log di CloudTrail dal bucket indicato.

git clone https://github.com/carlospolop/Cloudtrail2IAM
cd Cloudtrail2IAM
pip install -r requirements.txt
python3 cloudtrail2IAM.py --prefix PREFIX --bucket_name BUCKET_NAME --profile PROFILE [--filter-name FILTER_NAME] [--threads THREADS]

Warning

Se trovi .tfstate (Terraform state files) o CloudFormation files (di solito file yaml situati all’interno di un bucket con il prefisso cf-templates), puoi anche leggerli per trovare la configurazione aws e scoprire a chi sono state assegnate quali autorizzazioni.

enumerate-iam

To use the tool https://github.com/andresriancho/enumerate-iam you first need to download all the API AWS endpoints, from those the script generate_bruteforce_tests.py will get all the “list_”, “describe_”, and “get_” endpoints. And finally, it will try to access them with the given credentials and indicate if it worked.

(Nella mia esperienza lo strumento si blocca a un certo punto, checkout this fix per provare a risolvere).

Warning

Nella mia esperienza questo strumento è simile al precedente ma funziona peggio e controlla meno autorizzazioni

# Install tool
git clone git@github.com:andresriancho/enumerate-iam.git
cd enumerate-iam/
pip install -r requirements.txt

# Download API endpoints
cd enumerate_iam/
git clone https://github.com/aws/aws-sdk-js.git
python3 generate_bruteforce_tests.py
rm -rf aws-sdk-js
cd ..

# Enumerate permissions
python3 enumerate-iam.py --access-key ACCESS_KEY --secret-key SECRET_KEY [--session-token SESSION_TOKEN] [--region REGION]

weirdAAL

Puoi anche usare lo strumento weirdAAL. Questo strumento verificherà diverse operazioni comuni su diversi servizi comuni (controllerà alcuni permessi di enumeration e anche alcuni permessi di privesc). Ma controllerà solo i controlli codificati (l’unico modo per verificare più cose è scrivere altri test).

# Install
git clone https://github.com/carnal0wnage/weirdAAL.git
cd weirdAAL
python3 -m venv weirdAAL
source weirdAAL/bin/activate
pip3 install -r requirements.txt

# Create a .env file with aws credentials such as
[default]
aws_access_key_id = <insert key id>
aws_secret_access_key = <insert secret key>

# Setup DB
python3 create_dbs.py

# Invoke it
python3 weirdAAL.py -m ec2_describe_instances -t ec2test # Just some ec2 tests
python3 weirdAAL.py -m recon_all -t MyTarget # Check all permissions
# You will see output such as:
# [+] elbv2 Actions allowed are [+]
# ['DescribeLoadBalancers', 'DescribeAccountLimits', 'DescribeTargetGroups']

Strumenti di hardening per i permessi BF

# Export env variables
./index.js --console=text --config ./config.js --json /tmp/out-cloudsploit.json

# Filter results removing unknown
jq 'map(select(.status | contains("UNKNOWN") | not))' /tmp/out-cloudsploit.json | jq 'map(select(.resource | contains("N/A") | not))' > /tmp/out-cloudsploit-filt.json

# Get services by regions
jq 'group_by(.region) | map({(.[0].region): ([map((.resource | split(":"))[2]) | unique])})' ~/Desktop/pentests/cere/greybox/core-dev-dev-cloudsploit-filtered.json

<YourTool>

Nessuno dei precedenti strumenti è in grado di controllare quasi tutte le autorizzazioni; se conosci uno strumento migliore, invia una PR!

Unauthenticated Access

AWS - IAM & STS Unauthenticated Enum

Privilege Escalation

Nella pagina seguente puoi vedere come abusare dei permessi IAM per effettuare una Privilege Escalation:

AWS - IAM Privesc

IAM Post Exploitation

AWS - IAM Post Exploitation

IAM Persistence

AWS - IAM Persistence

IAM Identity Center

Puoi trovare una descrizione di IAM Identity Center in:

AWS - Basic Information

Connect via SSO with CLI

# Connect with sso via CLI aws configure sso
aws configure sso

[profile profile_name]
sso_start_url = https://subdomain.awsapps.com/start/
sso_account_id = <account_numbre>
sso_role_name = AdministratorAccess
sso_region = us-east-1

Enumerazione

Gli elementi principali dell’Identity Center sono:

  • Utenti e gruppi
  • Permission Sets: hanno policy associate
  • AWS Accounts

Poi vengono create relazioni in cui utenti/gruppi hanno Permission Sets su AWS Accounts.

Note

Nota che ci sono 3 modi per allegare policy a un Permission Set: allegare AWS managed policies, Customer managed policies (queste policy devono essere create in tutti gli account che il Permission Set interessa), e inline policies (definite al suo interno).

# Check if IAM Identity Center is used
aws sso-admin list-instances

# Get Permissions sets. These are the policies that can be assigned
aws sso-admin list-permission-sets --instance-arn <instance-arn>
aws sso-admin describe-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn>

## Get managed policies of a permission set
aws sso-admin list-managed-policies-in-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn>
## Get inline policies of a permission set
aws sso-admin get-inline-policy-for-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn>
## Get customer managed policies of a permission set
aws sso-admin list-customer-managed-policy-references-in-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn>
## Get boundaries of a permission set
aws sso-admin get-permissions-boundary-for-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn>

## List accounts a permission set is affecting
aws sso-admin list-accounts-for-provisioned-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn>
## List principals given a permission set in an account
aws sso-admin list-account-assignments --instance-arn <instance-arn> --permission-set-arn <perm-set-arn> --account-id <account_id>

# Get permissions sets affecting an account
aws sso-admin list-permission-sets-provisioned-to-account --instance-arn <instance-arn> --account-id <account_id>

# List users & groups from the identity store
aws identitystore list-users --identity-store-id <store-id>
aws identitystore list-groups --identity-store-id <store-id>
## Get members of groups
aws identitystore list-group-memberships --identity-store-id <store-id> --group-id <group-id>
## Get memberships or a user or a group
aws identitystore list-group-memberships-for-member --identity-store-id <store-id> --member-id <member-id>

Enumerazione locale

È possibile creare all’interno della cartella $HOME/.aws il file config per configurare profili accessibili tramite SSO, ad esempio:

[default]
region = us-west-2
output = json

[profile my-sso-profile]
sso_start_url = https://my-sso-portal.awsapps.com/start
sso_region = us-west-2
sso_account_id = 123456789012
sso_role_name = MySSORole
region = us-west-2
output = json

[profile dependent-profile]
role_arn = arn:aws:iam::<acc-id>:role/ReadOnlyRole
source_profile = Hacktricks-Admin

Questa configurazione può essere utilizzata con i comandi:

# Login in ms-sso-profile
aws sso login --profile my-sso-profile
# Use dependent-profile
aws s3 ls --profile dependent-profile

Quando viene utilizzato un profilo SSO per accedere ad alcune informazioni, le credenziali vengono memorizzate nella cache in un file all’interno della cartella $HOME/.aws/sso/cache. Di conseguenza possono essere lette e utilizzate da lì.

Inoltre, altre credenziali possono essere memorizzate nella cartella $HOME/.aws/cli/cache. Questa directory di cache è utilizzata principalmente quando stai lavorando con profili AWS CLI che usano credenziali utente IAM o assumono ruoli tramite IAM (senza SSO). Esempio di configurazione:

[profile crossaccountrole]
role_arn = arn:aws:iam::234567890123:role/SomeRole
source_profile = default
mfa_serial = arn:aws:iam::123456789012:mfa/saanvi
external_id = 123456

Accesso non autenticato

AWS - Identity Center & SSO Unauthenticated Enum

Escalation dei privilegi

AWS - SSO & identitystore Privesc

Post-exploitation

AWS - SSO & identitystore Post Exploitation

Persistenza

Crea un utente e assegnagli i permessi

# Create user identitystore:CreateUser
aws identitystore create-user --identity-store-id <store-id> --user-name privesc --display-name privesc --emails Value=sdkabflvwsljyclpma@tmmbt.net,Type=Work,Primary=True --name Formatted=privesc,FamilyName=privesc,GivenName=privesc
## After creating it try to login in the console using the selected username, you will receive an email with the code and then you will be able to select a password
  • Crea un gruppo, assegnagli i permessi e imposta su di esso un utente controllato
  • Assegna permessi aggiuntivi a un utente controllato o a un gruppo
  • Per impostazione predefinita, solo gli utenti con permessi del Management Account potranno accedere e controllare l’IAM Identity Center.

Tuttavia, è possibile, tramite Delegate Administrator, consentire agli utenti di un account diverso di gestirlo. Non avranno esattamente le stesse autorizzazioni, ma potranno eseguire attività di gestione.

Tip

Impara & pratica AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Impara & pratica GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
Impara & pratica Az Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Sostieni HackTricks