AWS - IAM, Identity Center & SSO 열거

Tip

AWS 해킹 학습 및 실습:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 학습 및 실습: HackTricks Training GCP Red Team Expert (GRTE)
Az 해킹 학습 및 실습: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기

IAM

다음에서 IAM 설명을 찾을 수 있습니다:

AWS - Basic Information

열거

필요한 주요 권한:

  • 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

의도적 실패를 통한 스텔스 권한 확인

When List* or simulator APIs are blocked, you can 변경 권한(mutating permissions)을 영구 리소스를 생성하지 않고 확인할 수 있습니다 by forcing predictable validation errors. AWS still evaluates IAM before returning these errors, so seeing the error proves the caller has the action:

# 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

These attempts still generate CloudTrail events (with errorCode set) but avoid leaving new IAM artifacts, making them useful for 저소음 권한 검증 during interactive recon.

Permissions Brute Force

If you are interested in your own permissions but you don’t have access to query IAM you could always brute-force them.

bf-aws-permissions

The tool bf-aws-permissions is just a bash script that will run using the indicated profile all the list*, describe*, get* actions it can find using aws cli help messages and 성공적으로 실행된 항목들을 반환합니다.

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

bf-aws-perms-simulate

도구 bf-aws-perms-simulate는 현재 당신의 권한(또는 다른 principals의 권한)을 확인할 수 있습니다. 단, iam:SimulatePrincipalPolicy 권한이 있어야 합니다.

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

Perms2ManagedPolicies

만약 당신의 사용자에게 부여된 일부 권한을 발견했고, 그것들이 AWS 관리형 역할(커스텀 역할이 아니라)에 의해 부여된 것이라고 생각한다면, aws-Perms2ManagedRoles 도구를 사용해 당신이 발견한 권한들을 부여하는 모든 AWS 관리형 역할을 확인할 수 있습니다.

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

Warning

예를 들어 사용하지 않는 서비스에 대한 권한을 가지고 있는지 보면 해당 권한이 AWS 관리형 역할에 의해 부여된 것인지 “알 수” 있습니다.

Cloudtrail2IAM

CloudTrail2IAM 는 모든 사용자 또는 특정 사용자나 역할이 수행한 작업을 추출하고 요약하기 위해 AWS CloudTrail 로그를 분석하는 Python 도구입니다. 이 도구는 지정된 버킷의 모든 cloudtrail 로그를 파싱합니다.

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

.tfstate (Terraform state files) 또는 CloudFormation 파일(일반적으로 cf-templates 접두사가 붙은 버킷 안에 있는 yaml 파일)을 발견하면, 해당 파일을 읽어 aws 구성과 누가 어떤 권한을 할당받았는지 확인할 수 있습니다.

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.

(In my experience the 도구가 어느 시점에서 멈춥니다, checkout this fix 문제를 해결하려고 시도해 보세요).

Warning

제 경험상 이 도구는 이전 도구와 비슷하지만 성능이 더 안 좋고 검사하는 권한이 더 적습니다

# 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

도구 weirdAAL를 사용할 수도 있습니다. 이 도구는 여러 일반적인 서비스에서의 여러 일반적인 작업을 검사합니다 (일부 enumeration 권한과 일부 privesc 권한도 검사합니다). 하지만 코딩된 검사만 수행하므로, 더 많은 항목을 검사하려면 더 많은 테스트를 코딩해야 합니다.

# 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']

BF permissions 강화를 위한 하드닝 도구

# 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>

앞의 도구들은 모든 권한을 거의 다 검사할 수 없습니다. 더 나은 도구를 알고 있다면 PR을 보내주세요!

Unauthenticated Access

AWS - IAM & STS Unauthenticated Enum

Privilege Escalation

다음 페이지에서 abuse IAM permissions to escalate privileges 방법을 확인할 수 있습니다:

AWS - IAM Privesc

IAM Post Exploitation

AWS - IAM Post Exploitation

IAM Persistence

AWS - IAM Persistence

IAM Identity Center

IAM Identity Center에 대한 설명은 다음에서 확인할 수 있습니다:

AWS - Basic Information

CLI로 SSO에 연결

# 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

열거

Identity Center의 주요 요소는 다음과 같습니다:

  • 사용자 및 그룹
  • Permission Sets: 정책이 연결됨
  • AWS Accounts

그런 다음 사용자/그룹이 특정 AWS Accounts에 대해 Permission Sets를 갖도록 관계가 생성됩니다.

Note

Permission Set에 정책을 연결하는 방법은 세 가지가 있습니다. AWS managed policies를 연결하는 방법, Customer managed policies(이 정책들은 Permission Set가 적용되는 모든 AWS Accounts에서 생성되어야 합니다), 그리고 inline policies(그 안에 정의됨).

# 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>

로컬 열거

예를 들어, $HOME/.aws 폴더 안에 config 파일을 생성하여 SSO로 접근 가능한 프로파일들을 구성할 수 있습니다:

[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

이 구성은 다음 명령어들과 함께 사용할 수 있습니다:

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

정보에 접근하기 위해 SSO 프로필이 사용될 때, 자격 증명은 $HOME/.aws/sso/cache 폴더 안의 파일에 캐시됩니다. 따라서 해당 파일에서 읽어와 사용할 수 있습니다.

또한 추가 자격 증명$HOME/.aws/cli/cache 폴더에 저장될 수 있습니다. 이 캐시 디렉터리는 주로 AWS CLI 프로필에서 IAM 사용자 자격 증명을 사용하거나 IAM을 통해 assume 역할(SSO 없이)할 때 사용됩니다. 설정 예:

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

인증되지 않은 액세스

AWS - Identity Center & SSO Unauthenticated Enum

권한 상승

AWS - SSO & identitystore Privesc

사후 활동

AWS - SSO & identitystore Post Exploitation

지속성

사용자를 생성하고 권한을 할당

# 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
  • 그룹을 생성하고 권한을 할당한 뒤 해당 그룹에 제어된 사용자를 설정합니다
  • 제어된 사용자 또는 그룹에 추가 권한을 부여합니다
  • 기본적으로, Management Account의 권한을 가진 사용자만 IAM Identity Center에 접근하고 제어할 수 있습니다.

그러나 Delegate Administrator를 통해 다른 계정의 사용자가 이를 관리하도록 허용할 수 있습니다. 그들이 정확히 동일한 권한을 가지지는 않지만, management activities를 수행할 수 있게 됩니다.

Tip

AWS 해킹 학습 및 실습:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 학습 및 실습: HackTricks Training GCP Red Team Expert (GRTE)
Az 해킹 학습 및 실습: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기